feat(http): configurable CORS with guarded OPTIONS preflight

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-07-06 19:16:48 -05:00
1 parent 0982873462
commit cb77216a53
4 files changed
+73 -7

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, 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<string, unknown>; tls?: TlsOptions; trustProxy?: boolean; security?: boolean | SecurityOptions }): 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; 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<void>((resolve) => server!.listen(port, resolve));
return server;
+12 -4
View File
@@ -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<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
@@ -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' });
+1
View File
@@ -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';