Files
co-lite/solvway-admin-portal/app/lib/sameOrigin.ts
ngqileandClaude Opus 5.5 1071ddaa2a feat(admin-portal): cut babyboo portal down to Co-Lite login, users and roles
Removes every other screen, API route, component, test and the dependencies only
they used. Cookie colite_admin, Co-Lite branding, BO_USERS/BO_ROLES modules only.
The user form no longer loads branches, events or country scope.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 21:24:30 +08:00

33 lines
1.5 KiB
TypeScript

// harden-portal-requests (F29): SameSite=Lax alone lets any sibling-subdomain 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
}
}