isLocalhost no longer throws if URL is invalid

This commit is contained in:
Konstantin Wohlwend 2024-11-22 18:28:36 +01:00
parent 11947d6732
commit 3b40cfc860

View File

@ -1,7 +1,16 @@
import { generateSecureRandomString } from "./crypto";
export function createUrlIfValid(...args: ConstructorParameters<typeof URL>) {
try {
return new URL(...args);
} catch (e) {
return null;
}
}
export function isLocalhost(urlOrString: string | URL) {
const url = new URL(urlOrString);
const url = createUrlIfValid(urlOrString);
if (!url) return false;
if (url.hostname === "localhost" || url.hostname.endsWith(".localhost")) return true;
if (url.hostname.match(/^127\.\d+\.\d+\.\d+$/)) return true;
return false;
@ -9,7 +18,8 @@ export function isLocalhost(urlOrString: string | URL) {
export function isRelative(url: string) {
const randomDomain = `${generateSecureRandomString()}.stack-auth.example.com`;
const u = new URL(url, `https://${randomDomain}`);
const u = createUrlIfValid(url, `https://${randomDomain}`);
if (!u) return false;
if (u.host !== randomDomain) return false;
if (u.protocol !== "https:") return false;
return true;