116e0468b0
phase-2 security baseline the main.ts placeholder has been
advertising since the auth track started. three independent
middlewares + their spa counterparts shipped together because
they only become meaningful as a set.
helmet on the bff:
helmet() with three overrides matching our specific shape:
- HSTS only in production (dev runs on plain http)
- crossOriginResourcePolicy: 'cross-origin' (SPA needs to read
bff json from a different origin)
- CSP disabled in non-prod (bff doesn't render html; default CSP
just adds devtools noise)
cors allowlist env-driven:
CORS_ALLOWED_ORIGINS is now mandatory at boot. readCorsAllowlist()
parses + validates (http(s) only, bare origins, no path/query),
same boot-time validator family as assertSessionSecret etc. the
previous hardcoded localhost fallback is removed — silent
cors misconfiguration is exactly the "works in dev breaks in
prod" trap this guard catches.
double-submit CSRF (session-bound):
- bff mints a 256-bit csrfToken at /auth/callback, stored on
req.session.csrfToken AND mirrored to a js-readable cookie
(__Host-portal_csrf prod / portal_csrf dev). cookie is the
spa's read-only view; session is the source of truth.
- createCsrfMiddleware compares X-CSRF-Token header to the
session token via crypto.timingSafeEqual. skips: safe methods,
anonymous requests, /auth/login + /auth/callback.
- mismatch → 403 {"error":"csrf"} + structured pino warn.
- spa csrfInterceptor reads the cookie via document.cookie and
copies into X-CSRF-Token on mutating bff requests. omitted on
GET/HEAD/OPTIONS and on non-bff origins.
- logout + absolute-timeout middleware now clear the csrf cookie
alongside the session cookie.
notable choices:
- session-bound double-submit, not pure cookie-vs-header. an
attacker who plants a cookie via subdomain takeover would
still need to know the server-side session token. tying the
check to req.session.csrfToken instead of the cookie itself
is what makes this stronger than the canonical recipe.
- csrfInterceptor sits between bffCredentialsInterceptor (which
sets withCredentials) and bffUnauthorizedInterceptor (which
handles 401s). forward order, no surprises.
- no CSRF for anonymous mutating routes in v1 — none exist today
and generating tokens for anonymous sessions conflicts with
express-session's saveUninitialized: false.
specs:
- 239 / 239 pass under the clean-env repro (env -u every config
var including the new CORS_ALLOWED_ORIGINS).
- +42 specs across check-cors-allowlist, csrf-cookie, csrf
middleware, csrf interceptor, and extended auth.controller /
absolute-timeout coverage for the csrf cookie mirror/clear.
out of scope, landing in follow-ups:
- rate limiting + structured error filter (remaining phase-2
todos)
- CSP fine-tuning for the portal-shell + portal-admin static
bundles
- csrf token rotation on idle-extension (current token lives
the session lifetime)
54 lines
2.2 KiB
TypeScript
54 lines
2.2 KiB
TypeScript
import type { CookieOptions } from 'express';
|
|
|
|
/**
|
|
* Name of the CSRF cookie that pairs with the `__Host-portal_session`
|
|
* cookie. Per ADR-0009 §"Double-submit CSRF": the BFF generates a
|
|
* random token at session creation and writes it both to the session
|
|
* payload (server-side) and to this cookie (readable by the SPA).
|
|
* Every mutating request must echo the value back in an
|
|
* `X-CSRF-Token` header; the middleware compares the header against
|
|
* the *session-stored* token, not the cookie — the cookie is just
|
|
* the SPA's UX way of reading the value it's expected to send back.
|
|
*
|
|
* Same env-conditional naming as the session cookie:
|
|
* - production: `__Host-portal_csrf` (prefix mandates Secure +
|
|
* Path=/ + no Domain — defeats subdomain cookie injection)
|
|
* - development: `portal_csrf` (no Secure available on HTTP)
|
|
*/
|
|
const PRODUCTION_NAME = '__Host-portal_csrf';
|
|
const DEVELOPMENT_NAME = 'portal_csrf';
|
|
|
|
export function csrfCookieName(): string {
|
|
return process.env['NODE_ENV'] === 'production' ? PRODUCTION_NAME : DEVELOPMENT_NAME;
|
|
}
|
|
|
|
/**
|
|
* Cookie options for the CSRF cookie.
|
|
*
|
|
* Crucially **NOT** `HttpOnly`: the SPA needs JavaScript access to
|
|
* read the token and echo it back in the `X-CSRF-Token` header. The
|
|
* tradeoff is acceptable because the cookie is _not_ the auth
|
|
* credential — the session id cookie (`__Host-portal_session`, which
|
|
* IS HttpOnly) is. An XSS that reads this CSRF cookie still cannot
|
|
* impersonate the user without also stealing the session cookie.
|
|
*
|
|
* `SameSite=Lax` (not Strict): matches the session cookie so the
|
|
* two travel together on the SPA→BFF cross-origin same-site fetch
|
|
* (different ports = different origin but same registrable domain).
|
|
* Strict would drop on top-level POST navigations originating from
|
|
* a different origin, which is correct for raw CSRF defense but
|
|
* loses parity with the session cookie's policy. The double-submit
|
|
* pattern itself is what gives the protection here; SameSite=Lax is
|
|
* a belt-and-braces layer.
|
|
*/
|
|
export function csrfCookieOptions(maxAgeMs: number): CookieOptions {
|
|
const isProduction = process.env['NODE_ENV'] === 'production';
|
|
return {
|
|
httpOnly: false,
|
|
sameSite: 'lax',
|
|
secure: isProduction,
|
|
path: '/',
|
|
maxAge: maxAgeMs,
|
|
};
|
|
}
|