// server/cloudflare-worker/src/origin-policy.ts // Shared upstream origin validation helpers for the Cloudflare Edge Worker. const IPV4_PATTERN = /^\d{1,3}(?:\.\d{1,3}){3}$/ const INTEGER_OR_HEX_HOST_PATTERN = /^(?:0x[\da-f]+|\d+)$/i const BLOCKED_HOST_SUFFIXES = ['.localhost', '.local', '.internal', '.home.arpa', '.localdomain'] export function hasSmuggledRequestPath(pathname: string): boolean { return pathname.startsWith('//') || pathname.includes('\\') } export function isDisallowedPublicHost(rawHostname: string): boolean { const trimmed = rawHostname.trim().toLowerCase() if (!trimmed || trimmed.endsWith('.')) return true if (trimmed === 'localhost') return true if (BLOCKED_HOST_SUFFIXES.some((suffix) => trimmed.endsWith(suffix))) return true if (trimmed.startsWith('[') || trimmed.includes(':')) return true if (IPV4_PATTERN.test(trimmed) || INTEGER_OR_HEX_HOST_PATTERN.test(trimmed)) return true if (!trimmed.includes('.')) return true return false } /** * Validates that a configured upstream origin is strictly a clean `https://` public hostname * with no credentials, path prefix, query string, fragment, or IP/internal literal. * Prevents Cloudflare Error 1003 ("Direct IP access not allowed") and internal SSRF. */ export function parsePublicHttpsOrigin(rawOrigin: string): URL | null { let originUrl: URL try { originUrl = new URL(rawOrigin.trim()) } catch { return null } if (originUrl.protocol !== 'https:' || originUrl.username || originUrl.password) { return null } if (originUrl.pathname !== '/' || originUrl.search !== '' || originUrl.hash !== '') { return null } if (isDisallowedPublicHost(originUrl.hostname)) { return null } return originUrl }