// harden-portal-requests (F29): SameSite=Lax alone lets any *.babyboo.my page drive this portal's API with the // viewer's cookie, because sibling subdomains are "same-site". A state-changing API request must therefore come // from this portal's own origin. Runs in the middleware (edge runtime): no Node APIs. const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]); /** * True when an unsafe-method request was sent by a browser from another origin. * * - `Sec-Fetch-Site` (set by the browser, not by scripts) wins: only `same-origin` passes. * - Without it, the `Origin` host must equal the request host (`X-Forwarded-Host` from the ingress, else `Host`). * - With neither header the caller is not a browser (server-to-server, CLI), so CSRF does not apply. */ export function isCrossSiteWrite(method: string, headers: Headers): boolean { if (SAFE_METHODS.has(method.toUpperCase())) return false; const site = headers.get("sec-fetch-site"); if (site !== null) return site !== "same-origin"; const origin = headers.get("origin"); if (origin === null) return false; const host = (headers.get("x-forwarded-host") ?? headers.get("host") ?? "").split(",")[0].trim().toLowerCase(); if (!host) return true; try { const from = new URL(origin); // Parse the request host with the Origin's scheme so a default port (":443" from the ingress) normalises away. return from.host.toLowerCase() !== new URL(`${from.protocol}//${host}`).host.toLowerCase(); } catch { return true; // "null" (opaque origin) or garbage } }