import { isValidHostLabel } from "@/worker/auth/host-labels"; import type { HostInfo } from "@/worker/types"; function stripPort(host: string): string { if (host.startsWith("[")) { const end = host.indexOf("]"); return end === -1 ? host : host.slice(0, end + 1); } const colon = host.lastIndexOf(":"); if (colon === -1) return host; return host.slice(0, colon); } export function normalizeHostHeader(hostHeader: string | null): string { if (!hostHeader) return ""; const withoutPort = stripPort(hostHeader.trim()); const withoutTrailingDot = withoutPort.endsWith(".") ? withoutPort.slice(0, -1) : withoutPort; return withoutTrailingDot.toLowerCase(); } export function classifyHost(request: Request, env: Env): HostInfo { const controlPlaneHost = env.CONTROL_PLANE_HOST.toLowerCase(); const subjectHostSuffix = env.SUBJECT_HOST_SUFFIX.toLowerCase(); const originalHost = request.headers.get("host") ?? new URL(request.url).host; const normalizedHost = normalizeHostHeader(originalHost); if (normalizedHost === controlPlaneHost) { return { kind: "control", originalHost, normalizedHost, controlPlaneHost, subjectHostSuffix, }; } if (normalizedHost.endsWith(subjectHostSuffix)) { const hostLabel = normalizedHost.slice(0, -subjectHostSuffix.length); if (isValidHostLabel(hostLabel)) { return { kind: "subject", originalHost, normalizedHost, controlPlaneHost, subjectHostSuffix, hostLabel, }; } } return { kind: "unknown", originalHost, normalizedHost, controlPlaneHost, subjectHostSuffix, }; }