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

+242
View File
@@ -0,0 +1,242 @@
import http from 'http';
import https from 'https';
import { errorToResponse } from '../transformers';
import { isHttpError } from '../signals';
import { isStreamResult, type PipelineResult, type ResponseShape } from '../pipeline';
import type { Bus } from '../bus';
import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from '../security';
import { parseMultipart, extractBoundary, collapseDuplicates } from '../multipart';
import { matchRoute, allowedMethods, parseQuery } from './router';
import { readBody, deriveSecure, deriveIp } from './request';
import { pickEncoder, pipeStream } from './stream';
import { attachWs } from './ws';
import type { RouteDef, WsRouteDef, MatchedRoute, MeshControl, HttpOptions } from './types';
interface HandlerConfig {
routes: RouteDef[];
bus?: Bus;
opts?: HttpOptions;
maxBody: number;
trustProxy: boolean;
}
/** A ready-to-send error response produced while acquiring the request body. */
type BodyFailure = { fail: { status: number; headers: Record<string, string>; body: string } };
/**
* Builds an HTTP/HTTPS server that routes requests, parses bodies, streams results, and handles WebSocket upgrades.
* @param routes HTTP route definitions.
* @param wsRoutes WebSocket route definitions (requires the optional `ws` peer dependency).
* @param bus Optional event bus for stream lifecycle events.
* @param meshControl Optional mesh gateway hook for a reserved upgrade path.
* @param opts Limits, TLS, security, CORS, and body-parsing options.
*/
export function createHttpServer(
routes: RouteDef[],
wsRoutes: WsRouteDef[] = [],
bus?: Bus,
meshControl?: MeshControl,
opts?: HttpOptions,
): http.Server {
const maxBody = opts?.limits?.maxBodyBytes ?? 1_000_000;
const trustProxy = opts?.trustProxy ?? false;
const handler = createRequestHandler({ routes, bus, opts, maxBody, trustProxy });
// runtime-compatible; only @types differ (https.Server lacks the http-only timeout props)
const server: http.Server = (opts?.tls
? https.createServer(opts.tls as https.ServerOptions, handler)
: http.createServer(handler)) as unknown as http.Server;
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
attachWs(server, wsRoutes, bus, meshControl, opts?.streams);
return server;
}
/** Builds the request listener: security/CORS headers, routing, body parsing, then buffered or streamed response. */
function createRequestHandler(cfg: HandlerConfig) {
const { routes, bus, opts, maxBody, trustProxy } = cfg;
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => {
const url = req.url ?? '/';
const path = url.split('?')[0];
// Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy);
const injected: Record<string, string> = { ...buildSecurityHeaders(opts?.security ?? true, secure) };
patchResponseHeaders(res, injected);
// CORS is added to `injected` AFTER the patch is installed — the patch reads it lazily
// by reference at writeHead time, so keys added here still land on every response.
if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req));
if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) {
res.writeHead(204, corsPreflightHeaders(opts.cors, req));
res.end();
return;
}
const matched = matchRoute(routes, req.method ?? 'GET', path);
if (!matched) {
// Path matches a route under a different method → 405 with Allow; otherwise 404.
const allow = allowedMethods(routes, path);
if (allow.length) {
res.writeHead(405, { 'content-type': 'application/json', allow: allow.join(', ') });
res.end(JSON.stringify({ error: 'Method Not Allowed' }));
return;
}
res.writeHead(404, { 'content-type': 'application/json' });
res.end(JSON.stringify({ error: 'Not Found' }));
return;
}
const acquired = await acquireBody(req, matched, opts, maxBody);
if ('fail' in acquired) {
res.writeHead(acquired.fail.status, acquired.fail.headers);
res.end(acquired.fail.body);
return;
}
let result: PipelineResult;
try {
result = await matched.def.handler({
method: req.method ?? 'GET',
url,
headers: req.headers,
params: matched.params,
query: parseQuery(url),
body: acquired.body,
protocol: secure ? 'https' : 'http',
ip: deriveIp(req, trustProxy),
});
} catch (error) {
result = errorToResponse(error);
}
if (isStreamResult(result)) {
const encoder = pickEncoder(matched.def.transport, String(req.headers.accept ?? ''));
await pipeStream(res, result.stream, encoder, bus, matched.def.pattern, opts?.streams);
return;
}
const response: ResponseShape = result;
res.writeHead(response.status, response.headers);
res.end(response.body);
};
}
/** Reads and parses the request body, returning `{ body }` or a ready-to-send `{ fail }` error response. */
async function acquireBody(
req: http.IncomingMessage,
matched: MatchedRoute,
opts: HttpOptions | undefined,
maxBody: number,
): Promise<{ body: unknown } | BodyFailure> {
let buf: Buffer | undefined;
try {
buf = await readBody(req, maxBody);
} catch (error) {
const response = errorToResponse(error);
return {
fail: { status: response.status, headers: { ...response.headers, connection: 'close' }, body: response.body },
};
}
const contentType = String(req.headers['content-type'] ?? '');
const duplicates = matched.def.bodyDuplicates ?? opts?.bodyDuplicates ?? 'last';
const parsed = await parseRequestBody(buf, contentType, duplicates, opts?.limits?.maxParts ?? 1000);
if ('error' in parsed) {
return {
fail: {
status: parsed.status ?? 400,
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ error: parsed.error }),
},
};
}
return { body: parsed.body };
}
/**
* Monkey-patches `res.writeHead` so injected (security/CORS) headers are authoritative on every response.
* Handler headers that case-insensitively collide with an injected key are dropped; `Vary` is merged.
* Reads `injected` by reference, so CORS keys added after installation still land.
*/
function patchResponseHeaders(res: http.ServerResponse, injected: Record<string, string>): void {
const origWriteHead = res.writeHead.bind(res);
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
// normalize (statusMessage?, headers?) overloads
const handlerHeaders = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
const merged: Record<string, any> = {};
const injectedLower = new Set(Object.keys(injected).map((key) => key.toLowerCase()));
let handlerVary: string | undefined;
if (handlerHeaders)
for (const key of Object.keys(handlerHeaders)) {
const lowerKey = key.toLowerCase();
if (lowerKey === 'vary') {
handlerVary = handlerHeaders[key];
continue;
} // merged separately below
if (!injectedLower.has(lowerKey)) merged[key] = handlerHeaders[key];
}
Object.assign(merged, injected);
if (injected['vary']) merged['vary'] = mergeVary(handlerVary, injected['vary']);
else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS
return typeof arg2 === 'string' ? origWriteHead(status, arg2, merged) : origWriteHead(status, merged);
};
}
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number };
/**
* Parses a raw request body by content type (JSON, urlencoded, multipart, or plain text).
* @returns `{ body }` on success, or `{ error, status? }` on malformed input / missing multipart support.
*/
async function parseRequestBody(
buf: Buffer | undefined,
contentType: string,
duplicates: 'array' | 'last',
maxParts: number,
): Promise<ParseResult> {
if (buf !== undefined && contentType.includes('application/json')) {
try {
return { body: JSON.parse(buf.toString('utf8')) };
} catch {
return { error: 'Invalid JSON body' };
}
}
if (buf !== undefined && contentType.includes('application/x-www-form-urlencoded')) {
return { body: collapseDuplicates(new URLSearchParams(buf.toString('utf8')), duplicates) };
}
if (buf !== undefined && contentType.includes('multipart/form-data')) {
const boundary = extractBoundary(contentType);
if (!boundary) return { error: 'Invalid multipart body' };
try {
return { body: await parseMultipart(buf, boundary, { maxParts, duplicates }) };
} catch (error) {
// HttpError = the busboy peer dep is missing (501); anything else = malformed input (400).
if (isHttpError(error)) return { error: error.message, status: error.status };
return { error: 'Invalid multipart body' };
}
}
const text = buf?.toString('utf8');
return { body: text === '' ? undefined : text };
}