feat(http): inject security headers on every response via writeHead patch

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-06 19:06:58 -05:00
1 parent 0dba41606a
commit 04da79721f
3 files changed
+84 -8

No files matched your search

+3 -3
View File
@@ -14,7 +14,7 @@ import {
import { getArgs, getHandlerNeeds, resolveArgs } from './params';
import { connectLink, type Link } from './mesh/link';
import { Rooms } from './rooms';
import type { TlsOptions } from './security';
import type { TlsOptions, SecurityOptions } from './security';
import { buildRemote } from './mesh/teacup';
import { buildManifest, createMeshControl } from './mesh/teapot';
import type { MeshControl } from './http';
@@ -53,7 +53,7 @@ export interface MeshConfig {
timeoutMs?: number;
}
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown>; tls?: TlsOptions; trustProxy?: boolean }): App {
export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record<string, unknown>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }): App {
const bus = new Bus();
const container = new Container();
let server: http.Server | undefined;
@@ -362,7 +362,7 @@ export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: Me
},
}));
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy });
server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true });
server.on('close', () => { for (const l of meshLinks) { try { l.close(); } catch { /* */ } } });
await new Promise<void>((resolve) => server!.listen(port, resolve));
return server;
+20 -4
View File
@@ -8,7 +8,8 @@ import { sseEncoder, ndjsonEncoder, StreamEncoder } from './encoders';
import { isStreamResult, type PipelineResult, type ResponseShape } from './pipeline';
import type { Transport } from './metadata';
import type { Bus } from './bus';
import type { TlsOptions } from './security';
import { buildSecurityHeaders, mergeVary } from './security';
import type { TlsOptions, SecurityOptions } from './security';
export interface RequestLimits {
maxBodyBytes?: number; // default 1_000_000
@@ -16,7 +17,7 @@ export interface RequestLimits {
headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000
}
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean }
export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }
export type RouteHandler = (req: {
method: string; url: string;
@@ -203,9 +204,26 @@ 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 = 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) };
// (CORS is folded into `injected` in Task 5; this task is security headers only.)
const orig = res.writeHead.bind(res);
(res as any).writeHead = (status: number, arg2?: any, arg3?: any) => {
// normalize (statusMessage?, headers?) overloads
const hdrs = (typeof arg2 === 'string' ? arg3 : arg2) as Record<string, any> | undefined;
// injected LAST → CORS/security keys are authoritative (a handler cannot weaken them).
// Handler's non-injected headers (content-type, etc.) survive via ...hdrs.
const merged: Record<string, any> = { ...(hdrs ?? {}), ...injected };
// Vary is list-valued: only merge when injected carries one (CORS active); else leave handler's Vary alone.
if (injected['vary']) merged['vary'] = mergeVary(hdrs?.['vary'], injected['vary']);
return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged);
};
const matched = matchRoute(routes, req.method ?? 'GET', path);
if (!matched) {
res.writeHead(404, { 'content-type': 'application/json' });
@@ -233,8 +251,6 @@ export function createHttpServer(
} else if (raw !== undefined && ct.includes('application/x-www-form-urlencoded')) {
body = Object.fromEntries(new URLSearchParams(raw));
}
const trustProxy = opts?.trustProxy ?? false;
const secure = deriveSecure(req, trustProxy);
let result: PipelineResult;
try {
result = await matched.def.handler({