/** Checks HTTP basic auth against the AUTH_USER / AUTH_PASS secrets. Fails closed if unset. */ export async function isAuthorized(req: Request, env: Env): Promise { if (!env.AUTH_USER || !env.AUTH_PASS) return false; const header = req.headers.get("authorization") ?? ""; const match = header.match(/^Basic\s+(.+)$/i); if (!match) return false; let supplied: string; try { supplied = atob(match[1]); } catch { return false; } // Compare fixed-length digests so timingSafeEqual never sees mismatched lengths. const [a, b] = await Promise.all([digest(supplied), digest(`${env.AUTH_USER}:${env.AUTH_PASS}`)]); return crypto.subtle.timingSafeEqual(a, b); } async function digest(s: string): Promise { return crypto.subtle.digest("SHA-256", new TextEncoder().encode(s)); } export function unauthorized(): Response { return new Response("Authentication required", { status: 401, headers: { "www-authenticate": 'Basic realm="monitor", charset="UTF-8"' }, }); }