fix: harden token and URL handling

* fix: harden token and URL handling

* test: restore full web test suite

---------

Co-authored-by: batumilove <batumilove@users.noreply.github.com>
This commit is contained in:
batumilove
2026-05-28 05:31:46 +04:00
committed by Offending Commit
parent 6960bf4ffe
commit 5cfbae6248
11 changed files with 152 additions and 14 deletions

View File

@@ -0,0 +1,38 @@
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "[::1]", "0.0.0.0"]);
function parseUrl(value: string): URL | null {
try {
return new URL(value);
} catch {
return null;
}
}
export function isLoopbackUrl(value: string): boolean {
const parsed = parseUrl(value);
if (!parsed) return false;
return LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase());
}
export function isHttpOrHttpsUrl(value: string): boolean {
const parsed = parseUrl(value);
return parsed?.protocol === "https:" || parsed?.protocol === "http:";
}
export function isSafeExternalUrl(value: string): boolean {
const parsed = parseUrl(value);
return parsed?.protocol === "https:" || parsed?.protocol === "http:";
}
export function isSecureTokenTransport(baseUrl: string): boolean {
const parsed = parseUrl(baseUrl);
if (!parsed) return false;
if (parsed.protocol === "https:") return true;
if (parsed.protocol === "http:" && LOOPBACK_HOSTS.has(parsed.hostname.toLowerCase())) return true;
return false;
}
export function tokenTransportError(baseUrl: string): string | null {
if (isSecureTokenTransport(baseUrl)) return null;
return "API tokens require HTTPS unless connecting to localhost.";
}