Files
core/src/security.ts
T
chrnx b8b3548f15
CI / dco (pull_request) Successful in 6s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 28s
CI / runtimes (edge) (pull_request) Successful in 12s
CI / runtimes (deno) (pull_request) Successful in 21s
perf(cors): resolve the request's headers once, not two or three times
`security` and `cors` were computed twice for every request and three times for a
preflight: once in the adapter, to seed the headers a response written *above*
`handle()` still has to carry — a shed 503, a 413 from the body reader — and again in
`dispatch`, plus a third time inside `corsPreflightHeaders`.

Nothing was incorrect, because the predicate is expected to be pure with respect to one
request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup:
an allowlist in Redis, a tenant query. The framework charged the caller's latency budget
and their backend two to three times for an answer whose inputs did not change in
between, and made a predicate with a counter in it count double.

`handle()` now takes the headers the adapter already computed and hands them down, with
`computeInjected` kept as the fallback for a caller that has none.
`corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter
was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which
is what removes the duplicate rather than papering over it.

Measured against the built `dist/`, same script that produced the numbers in the issue:

    GET with Origin      2x -> 1x
    OPTIONS preflight    3x -> 1x
    buildFetch, Origin   2x -> 1x
    GET without Origin   0x -> 0x   (never reached the predicate; unchanged)

The risk here is not the call count, it is that `injected` carries the security headers
onto every response shape — so the tests that matter are the existing ones across
`transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green.
The two new tests assert the count directly, on both adapters, which is the assertion
that keeps it from drifting back.

Closes #77.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-01 09:27:32 -05:00

149 lines
6.2 KiB
TypeScript

// src/security.ts — pure header computation, no server deps
import type { Logger } from './logger';
/** TLS material for an HTTPS server. */
export interface TlsOptions {
key: Buffer | string;
cert: Buffer | string;
ca?: Buffer | string;
passphrase?: string;
}
/** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */
export interface CorsOptions {
origins: string | string[] | '*' | ((origin: string) => boolean);
methods?: string[];
allowedHeaders?: string[];
exposedHeaders?: string[];
credentials?: boolean;
maxAge?: number;
}
/** Security header policy. Each field toggles or configures one response header. */
export interface SecurityOptions {
hsts?: boolean | { maxAge?: number; includeSubDomains?: boolean; preload?: boolean };
frameOptions?: 'SAMEORIGIN' | 'DENY' | false;
referrerPolicy?: string | false;
noSniff?: boolean;
dnsPrefetchControl?: boolean;
csp?: string;
}
type Headers = Record<string, string>;
const HSTS_DEFAULT_MAXAGE = 15552000; // 180 days
// scheme "://" host [":" port], or literal "null". Rejects control chars/whitespace.
// Control-char ranges (\x00-\x1f\x7f) are intentional: reject control chars in Origin headers.
// eslint-disable-next-line no-control-regex
const ORIGIN_RE = /^(?:null|[a-z][a-z0-9+.-]*:\/\/[^\s/?#\x00-\x1f\x7f]+)$/i;
/** True if `origin` is a well-formed Origin header value (scheme://host or literal `null`). */
export function isValidOrigin(origin: string): boolean {
return ORIGIN_RE.test(origin);
}
/** Append `add` to a `Vary` header value, case-insensitively deduplicated. */
export function mergeVary(existing: string | undefined, add: string): string {
const parts = existing
? existing
.split(',')
.map((segment) => segment.trim())
.filter(Boolean)
: [];
if (!parts.some((part) => part.toLowerCase() === add.toLowerCase())) parts.push(add);
return parts.join(', ');
}
/** Build security response headers (HSTS, frame options, CSP, etc.). `secure` gates HSTS. */
export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: boolean): Headers {
if (opts === false) return {};
const options: SecurityOptions = opts === true ? {} : opts;
const headers: Headers = {};
if (options.noSniff !== false) headers['x-content-type-options'] = 'nosniff';
if (options.frameOptions !== false) headers['x-frame-options'] = options.frameOptions ?? 'SAMEORIGIN';
if (options.referrerPolicy !== false) headers['referrer-policy'] = options.referrerPolicy ?? 'no-referrer';
if (options.dnsPrefetchControl !== false) headers['x-dns-prefetch-control'] = 'off';
if (options.csp) headers['content-security-policy'] = options.csp;
if (secure && options.hsts !== false) {
const hsts = options.hsts && options.hsts !== true ? options.hsts : {};
let value = `max-age=${hsts.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
if (hsts.includeSubDomains) value += '; includeSubDomains';
if (hsts.preload) value += '; preload';
headers['strict-transport-security'] = value;
}
return headers;
}
function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean {
if (spec === '*') return true;
if (Array.isArray(spec)) return spec.includes(origin);
if (typeof spec !== 'function') return spec === origin;
// The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs
// before the region where errors convert to a response, so a throw here would leave the request
// listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed
// has not said yes, and a broken allowlist must never widen into an open one.
try {
return spec(origin);
} catch (error) {
logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, {
origin,
err: error instanceof Error ? error.message : String(error),
});
return false;
}
}
/** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */
export function resolveCors(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
logger?: Logger,
): Headers {
const headers: Headers = {};
const rawOrigin = req.headers['origin'];
const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers;
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) {
headers['access-control-allow-origin'] = origin;
headers['access-control-allow-credentials'] = 'true';
headers['vary'] = mergeVary(headers['vary'], 'Origin');
} else if (opts.origins === '*') {
headers['access-control-allow-origin'] = '*';
} else {
headers['access-control-allow-origin'] = origin;
headers['vary'] = mergeVary(headers['vary'], 'Origin');
}
if (opts.exposedHeaders?.length) headers['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
return headers;
}
/** Preflight-specific headers (methods/allowed-headers/max-age). Call only for OPTIONS+ACRM. */
export function corsPreflightHeaders(
opts: CorsOptions,
req: { headers: Record<string, string | string[] | undefined> },
resolved?: Headers,
): Headers {
// The caller has almost always resolved CORS already, one layer up, to seed the headers every
// response carries. Re-deriving here would consult `origins` a second time for the same request —
// and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the
// preflight-only keys below belong to this 204, not to the shared object.
const headers: Headers = { ...resolved };
if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204
headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(
', ',
);
const requestedHeaders = req.headers['access-control-request-headers'];
headers['access-control-allow-headers'] =
opts.allowedHeaders?.join(', ') ??
(Array.isArray(requestedHeaders) ? requestedHeaders.join(', ') : (requestedHeaders ?? '*'));
if (opts.maxAge != null) headers['access-control-max-age'] = String(opts.maxAge);
return headers;
}