feat: beta-hardening — routing, degradation, mesh gate, uploads, @header

Restructure first: split the two oversized files by cohesion (http.ts 449
→ http/{router,request,stream,ws,server,types}; app.ts 556 → app/{types,
introspect,index}), rename cryptic locals, JSDoc the public API, and
extract helpers so no function exceeds the complexity gate (createApp
187 → <15, listen 113 → 6). Public import paths are unchanged (barrels).

On that structure, five features that close the biggest gaps vs
Express/Fastify/Nest for a comparable beta:

- routing: `:name*` catch-all, specificity precedence (static ▸ param ▸
  catch-all, not registration order), and 405 + Allow when a path exists
  under a different method (was 404)
- visible degradation: optional providers that fail boot are summarized on
  listen() and queryable via app.degraded(), instead of a silent warn
- mesh is alpha — gated behind `experimental: true`; createApp throws if
  `mesh` is configured without it
- multipart moves to the optional `busboy` peer dependency (clear 501 when
  absent), keeping the core at one runtime dependency
- `@header('name')` as a singular alias of `@headers`

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-07 12:00:15 -05:00
1 parent 9d79972f62
commit d6c5cee0ee
42 files changed
+2619 -1170

No files matched your search

+76 -42
View File
@@ -1,6 +1,14 @@
// src/security.ts — pure header computation, no server deps
export interface TlsOptions { key: Buffer | string; cert: Buffer | string; ca?: Buffer | string; passphrase?: string }
/** 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[];
@@ -10,6 +18,7 @@ export interface CorsOptions {
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;
@@ -23,32 +32,47 @@ 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;
export function isValidOrigin(o: string): boolean { return ORIGIN_RE.test(o); }
/** 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((s) => s.trim()).filter(Boolean) : []);
if (!parts.some((p) => p.toLowerCase() === add.toLowerCase())) parts.push(add);
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 o: SecurityOptions = opts === true ? {} : opts;
const h: Headers = {};
if (o.noSniff !== false) h['x-content-type-options'] = 'nosniff';
if (o.frameOptions !== false) h['x-frame-options'] = o.frameOptions ?? 'SAMEORIGIN';
if (o.referrerPolicy !== false) h['referrer-policy'] = o.referrerPolicy ?? 'no-referrer';
if (o.dnsPrefetchControl !== false) h['x-dns-prefetch-control'] = 'off';
if (o.csp) h['content-security-policy'] = o.csp;
if (secure && o.hsts !== false) {
const hs = o.hsts && o.hsts !== true ? o.hsts : {};
let v = `max-age=${hs.maxAge ?? HSTS_DEFAULT_MAXAGE}`;
if (hs.includeSubDomains) v += '; includeSubDomains';
if (hs.preload) v += '; preload';
h['strict-transport-security'] = v;
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 h;
return headers;
}
function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
@@ -58,36 +82,46 @@ function originAllowed(spec: CorsOptions['origins'], origin: string): boolean {
return spec === origin;
}
// req: minimal shape { headers: { origin? } }
export function resolveCors(opts: CorsOptions, req: { headers: Record<string, string | string[] | undefined> }): Headers {
const h: Headers = {};
const raw = req.headers['origin'];
const origin = Array.isArray(raw) ? raw[0] : raw;
if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return h;
/** 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> },
): 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)) return headers;
// credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic.
if (opts.credentials) {
h['access-control-allow-origin'] = origin;
h['access-control-allow-credentials'] = 'true';
h['vary'] = mergeVary(h['vary'], 'Origin');
headers['access-control-allow-origin'] = origin;
headers['access-control-allow-credentials'] = 'true';
headers['vary'] = mergeVary(headers['vary'], 'Origin');
} else if (opts.origins === '*') {
h['access-control-allow-origin'] = '*';
headers['access-control-allow-origin'] = '*';
} else {
h['access-control-allow-origin'] = origin;
h['vary'] = mergeVary(h['vary'], 'Origin');
headers['access-control-allow-origin'] = origin;
headers['vary'] = mergeVary(headers['vary'], 'Origin');
}
if (opts.exposedHeaders?.length) h['access-control-expose-headers'] = opts.exposedHeaders.join(', ');
return h;
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> }): Headers {
const h = resolveCors(opts, req);
if (!h['access-control-allow-origin']) return h; // origin not allowed → bare 204
h['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join(', ');
const reqHdrs = req.headers['access-control-request-headers'];
h['access-control-allow-headers'] = opts.allowedHeaders?.join(', ')
?? (Array.isArray(reqHdrs) ? reqHdrs.join(', ') : reqHdrs ?? '*');
if (opts.maxAge != null) h['access-control-max-age'] = String(opts.maxAge);
return h;
/** 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> },
): Headers {
const headers = resolveCors(opts, req);
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;
}