From cb77216a53d1a59ae71a780c059fe4d3d969df09 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Mon, 6 Jul 2026 19:16:48 -0500 Subject: [PATCH] feat(http): configurable CORS with guarded OPTIONS preflight Signed-off-by: Diego Resendez --- src/app.ts | 6 ++-- src/http.ts | 16 ++++++--- src/index.ts | 1 + test/transport-security.test.ts | 57 +++++++++++++++++++++++++++++++++ 4 files changed, 73 insertions(+), 7 deletions(-) diff --git a/src/app.ts b/src/app.ts index 3f5e4af..ecc64fb 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, SecurityOptions } from './security'; +import type { TlsOptions, SecurityOptions, CorsOptions } 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; security?: boolean | SecurityOptions }): App { +export function createApp(opts: { modules: Ctor[]; plugins?: Plugin[]; mesh?: MeshConfig; limits?: RequestLimits; devGraph?: boolean; overrides?: Record; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions }): 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, security: opts.security ?? true }); + server = createHttpServer(httpRoutes, wsRoutes, bus, meshControl, { limits: opts.limits, streams, tls: opts.tls, trustProxy: opts.trustProxy, security: opts.security ?? true, cors: opts.cors }); 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 6abc63c..abc83a5 100644 --- a/src/http.ts +++ b/src/http.ts @@ -8,8 +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 { buildSecurityHeaders, mergeVary } from './security'; -import type { TlsOptions, SecurityOptions } from './security'; +import { buildSecurityHeaders, mergeVary, resolveCors, corsPreflightHeaders } from './security'; +import type { TlsOptions, SecurityOptions, CorsOptions } from './security'; export interface RequestLimits { maxBodyBytes?: number; // default 1_000_000 @@ -17,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; security?: boolean | SecurityOptions } +export interface HttpOptions { limits?: RequestLimits; streams?: Set<() => void>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions; cors?: CorsOptions } export type RouteHandler = (req: { method: string; url: string; @@ -212,7 +212,6 @@ export function createHttpServer( // (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 @@ -233,6 +232,15 @@ export function createHttpServer( else if (handlerVary !== undefined) merged['vary'] = handlerVary; // preserve handler Vary when no CORS return typeof arg2 === 'string' ? orig(status, arg2, merged) : orig(status, merged); }; + // 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']) { + const pf = corsPreflightHeaders(opts.cors, req); + res.writeHead(204, pf); + res.end(); + return; + } const matched = matchRoute(routes, req.method ?? 'GET', path); if (!matched) { res.writeHead(404, { 'content-type': 'application/json' }); diff --git a/src/index.ts b/src/index.ts index cbaa2e0..28cf546 100644 --- a/src/index.ts +++ b/src/index.ts @@ -24,6 +24,7 @@ export { sseEncoder, ndjsonEncoder } from './encoders'; export type { StreamEncoder } from './encoders'; export type { MeshConfig } from './app'; export type { RequestLimits } from './http'; +export type { TlsOptions, CorsOptions, SecurityOptions } from './security'; export { connectLink } from './mesh/link'; export { buildRemote, envelopeFrom } from './mesh/teacup'; export { buildManifest, createMeshControl, MESH_CONTROL_PATH } from './mesh/teapot'; diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 043fc28..7f880d9 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -158,3 +158,60 @@ describe('security headers', () => { await res.body?.cancel(); }); }); + +describe('CORS', () => { + it('echoes allowed origin, sets Vary; preflight 204', async () => { + @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } }); + expect(r.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(r.headers.get('vary')).toContain('Origin'); + const pre = await fetch(`http://127.0.0.1:${port}/x`, { + method: 'OPTIONS', headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' } }); + expect(pre.status).toBe(204); + expect(pre.headers.get('access-control-allow-methods')).toContain('GET'); + expect(pre.headers.get('x-content-type-options')).toBe('nosniff'); // security headers on preflight too + }); + + it('credentials never returns *; echoes concrete origin', async () => { + @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], cors: { origins: '*', credentials: true } }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } }); + expect(r.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(r.headers.get('access-control-allow-credentials')).toBe('true'); + }); + + it('disallowed origin → no allow-origin; bare OPTIONS (no ACRM) falls through to 404', async () => { + @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://evil.com' } }); + expect(r.headers.get('access-control-allow-origin')).toBeNull(); + const bare = await fetch(`http://127.0.0.1:${port}/x`, { method: 'OPTIONS' }); // no ACRM + expect(bare.status).toBe(404); + }); + + it("merges a handler's Title-Case Vary with CORS's Origin", async () => { + @Route('/') class C { + @Get('/x') + @Transformer((v) => ({ status: 200, headers: { Vary: 'Accept-Encoding' }, body: JSON.stringify(v) })) + x() { return { ok: 1 }; } + } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + app = createApp({ modules: [CMod], cors: { origins: 'https://a.com' } }); + const server = await app.listen(0); + const port = (server.address() as any).port; + const r = await fetch(`http://127.0.0.1:${port}/x`, { headers: { origin: 'https://a.com' } }); + const vary = r.headers.get('vary'); + expect(vary).toContain('Accept-Encoding'); + expect(vary).toContain('Origin'); + }); +});