From 04da79721f97fe848254e34a4ca749c609e02971 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 6 Jul 2026 19:06:58 -0500 Subject: [PATCH] feat(http): inject security headers on every response via writeHead patch Signed-off-by: Diego Resendez --- src/app.ts | 6 ++-- src/http.ts | 24 ++++++++++--- test/transport-security.test.ts | 62 ++++++++++++++++++++++++++++++++- 3 files changed, 84 insertions(+), 8 deletions(-) diff --git a/src/app.ts b/src/app.ts index d41aba1..3f5e4af 100644 --- a/src/app.ts +++ b/src/app.ts @@ -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; tls?: TlsOptions; trustProxy?: boolean }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; 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((resolve) => server!.listen(port, resolve)); return server; diff --git a/src/http.ts b/src/http.ts index 345815b..9f67fc9 100644 --- a/src/http.ts +++ b/src/http.ts @@ -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 => { 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 = { ...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 | 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 = { ...(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({ diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 19c0138..69b6b31 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -1,7 +1,7 @@ import { describe, it, expect, afterEach } from 'vitest'; import https from 'https'; import WebSocket from 'ws'; -import { createApp, Route, Get, Ws, Module, inbound, channel, ctx } from '../src'; +import { createApp, Route, Get, Sse, Ws, Module, inbound, channel, ctx } from '../src'; import { selfSignedTls } from './helpers/tls'; @Route('/') @@ -69,3 +69,63 @@ describe('trustProxy', () => { expect(await r.json()).toEqual({ proto: 'http' }); }); }); + +describe('security headers', () => { + it('on 200, 404, error; HSTS only when secure', async () => { + @Route('/') class S { + @Get('/ok') ok() { return { a: 1 }; } + @Get('/boom') boom() { throw new Error('x'); } + } + @Module({ mountpoint: '/', controllers: [S] }) class SMod {} + app = createApp({ modules: [SMod] }); // security defaults on + const server = await app.listen(0); + const port = (server.address() as any).port; + const ok = await fetch(`http://127.0.0.1:${port}/ok`); + expect(ok.headers.get('x-content-type-options')).toBe('nosniff'); + expect(ok.headers.get('strict-transport-security')).toBeNull(); // http, not secure + const nf = await fetch(`http://127.0.0.1:${port}/nope`); + expect(nf.status).toBe(404); + expect(nf.headers.get('x-frame-options')).toBe('SAMEORIGIN'); + const boom = await fetch(`http://127.0.0.1:${port}/boom`); + expect(boom.status).toBe(500); + expect(boom.headers.get('x-content-type-options')).toBe('nosniff'); + }); + + it('security:false emits none', async () => { + @Route('/') class S { @Get('/ok') ok() { return { a: 1 }; } } + @Module({ mountpoint: '/', controllers: [S] }) class SMod {} + app = createApp({ modules: [SMod], security: false }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const ok = await fetch(`http://127.0.0.1:${port}/ok`); + expect(ok.headers.get('x-content-type-options')).toBeNull(); + }); + + it('HSTS present over https', async () => { + @Route('/') class S { @Get('/ok') ok() { return { a: 1 }; } } + @Module({ mountpoint: '/', controllers: [S] }) class SMod {} + app = createApp({ modules: [SMod], tls: selfSignedTls() }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const hsts = await new Promise((resolve, reject) => { + https.get({ port, path: '/ok', rejectUnauthorized: false }, (res) => { + res.resume(); + resolve(res.headers['strict-transport-security'] as string | undefined); + }).on('error', reject); + }); + expect(hsts).toContain('max-age='); + }); + + it('stream response carries security headers', async () => { + @Route('/') class S { + @Sse('/stream') async *stream() { yield 'a'; } + } + @Module({ mountpoint: '/', controllers: [S] }) class SMod {} + app = createApp({ modules: [SMod] }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const res = await fetch(`http://127.0.0.1:${port}/stream`, { headers: { accept: 'text/event-stream' } }); + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + await res.body?.cancel(); + }); +});