From bb0b01cf26e492109d3907dd48fbc7a1fe7d29ac Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 08:39:11 -0500 Subject: [PATCH 1/5] fix(cors): deny the origin when the origins predicate throws MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `CorsOptions.origins` accepts a predicate, and it runs on the request path above the region where errors convert to a response. A predicate that threw became a rejected promise nobody awaited, and Node's default for that is to exit — so one cross-origin GET took the process down, with `onError` never reaching it. The trigger is a browser: `originAllowed` only runs when an `Origin` header is present, so the crash is reachable by any cross-origin client and by no test that forgets the header, which is how it survived a green suite. Guard the call at `originAllowed`, the single point all four call sites funnel through (the Node handler, `computeInjected` on both adapters, and the preflight path). A predicate that throws denies the origin: a lookup that failed has not said yes, and a broken allowlist must never widen into an open one. The failure is reported through the app logger rather than swallowed — `HttpOptions` already carries one. The published behaviour changes for a throwing predicate only. Every other origin shape is untouched, and the security headers still land on the response. Amends one test from the `maxConcurrentRequests` contribution, which asserted the old crash as its baseline while proving the gate does not leak a slot. It still proves that, against a transient failure that is now answered rather than fatal. Closes #72. Signed-off-by: Diego Resendez --- src/http/core.ts | 4 ++-- src/http/server.ts | 2 +- src/security.ts | 27 ++++++++++++++++++++++----- test/http.test.ts | 32 ++++++++++++++++++++++++++++++++ test/security.test.ts | 29 ++++++++++++++++++++++++++++- test/web-stream.test.ts | 22 ++++++++++++++++------ 6 files changed, 101 insertions(+), 15 deletions(-) diff --git a/src/http/core.ts b/src/http/core.ts index 357511e..977dfdf 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -132,7 +132,7 @@ export function computeInjected( req: { secure: boolean; headers: Record }, ): Record { const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, req.secure) }; - if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req)); + if (opts?.cors) Object.assign(injected, resolveCors(opts.cors, req, opts.logger)); return injected; } @@ -287,7 +287,7 @@ async function dispatch( } if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { - return { preflight: corsPreflightHeaders(opts.cors, req) }; + return { preflight: corsPreflightHeaders(opts.cors, req, opts.logger) }; } const matched = resolveRoute(routes, req.method, path); diff --git a/src/http/server.ts b/src/http/server.ts index 44b3aec..32ad05e 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -101,7 +101,7 @@ function createRequestHandler(cfg: HandlerConfig) { // 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) Object.assign(injected, resolveCors(opts.cors, req, opts?.logger)); let result: HandleResult | Preflight; let acquired = false; diff --git a/src/security.ts b/src/security.ts index c48023d..8dee23a 100644 --- a/src/security.ts +++ b/src/security.ts @@ -1,5 +1,7 @@ // src/security.ts — pure header computation, no server deps +import type { Logger } from './logger'; + /** TLS material for an HTTPS server. */ export interface TlsOptions { key: Buffer | string; @@ -75,22 +77,36 @@ export function buildSecurityHeaders(opts: boolean | SecurityOptions, secure: bo return headers; } -function originAllowed(spec: CorsOptions['origins'], origin: string): boolean { +function originAllowed(spec: CorsOptions['origins'], origin: string, logger?: Logger): boolean { if (spec === '*') return true; - if (typeof spec === 'function') return spec(origin); if (Array.isArray(spec)) return spec.includes(origin); - return spec === origin; + if (typeof spec !== 'function') return spec === origin; + + // The predicate is user code on the request path — a Redis allowlist, a tenant lookup — and it runs + // before the region where errors convert to a response, so a throw here would leave the request + // listener as an unhandled rejection and take the process down. Deny instead: a lookup that failed + // has not said yes, and a broken allowlist must never widen into an open one. + try { + return spec(origin); + } catch (error) { + logger?.warn(`cors: the origins predicate threw for ${origin} — treating the origin as not allowed`, { + origin, + err: error instanceof Error ? error.message : String(error), + }); + return false; + } } /** Compute CORS response headers for a request. Returns `{}` when the origin is not allowed. */ export function resolveCors( opts: CorsOptions, req: { headers: Record }, + logger?: Logger, ): Headers { const headers: Headers = {}; const rawOrigin = req.headers['origin']; const origin = Array.isArray(rawOrigin) ? rawOrigin[0] : rawOrigin; - if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin)) return headers; + if (!origin || !isValidOrigin(origin) || !originAllowed(opts.origins, origin, logger)) return headers; // credentials => never '*'; echo concrete origin. Also echo when allowlist is dynamic. if (opts.credentials) { @@ -112,8 +128,9 @@ export function resolveCors( export function corsPreflightHeaders( opts: CorsOptions, req: { headers: Record }, + logger?: Logger, ): Headers { - const headers = resolveCors(opts, req); + const headers = resolveCors(opts, req, logger); if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204 headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join( ', ', diff --git a/test/http.test.ts b/test/http.test.ts index 01b5bdd..1e7bfc8 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -352,4 +352,36 @@ describe('request hardening', () => { expect(await res.json()).toEqual({ a: '1', b: 'two' }); server.close(); }); + + it('a cors.origins predicate that throws answers the request instead of taking the process down', async () => { + const warn = vi.fn(); + const server = createHttpServer( + [{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }], + [], + undefined, + undefined, + { + cors: { + origins: () => { + throw new Error('lookup failed'); + }, + }, + logger: { debug: vi.fn(), info: vi.fn(), warn, error: vi.fn() } as any, + }, + ); + await new Promise((r) => server.listen(0, r)); + + // Only a request carrying an Origin reaches the predicate — which is why a suite that forgets + // the header watches this crash in production instead. + const res = await fetch(`${getUrl(server)}/ping`, { headers: { origin: 'https://a.com' } }); + + expect(res.status).toBe(200); + expect(res.headers.get('access-control-allow-origin')).toBeNull(); + expect(warn).toHaveBeenCalled(); + + // The security headers still land: one broken predicate must not strip the rest. + expect(res.headers.get('x-content-type-options')).toBe('nosniff'); + server.close(); + }); + }); diff --git a/test/security.test.ts b/test/security.test.ts index 4cba1e9..4ddce20 100644 --- a/test/security.test.ts +++ b/test/security.test.ts @@ -1,4 +1,4 @@ -import { describe, it, expect } from 'vitest'; +import { describe, it, expect, vi } from 'vitest'; import { buildSecurityHeaders, resolveCors, mergeVary, isValidOrigin } from '../src/security'; describe('buildSecurityHeaders', () => { @@ -51,6 +51,33 @@ describe('resolveCors', () => { const r = resolveCors({ origins: () => true }, req('https://a.com\r\nX: y') as any); expect(r['access-control-allow-origin']).toBeUndefined(); }); + + // An `origins` predicate is the whole reason the option takes a function: an allowlist in Redis, a + // tenant lookup, a regex over a parsed URL. Every one of those has a failure mode, and it runs on + // the request path — so a throw must not leave the boundary. + describe('a predicate that throws', () => { + const boom = () => { + throw new Error('lookup failed'); + }; + + it('denies the origin rather than escaping the request path', () => { + expect(() => resolveCors({ origins: boom }, req('https://a.com') as any)).not.toThrow(); + expect(resolveCors({ origins: boom }, req('https://a.com') as any)).toEqual({}); + }); + + it('fails closed even when credentials are on — a broken allowlist is not an open one', () => { + const r = resolveCors({ origins: boom, credentials: true }, req('https://a.com') as any); + expect(r['access-control-allow-origin']).toBeUndefined(); + expect(r['access-control-allow-credentials']).toBeUndefined(); + }); + + it('reports the failure through the logger instead of swallowing it', () => { + const logger = { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() }; + resolveCors({ origins: boom }, req('https://a.com') as any, logger as any); + expect(logger.warn).toHaveBeenCalledOnce(); + expect(logger.warn.mock.calls[0][0]).toMatch(/cors/i); + }); + }); }); describe('isValidOrigin', () => { diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts index 4728c5a..54481f8 100644 --- a/test/web-stream.test.ts +++ b/test/web-stream.test.ts @@ -52,8 +52,10 @@ describe('asReadableStream', () => { }); describe('buildFetch request gate', () => { - it('does not permanently exhaust the gate when CORS setup throws', async () => { - let attempts = 0; + it('rides out a transient CORS predicate failure without leaking a gate slot', async () => { + // A flag rather than an attempt counter: `computeInjected` runs both in this adapter and again + // inside `handle()`, so the predicate is consulted more than once per request. + let lookupDown = true; const fetchHandler = buildFetch( [ @@ -68,8 +70,7 @@ describe('buildFetch request gate', () => { limits: { maxConcurrentRequests: 2 }, cors: { origins: () => { - attempts++; - if (attempts <= 2) throw new Error('transient CORS failure'); + if (lookupDown) throw new Error('transient CORS failure'); return true; }, }, @@ -81,11 +82,20 @@ describe('buildFetch request gate', () => { headers: { origin: 'https://example.com' }, }); - await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure'); - await expect(fetchHandler(request())).rejects.toThrow('transient CORS failure'); + // While the lookup is down the origin is denied — the request is answered, just without the + // header that would let the browser read it. A failed lookup has not said yes. + for (let i = 0; i < 2; i++) { + const denied = await fetchHandler(request()); + expect(denied.status).toBe(200); + expect(denied.headers.get('access-control-allow-origin')).toBeNull(); + } + // Once the lookup recovers the origin is allowed again, which also proves the two failures + // returned their slots: a budget of 2 that leaked would have shed this one. + lookupDown = false; const recovered = await fetchHandler(request()); expect(recovered.status).toBe(200); + expect(recovered.headers.get('access-control-allow-origin')).toBe('https://example.com'); }); it('rejects requests above maxConcurrentRequests and releases the slot afterwards', async () => { From 4896ee86d28cc2bb869477cf6ce802f579897328 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 08:50:42 -0500 Subject: [PATCH 2/5] fix(jsr): resolve `require` from source, not from tsup's banner MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit JSR publishes `src/` and runs no bundler, so the `createRequire` banner tsup gives the ESM build (tsup.config.ts) never exists there. Every lazy `require(...)` in the source had nothing to resolve, and one of them was unguarded: `@Html('file')` and template mode died at boot on Deno with `ReferenceError: require is not defined`. The two guarded sites were worse than the crash, because they answered confidently and wrongly. `static` reported *"needs a filesystem and is unavailable on this runtime (edge)"* while running on Deno, which has one; multipart reported busboy as not installed while it sat in node_modules. Both blamed the runtime for a packaging problem, and both named a runtime the reader was not on. Route all ten call sites through one `nodeRequire`, which prefers the ambient `require` — so the CJS build and the banner-carrying ESM build behave exactly as before — and otherwise rebuilds one from `process.getBuiltinModule('node:module')`. Node 22.3+, Deno and Bun all expose that synchronously, which is the requirement: every caller sits on a sync path a dynamic `import()` could not serve. It resolves from `process.cwd()`, since a peer dependency like busboy belongs to the application, not to a module served over https from a registry. Where neither exists — workerd, where esbuild rewrites the call into its own throwing stub — the behaviour is unchanged: the guarded sites still catch, and their "edge has no filesystem" story is finally the true one. Covered by a Deno suite that imports `src/` exactly as JSR serves it. The other Deno tests already did that; none of them touched a path that loads a Node builtin lazily, which is how a package that died at boot kept a green suite. Closes #69. Signed-off-by: Diego Resendez --- src/http/core.ts | 9 +++-- src/http/server.ts | 7 ++-- src/http/ws-adapter.ts | 4 +- src/http/ws.ts | 4 +- src/multipart.ts | 4 +- src/node-require.ts | 44 ++++++++++++++++++++ src/views.ts | 17 ++++---- test/deno/views.test.ts | 76 +++++++++++++++++++++++++++++++++++ test/fixtures/views/asset.txt | 1 + test/fixtures/views/dash.html | 1 + test/fixtures/views/user.html | 1 + 11 files changed, 145 insertions(+), 23 deletions(-) create mode 100644 src/node-require.ts create mode 100644 test/deno/views.test.ts create mode 100644 test/fixtures/views/asset.txt create mode 100644 test/fixtures/views/dash.html create mode 100644 test/fixtures/views/user.html diff --git a/src/http/core.ts b/src/http/core.ts index 977dfdf..f0264fb 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -9,6 +9,7 @@ import { acquireBody, type BodyReader } from './body'; import type { RouteDef, HttpOptions } from './types'; import type { StreamEncoder } from '../encoders'; import type { Bus } from '../bus'; +import { nodeRequire } from '../node-require'; /** * `randomUUID`, from wherever this runtime keeps it. Resolved once, at import. @@ -23,15 +24,15 @@ import type { Bus } from '../bus'; * CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly * why that job is pinned to the floor rather than to the current release. * - * The fallback is reached only by a runtime that lacks the global, so workerd never evaluates the - * `require` — and the ESM build has a real one, from the `createRequire` banner in `tsup.config.ts`. + * The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it. + * It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on + * every distribution of this package and not just the bundled ones. */ const randomUUID: () => string = (() => { const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto; if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!(); - // eslint-disable-next-line @typescript-eslint/no-require-imports - return (require('node:crypto') as { randomUUID: () => string }).randomUUID; + return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID; })(); /** diff --git a/src/http/server.ts b/src/http/server.ts index 32ad05e..6f9033d 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -11,6 +11,7 @@ import { mergeInjectedHeaders } from './headers'; import { handle, correlateRequest, type HandleResult, type Preflight } from './core'; import type { BodyFailure, BodyReader } from './body'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; +import { nodeRequire } from '../node-require'; interface HandlerConfig { routes: RouteDef[]; @@ -44,10 +45,8 @@ export function createHttpServer( // Node http/https are loaded lazily so importing createApp stays edge/workerd-safe // (workerd's nodejs_compat provides no node:http/node:https). This path only runs under listen(). - // eslint-disable-next-line @typescript-eslint/no-require-imports - const nodeHttp = require('http') as typeof import('http'); - // eslint-disable-next-line @typescript-eslint/no-require-imports - const nodeHttps = require('https') as typeof import('https'); + const nodeHttp = nodeRequire('http'); + const nodeHttps = nodeRequire('https'); // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) const server: http.Server = (opts?.tls diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index 8f9307e..1c0d8d8 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -1,6 +1,7 @@ import { channel } from '../channel'; import type { App } from '../app/types'; import type { WsRequest, WsSocket } from './ws-core'; +import { nodeRequire } from '../node-require'; /** * Shared plumbing for the runtime adapters (Bun/Deno/edge) that bridge a host WebSocket @@ -123,8 +124,7 @@ export function loadWebSocketCtor(): SocketCtor { if (platform) return platform; - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('ws') as SocketCtor; + return nodeRequire('ws'); } /** diff --git a/src/http/ws.ts b/src/http/ws.ts index f738067..b22d684 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -3,14 +3,14 @@ import { channel } from '../channel'; import type { Bus } from '../bus'; import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import type { WsRouteDef, MeshControl } from './types'; +import { nodeRequire } from '../node-require'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ function loadWss(): any | null { try { // `ws` is an OPTIONAL peer dependency: lazy-required so installs without WebSocket // support don't fail. When absent this throws and we fall back to null (501 on upgrade). - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('ws').WebSocketServer; + return nodeRequire<{ WebSocketServer: unknown }>('ws').WebSocketServer; } catch { return null; } diff --git a/src/multipart.ts b/src/multipart.ts index 3e03cab..d525388 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -1,6 +1,7 @@ // src/multipart.ts — multipart/form-data parsing on top of the optional `busboy` peer dependency. import { Readable } from 'stream'; import { HttpError } from './signals'; +import { nodeRequire } from './node-require'; /** A single uploaded file part decoded from a multipart body. */ export interface UploadedFile { @@ -67,8 +68,7 @@ function loadBusboy(): ((cfg: unknown) => NodeJS.WritableStream & NodeJS.EventEm try { // `busboy` is an OPTIONAL peer dependency: only multipart uploads need it, so it is // lazy-required and its absence surfaces as a clear 501 rather than a load-time crash. - // eslint-disable-next-line @typescript-eslint/no-require-imports - return require('busboy'); + return nodeRequire('busboy'); } catch { return null; } diff --git a/src/node-require.ts b/src/node-require.ts new file mode 100644 index 0000000..a9c7e27 --- /dev/null +++ b/src/node-require.ts @@ -0,0 +1,44 @@ +// src/node-require.ts — one `require` that survives being published as source. + +type Require = (id: string) => T; + +interface NodeProcess { + cwd?: () => string; + getBuiltinModule?: (id: string) => unknown; +} + +let cached: Require | null | undefined; + +function resolveRequire(): Require | undefined { + // The CJS build has a native one, and tsup gives the ESM build one through a `createRequire` + // banner (tsup.config.ts). Both npm paths stop here. + if (typeof require === 'function') return require as Require; + + // JSR publishes `src/` and runs no bundler, so on that path nothing ever defined `require`. + // `process.getBuiltinModule` is the way back: Node 22.3+, Deno and Bun all expose it, and all + // three do it *synchronously* — which is the whole requirement, since every caller here sits on + // a sync path that a dynamic `import()` could not serve. + const proc = (globalThis as { process?: NodeProcess }).process; + const nodeModule = proc?.getBuiltinModule?.('node:module') as + { createRequire?: (from: string) => Require } | undefined; + if (!nodeModule?.createRequire || !proc?.cwd) return undefined; + + // Resolve from the application's directory rather than from this file: served from JSR this + // module lives under an `https://` URL with no `node_modules` beneath it, while an optional peer + // dependency such as `busboy` is installed in the app that asked for it. + return nodeModule.createRequire(`${proc.cwd()}/`); +} + +/** + * Loads a Node builtin or an installed package, synchronously. + * + * Throws on a runtime that can offer neither — workerd, where `node:fs` and `busboy` are genuinely + * out of reach. Every caller already guards for that and reports it in its own terms; what they + * must not do is report it when the module is in fact reachable, which is what a bare `require` + * caused on JSR by failing with `ReferenceError` before any of them was consulted. + */ +export function nodeRequire(id: string): T { + if (cached === undefined) cached = resolveRequire() ?? null; + if (cached === null) throw new Error(`cannot load '${id}': this runtime provides no CommonJS require`); + return cached(id); +} diff --git a/src/views.ts b/src/views.ts index 210ab9c..ee07a8b 100644 --- a/src/views.ts +++ b/src/views.ts @@ -3,6 +3,7 @@ import type { TransformerFn } from './metadata'; import type { HtmlMeta } from './metadata'; +import { nodeRequire } from './node-require'; /** Escape the five HTML-significant characters so interpolated data can't inject markup. */ export function escapeHtml(s: string): string { @@ -58,12 +59,12 @@ export interface ViewsContext { /** Reads a view file at boot (lazy fs). Relative paths resolve against `views` (default cwd); absolute as-is. * node:fs/node:path are loaded lazily so importing the barrel stays edge/workerd-safe - * (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. */ + * (workerd's nodejs_compat provides no filesystem). This path only runs for path/template `@Html` modes. + * Unguarded on purpose: `@Html('file')` cannot degrade into anything useful, so a runtime with no + * filesystem should hear about it here rather than at the first request. */ function readViewFile(views: string | undefined, path: string): string { - // eslint-disable-next-line @typescript-eslint/no-require-imports - const nodePath = require('node:path') as typeof import('node:path'); - // eslint-disable-next-line @typescript-eslint/no-require-imports - const fs = require('node:fs') as typeof import('node:fs'); + const nodePath = nodeRequire('node:path'); + const fs = nodeRequire('node:fs'); const base = views ?? process.cwd(); const full = nodePath.isAbsolute(path) ? path : nodePath.resolve(base, path); @@ -94,10 +95,8 @@ export function buildStaticResolver(root: string | true): StaticResolver { let nodePath: typeof import('node:path'); try { - // eslint-disable-next-line @typescript-eslint/no-require-imports - fs = require('node:fs'); - // eslint-disable-next-line @typescript-eslint/no-require-imports - nodePath = require('node:path'); + fs = nodeRequire('node:fs'); + nodePath = nodeRequire('node:path'); } catch { throw new Error( '`static` needs a filesystem and is unavailable on this runtime (edge). Remove it or serve assets from a CDN.', diff --git a/test/deno/views.test.ts b/test/deno/views.test.ts new file mode 100644 index 0000000..4aff1f4 --- /dev/null +++ b/test/deno/views.test.ts @@ -0,0 +1,76 @@ +// `@Html` and `static` under the real Deno runtime, importing `src/` the way JSR serves it. +// +// This is the shape the JSR package actually ships: no bundler ran, so tsup's `createRequire` +// banner (tsup.config.ts) never existed and the lazy `require('node:fs')` in `src/views.ts` has +// nothing to resolve. Every other Deno test here imports `src/` too, but none of them touches a +// path that loads a Node builtin lazily — which is how a package that dies at boot on Deno kept a +// green suite. Run with: npm run test:deno +import 'npm:reflect-metadata'; +import { assertEquals, assertStringIncludes } from 'jsr:@std/assert'; +import { createApp, Route, Get, Html, Module } from '../../src/index.ts'; + +// Committed fixtures rather than a temp dir, so the suite keeps running without `--allow-write`. +const dir = 'test/fixtures/views'; + +@Route('/') +class Views { + @Get('/dash') @Html('dash.html') dash() {} + @Get('/user') @Html('user.html', { template: true }) user() { + return { name: 'Deno' }; + } +} + +@Module({ mountpoint: '/', controllers: [Views] }) +class M {} + +Deno.test("@Html file mode reads the file — the require path resolves without tsup's banner", async () => { + const app = createApp({ modules: [M], views: dir }); + const res = await app.fetch(new Request('http://x/dash')); + assertEquals(res.status, 200); + assertEquals(await res.text(), '

Dash

'); + await app.close(); +}); + +Deno.test('@Html template mode renders', async () => { + const app = createApp({ modules: [M], views: dir }); + const res = await app.fetch(new Request('http://x/user')); + assertStringIncludes(await res.text(), 'Hi Deno'); + await app.close(); +}); + +// Deno has a filesystem, so `static` must not report the runtime as the reason for anything. +Deno.test('static: true builds a resolver instead of blaming the runtime', async () => { + const app = createApp({ modules: [], static: dir }); + const res = await app.fetch(new Request('http://x/asset.txt')); + assertEquals(res.status, 200); + assertEquals(await res.text(), 'served'); + await app.close(); +}); + +// The other half of the shim: `node:fs` above comes from `process.getBuiltinModule`, but `busboy` +// is an npm package and has to be resolved from the application's own `node_modules`. On JSR that +// failed as a `ReferenceError` under the catch that reports "busboy not installed" — the one +// diagnosis guaranteed to send a reader to reinstall a package they already have. +Deno.test('multipart resolves the busboy peer dependency instead of reporting it missing', async () => { + const { createApp: create, Route: R, Post, Module: Mod, body } = await import('../../src/index.ts'); + + @R('/') + class Upload { + @Post('/up') up(@body() b: { fields: Record; files: Record }) { + return { name: b.fields.name, filename: b.files.file.filename }; + } + } + + @Mod({ mountpoint: '/', controllers: [Upload] }) + class UploadMod {} + + const app = create({ modules: [UploadMod] }); + const form = new FormData(); + form.set('name', 'joe'); + form.set('file', new Blob([new Uint8Array([1, 2, 3])], { type: 'image/png' }), 'p.png'); + + const res = await app.fetch(new Request('http://x/up', { method: 'POST', body: form })); + assertEquals(res.status, 200); + assertEquals(await res.json(), { name: 'joe', filename: 'p.png' }); + await app.close(); +}); diff --git a/test/fixtures/views/asset.txt b/test/fixtures/views/asset.txt new file mode 100644 index 0000000..0d3564a --- /dev/null +++ b/test/fixtures/views/asset.txt @@ -0,0 +1 @@ +served \ No newline at end of file diff --git a/test/fixtures/views/dash.html b/test/fixtures/views/dash.html new file mode 100644 index 0000000..1288d45 --- /dev/null +++ b/test/fixtures/views/dash.html @@ -0,0 +1 @@ +

Dash

\ No newline at end of file diff --git a/test/fixtures/views/user.html b/test/fixtures/views/user.html new file mode 100644 index 0000000..d3e1277 --- /dev/null +++ b/test/fixtures/views/user.html @@ -0,0 +1 @@ +

Hi {{ name }}

\ No newline at end of file From e5d5fb801a1b34c1447f806b8098b7a2c5f14507 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 09:06:06 -0500 Subject: [PATCH 3/5] feat(shutdown): opt into SIGINT/SIGTERM with createApp({ handleSignals }) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The README promised shutdown was *"an extension point, not a SIGTERM handler you write"*. Half of it was true: `dispose()`, `onShutdown` and `hooks` all deliver the *content* of teardown, but nothing called `close()`, so every application still wrote the handler — and wrote it three times, because the spelling is per runtime. Forget it and the container is SIGKILLed after its grace period, every `dispose()` the registry so carefully ordered never runs, and nothing reports it. `createApp({ handleSignals: true })` registers SIGINT/SIGTERM to close and exit. Off by default, and that is the design rather than caution: a library that installs process-wide handlers behind your back is worse than one that installs none, because when the process exits is the application's call. Both halves are now supported and documented — keep the handler, or hand it over. What is not optional either way is that *something* calls `close()`, and the README now says so instead of implying the framework already had it covered. Declared once on `createApp`, wired per runtime by whichever boot call runs: `listen()`, `serveDeno()` and `serveBun()` each pass the closer that drains *their* server to `app.handleSignals`, which returns a close that also unregisters. On Deno that unregistering is load-bearing rather than tidy — a live `Deno.addSignalListener` holds the process open, so an app that closed itself would otherwise hang. Unregistering first also means a *second* signal falls through to the platform default and ends the process at once. That is deliberate: Ctrl-C twice is the way out of a teardown that is stuck, and swallowing it for the length of a 10s budget would read as a hang. An orchestrator sends SIGTERM once and then SIGKILL, so it never gets there. Tested against real processes, because a handler whose job is to exit its own process cannot be fired by hand in the runner: Node covers SIGTERM, SIGINT, the double-signal escape hatch and the default-off case; Deno covers `Deno.addSignalListener`/`Deno.exit`, which is the API that actually differs. Bun shares Node's `process` path. Closes #70. Signed-off-by: Diego Resendez --- README.md | 3 +- src/app/index.ts | 61 ++++++++++++++- src/app/types.ts | 9 +++ src/bun.ts | 6 +- src/deno.ts | 6 +- src/http/signals-shutdown.ts | 125 +++++++++++++++++++++++++++++++ test/deno-adapter.test.ts | 5 +- test/deno/signals.test.ts | 53 +++++++++++++ test/interop/_signal-app-deno.ts | 29 +++++++ test/interop/_signal-app.ts | 41 ++++++++++ test/shutdown-signals.test.ts | 112 +++++++++++++++++++++++++++ tsconfig.json | 2 +- 12 files changed, 445 insertions(+), 7 deletions(-) create mode 100644 src/http/signals-shutdown.ts create mode 100644 test/deno/signals.test.ts create mode 100644 test/interop/_signal-app-deno.ts create mode 100644 test/interop/_signal-app.ts create mode 100644 test/shutdown-signals.test.ts diff --git a/README.md b/README.md index c54acaa..9dfcc8e 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,8 @@ without growing the runtime dependency tree past `reflect-metadata`: - **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. -- **Shutdown is an extension point, not a `SIGTERM` handler you write.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. +- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. +- **The `SIGTERM` handler is yours to keep or to hand over.** All of the above runs from `close()`, and something has to call it — a container `SIGKILL`ed after its grace period skips every `dispose()` and reports nothing. Write the handler yourself and keep the control, or set `createApp({ handleSignals: true })` and the framework registers `SIGINT`/`SIGTERM` to close and exit for you. Off by default, because a library that installs process-wide handlers behind your back is worse than one that installs none. Turning it on also absorbs the last runtime difference an app has: `process.on` on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each — `listen()`, `serveDeno()` and `serveBun()` each wire it to the closer that drains *their* server. `close()` unregisters, so a second Ctrl-C ends a teardown that is stuck. - **Testable by construction.** `createApp({ overrides: { db: fakeDb } })` swaps any node in one line. - **Dual ESM + CommonJS.** Ships both builds behind an `exports` map — `import` and `require` both resolve, with matching type declarations. diff --git a/src/app/index.ts b/src/app/index.ts index 3a9e3e4..9e69c3e 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -13,6 +13,7 @@ import { isAsyncIterable } from '../channel'; import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { TeardownRegistry } from '../lifecycle'; +import { installSignalHandlers } from '../http/signals-shutdown'; import type { Hooks } from './types'; import { Ctor, @@ -139,6 +140,25 @@ export function createApp(opts: { * Must not exceed `shutdownTimeoutMs`; `createApp` throws rather than clamping silently. */ teardownTimeoutMs?: number; + /** + * Register `SIGINT`/`SIGTERM` to run `close()` and exit the process (default: `false`). + * + * Off by default because a library that installs process-wide handlers behind your back is worse + * than one that installs none — when the process exits is the application's call, not ours. Turn + * it on and the framework absorbs the last runtime difference an app otherwise has: `process.on` + * on Node and Bun, `Deno.addSignalListener` on Deno, and the matching `exit` for each. + * + * Leaving it off is a supported choice, not a gap — write the handler yourself if you want the + * control. What is *not* optional either way is that something calls `close()`: the teardown + * registry only runs from there, so a container `SIGKILL`ed after its grace period skips every + * `dispose()` the registry so carefully ordered, and reports nothing. + * + * Registered by `listen()`, `serveDeno()` and `serveBun()`, and taken back off by `close()` — + * so a *second* signal arriving mid-shutdown falls through to the platform default and ends the + * process at once. Ctrl-C twice is the way out of a teardown that is stuck; once is the way to + * let it finish. + */ + handleSignals?: boolean; /** * Where every framework diagnostic is written (default: structured JSON, human-readable on a TTY). * @@ -319,15 +339,52 @@ export function createApp(opts: { }); server.on('close', () => closeLinks(meshLinks)); await new Promise((resolve) => server!.listen(port, resolve)); + // After the socket is up, so a boot that throws never leaves a handler behind pointing at an + // app that never served. + handleSignals(close); return server; }; - const close = (options: { timeoutMs?: number } = {}): Promise => - closeApp(server, meshLinks, streams, options, opts.shutdownTimeoutMs, logger, teardown, opts.teardownTimeoutMs); + // Torn down by whichever close runs first, signal-driven or hand-called. On Deno that is + // load-bearing rather than tidy: a live `Deno.addSignalListener` keeps the process up, so an app + // that closed itself and expected to exit would simply hang. + let removeSignalHandlers: (() => void) | undefined; + + const clearSignalHandlers = (): void => { + removeSignalHandlers?.(); + removeSignalHandlers = undefined; + }; + + const close = (options: { timeoutMs?: number } = {}): Promise => { + clearSignalHandlers(); + return closeApp( + server, + meshLinks, + streams, + options, + opts.shutdownTimeoutMs, + logger, + teardown, + opts.teardownTimeoutMs, + ); + }; + + const handleSignals = Promise>(closer: T): T => { + if (!opts.handleSignals) return closer; + + const wrapped = ((options?: { timeoutMs?: number }) => { + clearSignalHandlers(); + return closer(options); + }) as T; + + removeSignalHandlers = installSignalHandlers(() => wrapped(), logger); + return wrapped; + }; return { listen, close, + handleSignals, ready, fetch: fetchFn, upgrade: upgradeFn, diff --git a/src/app/types.ts b/src/app/types.ts index 578f728..6e9626c 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -38,6 +38,15 @@ export interface Explain { export interface App { listen(port: number): Promise; close(options?: { timeoutMs?: number }): Promise; + /** + * Wires `SIGINT`/`SIGTERM` to `closer` and returns a close that also unregisters them — or + * returns `closer` untouched when `createApp({ handleSignals })` was not set. + * + * `listen()`, `serveDeno()` and `serveBun()` each call this with the closer that actually drains + * their server, which is why the option is declared once on `createApp` and works on all three. + * Call it yourself only if you serve the app some other way. + */ + handleSignals Promise>(closer: T): T; /** * Resolves the dependency graph, then returns. For a mesh app that means connecting to its * teapots and splicing their scopes in — a mesh graph is not knowable without asking. For every diff --git a/src/bun.ts b/src/bun.ts index 50f66d0..32e8b06 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -117,7 +117,10 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu // Object.assign rather than a fresh object: Bun.serve returns more than the ambient above // declares (reload, ref, unref, …), and rebuilding would silently drop whatever we did not name. return Object.assign(server, { - close: (closeOptions: { timeoutMs?: number } = {}): Promise => + // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this + // runtime's own signal API — and so the close it returns takes the handlers back off, which + // Deno requires to exit at all. + close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise => closeWithDeadline( // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // `app.close()` returns at its no-server guard on Bun, but still drains the teardown @@ -133,5 +136,6 @@ export function serveBun(app: App, options?: BunServeShortOptions): BunServeResu runtime: 'bun', }), ), + ), }); } diff --git a/src/deno.ts b/src/deno.ts index 4deca38..323a61c 100644 --- a/src/deno.ts +++ b/src/deno.ts @@ -76,7 +76,10 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { // Object.assign rather than a fresh object: Deno.serve returns more than the ambient above // declares (addr, ref, unref, …), and rebuilding would silently drop whatever we did not name. return Object.assign(server, { - close: (closeOptions: { timeoutMs?: number } = {}): Promise => + // Through `app.handleSignals` so that `createApp({ handleSignals: true })` reaches this + // runtime's own signal API — and so the close it returns takes the handlers back off, which + // Deno requires to exit at all. + close: app.handleSignals((closeOptions: { timeoutMs?: number } = {}): Promise => closeWithDeadline( // Drain, then hand over to the app so registered teardown runs — D7 of the teardown design. // `app.close()` returns at its no-server guard on Deno, but still drains the teardown @@ -101,5 +104,6 @@ export function serveDeno(app: App, options?: DenoServeOptions): DenoServer { { timeoutMs: ms, runtime: 'deno' }, ), ), + ), }); } diff --git a/src/http/signals-shutdown.ts b/src/http/signals-shutdown.ts new file mode 100644 index 0000000..dd6db30 --- /dev/null +++ b/src/http/signals-shutdown.ts @@ -0,0 +1,125 @@ +// src/http/signals-shutdown.ts — SIGINT/SIGTERM → close(), opt-in, one spelling per runtime. + +import type { Logger } from '../logger'; + +/** The two signals an orchestrator actually sends: Ctrl-C, and every container runtime's stop. */ +const SIGNALS = ['SIGINT', 'SIGTERM'] as const; + +type Signal = (typeof SIGNALS)[number]; + +interface SignalApi { + runtime: string; + on(signal: Signal, handler: () => void): void; + off(signal: Signal, handler: () => void): void; + exit(code: number): void; +} + +interface DenoSignals { + addSignalListener(signal: Signal, handler: () => void): void; + removeSignalListener(signal: Signal, handler: () => void): void; + exit(code: number): void; +} + +interface ProcessSignals { + on(signal: Signal, handler: () => void): unknown; + off?(signal: Signal, handler: () => void): unknown; + removeListener?(signal: Signal, handler: () => void): unknown; + exit(code: number): void; +} + +/** + * Deno first, on purpose. Its `node:process` shim does carry signal support, but `Deno.exit` and + * `Deno.addSignalListener` are the APIs Deno itself documents, and a listener registered natively + * is the one `removeSignalListener` can take back — which matters here, because a Deno signal + * listener holds the process open until it is removed. Node and Bun share `process`. + */ +function signalApi(): SignalApi | undefined { + const deno = (globalThis as { Deno?: DenoSignals }).Deno; + + if (typeof deno?.addSignalListener === 'function') + return { + runtime: 'deno', + on: (signal, handler) => deno.addSignalListener(signal, handler), + off: (signal, handler) => deno.removeSignalListener(signal, handler), + exit: (code) => deno.exit(code), + }; + + const proc = (globalThis as { process?: ProcessSignals }).process; + + if (typeof proc?.on === 'function' && typeof proc.exit === 'function') { + const remove = proc.off ?? proc.removeListener; + + return { + runtime: 'node', + on: (signal, handler) => void proc.on(signal, handler), + off: (signal, handler) => void remove?.call(proc, signal, handler), + exit: (code) => proc.exit(code), + }; + } + + return undefined; +} + +/** + * Registers SIGINT/SIGTERM to run `close` and then exit. Returns the function that takes those + * handlers back off — which is not optional bookkeeping on Deno, where a live signal listener keeps + * the process from exiting on its own. + * + * The close is expected to unregister first thing, which leaves a **second signal falling through + * to the platform default** — an immediate end to the process, teardown or no teardown. That is + * the escape hatch, and it is deliberate: a developer pressing Ctrl-C twice wants out now, and + * swallowing it for the length of a 10s shutdown budget would read as a hang. An orchestrator + * sends `SIGTERM` once and then `SIGKILL`, so it never reaches this path. + * + * If the close throws, the process still exits — with 1, because a shutdown that failed halfway is + * not a clean one and an orchestrator should be told. + */ +export function installSignalHandlers(close: () => Promise, logger: Logger): () => void { + const api = signalApi(); + + if (!api) { + logger.warn( + 'handleSignals: this runtime delivers no process signals, so nothing was registered — call close() yourself', + ); + return () => {}; + } + + const registered: Array<[Signal, () => void]> = []; + + const remove = (): void => { + while (registered.length) { + const [signal, handler] = registered.pop()!; + api.off(signal, handler); + } + }; + + for (const signal of SIGNALS) { + const handler = (): void => { + logger.info(`${signal} received — closing`, { signal, runtime: api.runtime }); + void close().then( + () => api.exit(0), + (error: unknown) => { + logger.error(`shutdown failed after ${signal}`, { + signal, + err: error instanceof Error ? error.message : String(error), + }); + api.exit(1); + }, + ); + }; + + try { + api.on(signal, handler); + registered.push([signal, handler]); + } catch (error) { + // Deno throws for SIGTERM on Windows, where the signal does not exist. Registering what the + // platform does have beats refusing to start over the one it does not. + logger.warn(`handleSignals: ${signal} is unavailable on this platform — skipping it`, { + signal, + err: error instanceof Error ? error.message : String(error), + }); + } + } + + return remove; +} diff --git a/test/deno-adapter.test.ts b/test/deno-adapter.test.ts index 568218d..2c9083e 100644 --- a/test/deno-adapter.test.ts +++ b/test/deno-adapter.test.ts @@ -29,7 +29,10 @@ it('snapshots connection metadata before Deno invalidates the upgraded request', }); const upgrade = vi.fn().mockResolvedValue(undefined); - serveDeno({ upgrade } as unknown as App); + // `handleSignals` is a pass-through here: this test is about upgrade metadata, and the identity + // it returns is exactly what `createApp` returns when `handleSignals` is left off. + const handleSignals = (closer: T): T => closer; + serveDeno({ upgrade, handleSignals } as unknown as App); const info = { get remoteAddr() { if (upgraded) throw new TypeError('Request closed'); diff --git a/test/deno/signals.test.ts b/test/deno/signals.test.ts new file mode 100644 index 0000000..ec8d7a3 --- /dev/null +++ b/test/deno/signals.test.ts @@ -0,0 +1,53 @@ +// `createApp({ handleSignals: true })` under the real Deno runtime. +// +// Deno is the runtime this option exists for. Node and Bun share `process.on`/`process.exit`; Deno +// has `Deno.addSignalListener`/`Deno.exit`, and its listeners hold the process open until removed — +// so an app that closed itself and forgot to unregister would hang here and nowhere else. +// +// Run with: npm run test:deno +import { assert, assertEquals } from 'jsr:@std/assert'; + +const HARNESS = 'test/interop/_signal-app-deno.ts'; + +async function run(): Promise<{ code: number; lines: string[] }> { + const child = new Deno.Command('deno', { + args: ['run', '--allow-all', '--no-check', HARNESS], + stdout: 'piped', + stderr: 'inherit', + }).spawn(); + + const lines: string[] = []; + let buffered = ''; + let signalled = false; + + const reader = child.stdout.pipeThrough(new TextDecoderStream()).getReader(); + const pump = (async () => { + while (true) { + const { value, done } = await reader.read(); + if (done) break; + buffered += value; + const parts = buffered.split('\n'); + buffered = parts.pop() ?? ''; + for (const line of parts.filter(Boolean)) { + lines.push(line); + if (!signalled && line.includes('"ready"')) { + signalled = true; + child.kill('SIGTERM'); + } + } + } + })(); + + const status = await child.status; + await pump; + return { code: status.code, lines }; +} + +Deno.test('SIGTERM runs teardown and exits 0 through Deno.addSignalListener', async () => { + const { code, lines } = await run(); + assert( + lines.some((l) => l.includes('"disposed"')), + `dispose() never ran — got: ${lines.join(' | ')}`, + ); + assertEquals(code, 0); +}); diff --git a/test/interop/_signal-app-deno.ts b/test/interop/_signal-app-deno.ts new file mode 100644 index 0000000..be61e5e --- /dev/null +++ b/test/interop/_signal-app-deno.ts @@ -0,0 +1,29 @@ +// Not a test — a Deno app with `handleSignals: true`, spawned by test/deno/signals.test.ts. +// Deno's test runner only discovers *.test.ts, so this file is ignored by `deno test`. +// +// It exists because Deno is where the signal API actually differs: `Deno.addSignalListener` and +// `Deno.exit` rather than `process.on`/`process.exit`, and a listener that holds the process open +// until it is removed. Node passing says nothing about any of that. +import 'npm:reflect-metadata'; +import { createApp, Module } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Module({ mountpoint: '/', controllers: [] }) +class Mod {} + +// A hook rather than a provider's `dispose()`: on Deno nothing boots until the first request, so an +// unvisited app has no provider to dispose and the run would pass without proving anything. The +// hook registers at `createApp`, which makes "teardown ran" mean "close() was reached". +const app = createApp({ + modules: [Mod], + handleSignals: true, + hooks: [{ onShutdown: () => console.log(JSON.stringify({ disposed: true })) }], +}); + +// `ready` is printed after `serveDeno` returns, not from `onListen` — Deno calls `onListen` +// synchronously from inside `Deno.serve`, so a parent that signals on that line races the handler +// registration that happens a few statements later and wins. +const server = serveDeno(app, { port: 0, onListen: () => {} }); + +console.log(JSON.stringify({ ready: true })); +void server; diff --git a/test/interop/_signal-app.ts b/test/interop/_signal-app.ts new file mode 100644 index 0000000..a77478c --- /dev/null +++ b/test/interop/_signal-app.ts @@ -0,0 +1,41 @@ +// Not a test — a Node app with `handleSignals: true`, spawned by shutdown-signals.test.ts. +// +// Signal handling can only be told apart from doing nothing by a real process that really gets a +// real signal: an in-process test would have to fire the handler by hand, and the handler's whole +// job is to exit the process it is running in. +// +// Prints one JSON line per event on stdout: {"ready":port}, then {"disposed":n} per dispose call. +import 'reflect-metadata'; +import { createApp, Provider, Route, Get, Module } from '../../src/index'; + +const SLOW = Number(process.env.DISPOSE_DELAY_MS ?? 0); +let disposals = 0; + +@Provider({ provides: 'db' }) +class Db { + provide() { + return { db: { name: 'db' } }; + } + + async dispose() { + if (SLOW) await new Promise((r) => setTimeout(r, SLOW)); + disposals++; + console.log(JSON.stringify({ disposed: disposals })); + } +} + +@Route('/') +class Api { + @Get('/ping') ping() { + return { ok: true }; + } +} + +@Module({ mountpoint: '/', controllers: [Api], providers: [Db] }) +class Mod {} + +const app = createApp({ modules: [Mod], handleSignals: process.env.HANDLE_SIGNALS !== 'false' }); + +void app.listen(0).then((server) => { + console.log(JSON.stringify({ ready: (server.address() as { port: number }).port })); +}); diff --git a/test/shutdown-signals.test.ts b/test/shutdown-signals.test.ts new file mode 100644 index 0000000..5afd6ca --- /dev/null +++ b/test/shutdown-signals.test.ts @@ -0,0 +1,112 @@ +import { describe, it, expect, afterEach } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { createApp, Module } from '../src'; + +@Module({ mountpoint: '/', controllers: [] }) +class Empty {} + +let app: ReturnType | undefined; +let child: ChildProcess | undefined; + +afterEach(async () => { + await app?.close(); + app = undefined; + child?.kill('SIGKILL'); + child = undefined; +}); + +const disposed = (r: { lines: string[] }) => r.lines.filter((l) => l.includes('"disposed"')); +const handled = (r: { lines: string[] }) => r.lines.some((l) => l.includes('received — closing')); +const listeners = () => process.listenerCount('SIGINT') + process.listenerCount('SIGTERM'); + +describe('handleSignals registration', () => { + it('registers nothing by default — a library must not own when the process exits', async () => { + const before = listeners(); + app = createApp({ modules: [Empty] }); + await app.listen(0); + expect(listeners()).toBe(before); + }); + + it('registers SIGINT and SIGTERM when asked, and takes both back off in close()', async () => { + const before = listeners(); + const opted = createApp({ modules: [Empty], handleSignals: true }); + await opted.listen(0); + expect(listeners()).toBe(before + 2); + + // Not tidiness: on Deno a live signal listener holds the process open, so an app that closed + // itself and expected to exit would hang. Node is where it is observable. + await opted.close(); + expect(listeners()).toBe(before); + }); +}); + +/** Boots the harness app, waits for its `ready` line, and resolves once it has exited. */ +function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwice = false) { + return new Promise<{ code: number | null; signal: NodeJS.Signals | null; lines: string[] }>((resolve, reject) => { + // `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further + // down, and on Linux the signal then lands on the wrapper while the app never hears it — which + // is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader` + // because it is the one form that works on both the Node 18 floor CI builds against and the + // current release. + const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], { + env: { ...process.env, ...env }, + stdio: ['ignore', 'pipe', 'inherit'], + }); + child = proc; + + const lines: string[] = []; + let ready = false; + let buffered = ''; + + proc.stdout.on('data', (chunk: Buffer) => { + buffered += chunk.toString(); + const parts = buffered.split('\n'); + buffered = parts.pop() ?? ''; + + for (const line of parts.filter(Boolean)) { + lines.push(line); + if (!ready && line.includes('"ready"')) { + ready = true; + proc.kill(signal); + if (sendTwice) setTimeout(() => proc.kill(signal), 20); + } + } + }); + + proc.on('error', reject); + proc.on('exit', (code, exitSignal) => resolve({ code, signal: exitSignal, lines })); + }); +} + +// These need a real process because the handler's job is to exit the one it runs in — firing it by +// hand in the test runner would either take the runner down or prove nothing. +describe('handleSignals end to end', () => { + it('SIGTERM runs teardown and exits 0', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGTERM'); + expect(disposed(r)).toHaveLength(1); + expect(r.code).toBe(0); + }); + + it('SIGINT does the same — Ctrl-C is not a different kind of shutdown', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGINT'); + expect(disposed(r)).toHaveLength(1); + expect(r.code).toBe(0); + }); + + // The escape hatch, and the reason `close()` unregisters before it starts draining: a second + // signal finds no handler and gets the platform default. Ctrl-C twice ends a stuck teardown + // rather than waiting out the whole shutdown budget. + it('lets a second signal end a shutdown that is still draining', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGTERM', { DISPOSE_DELAY_MS: '2000' }, true); + expect(handled(r)).toBe(true); // the first signal was ours + expect(disposed(r)).toHaveLength(0); // the second one did not wait for the 2s dispose + expect(r.code).not.toBe(0); + }); + + it('leaves the process to its default fate when handleSignals is off', { timeout: 20_000 }, async () => { + const r = await runHarness('SIGTERM', { HANDLE_SIGNALS: 'false' }); + expect(handled(r)).toBe(false); // nothing of ours ran at all + expect(disposed(r)).toHaveLength(0); + expect(r.code).not.toBe(0); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 8d268e0..0d0bf73 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -15,5 +15,5 @@ "forceConsistentCasingInFileNames": true }, "include": ["src", "test", "example"], - "exclude": ["test/deno", "test/bun", "test/edge"] + "exclude": ["test/deno", "test/bun", "test/edge", "test/interop/_signal-app-deno.ts"] } From 855e044d2ae1ed7a0ac1d566ef03ff8573326364 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 09:13:08 -0500 Subject: [PATCH 4/5] fix(types): export the extension-point types, not just the extension points MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `Transformer` was exported and `TransformerFn` was not, so a custom transformer could be attached but not typed. The workaround is to borrow the type off a value — `const text: typeof JsonTransformer = ...` — which works and reads like a trick, because it is one. `ErrorRenderer` and `StreamEncoder`, the two neighbouring extension points, were both already exported; this one was an oversight rather than a decision. Checking the rest of the barrel for the same shape turned up four more. A plugin split into named functions rather than one inline arrow cannot annotate what it receives: `Plugin` types the arrow, and `PluginApi`, `ScopeApi` and `ScopeNode` — the chain reached through `api.scope.add`, which is how a plugin contributes to the graph — were all unreachable. So was `Hooks`, which makes `createApp({ hooks })` typeable only inline, and `TeardownFn`, the shape every one of those three doors takes. Types only. Nothing at runtime moves, and no existing export changes. Covered by a type test that fails to compile if any of them leaves the barrel again, including the two that were already there — the failure mode this fixes is a barrel edit nobody notices until a user writes the annotation. Closes #66. Signed-off-by: Diego Resendez --- src/app/index.ts | 2 +- src/index.ts | 6 ++- test/types/extension-points.test.ts | 68 +++++++++++++++++++++++++++++ 3 files changed, 73 insertions(+), 3 deletions(-) create mode 100644 test/types/extension-points.test.ts diff --git a/src/app/index.ts b/src/app/index.ts index 9e69c3e..6da0056 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -41,7 +41,7 @@ import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { compilePattern } from '../http/router'; -export type { App, InspectLine, ExplainNode, Explain, MeshConfig } from './types'; +export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types'; type Runner = (ctx: any) => any; diff --git a/src/index.ts b/src/index.ts index 031a099..bbd0872 100644 --- a/src/index.ts +++ b/src/index.ts @@ -40,8 +40,10 @@ export { Options, Html, } from './metadata'; -export type { Transport, HttpMethod, RouteDecorator } from './metadata'; -export type { Plugin } from './plugin'; +export type { Transport, HttpMethod, RouteDecorator, TransformerFn } from './metadata'; +export type { Plugin, PluginApi, ScopeApi, ScopeNode } from './plugin'; +export type { Hooks } from './app'; +export type { TeardownFn } from './lifecycle'; // Transformers & error signals export { JsonTransformer } from './transformers'; diff --git a/test/types/extension-points.test.ts b/test/types/extension-points.test.ts new file mode 100644 index 0000000..272f4f6 --- /dev/null +++ b/test/types/extension-points.test.ts @@ -0,0 +1,68 @@ +// Every extension point the docs tell a user to write must be *typeable* from the package, not just +// callable. A decorator whose argument type is not exported can be passed a literal and nothing +// else — the shape has to be redeclared inline, or borrowed off a value with +// `typeof JsonTransformer`, which works and reads like a trick because it is one. +// +// This file's job is to fail to compile if one of them stops being exported. +import { test, expect } from 'vitest'; +import { + JsonTransformer, + type TransformerFn, + type Plugin, + type PluginApi, + type ScopeApi, + type ScopeNode, + type Hooks, + type TeardownFn, + type ErrorRenderer, + type StreamEncoder, +} from '../../src'; + +// @Transformer(fn) — the case that started this. Prometheus scrapes text, so a /metrics route +// needs its own transformer, and this is the annotation that was impossible to write. +const prometheusText: TransformerFn = (value) => ({ + status: 200, + headers: { 'content-type': 'text/plain; version=0.0.4; charset=utf-8' }, + body: String(value), +}); + +// A plugin split into named functions rather than one inline arrow: `Plugin` alone types the +// arrow, and nothing typed its argument. +function subscribe(api: PluginApi): void { + api.bus.on('request:end', () => {}); + api.onShutdown(flush); +} + +const flush: TeardownFn = () => {}; + +function contribute(scope: ScopeApi): void { + const node: ScopeNode = { kind: 'provider', name: 'metrics', needs: [], provides: ['metrics'], run: () => ({}) }; + scope.add(node); +} + +const metricsPlugin: Plugin = (api) => { + subscribe(api); + contribute(api.scope); +}; + +// createApp({ hooks }) — declared as a value, which is the point of the option. +const hooks: Hooks[] = [{ onShutdown: flush }]; + +// The two neighbouring extension points, already exported. Here so a future barrel edit that drops +// one is caught by the same test rather than by a user. +const renderError: ErrorRenderer = () => ({ status: 500, headers: {}, body: 'boom' }); +const encoder: StreamEncoder = { + headers: {}, + encode: (item) => String(item), + encodeError: (err) => String(err), +}; + +test('every extension point is typeable from the package barrel', () => { + expect(prometheusText('x').body).toBe('x'); + expect(typeof metricsPlugin).toBe('function'); + expect(hooks).toHaveLength(1); + expect(renderError(new Error('boom'), {} as never)?.status).toBe(500); + expect(encoder.encode(1)).toBe('1'); + // The workaround the missing export forced, kept as a reminder of what it replaced. + expect(typeof JsonTransformer).toBe('function'); +}); From b8b3548f15ba7093a84b4321ade525e6bfd1b603 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 1 Sep 2026 09:27:32 -0500 Subject: [PATCH 5/5] perf(cors): resolve the request's headers once, not two or three times MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `security` and `cors` were computed twice for every request and three times for a preflight: once in the adapter, to seed the headers a response written *above* `handle()` still has to carry — a shed 503, a 413 from the body reader — and again in `dispatch`, plus a third time inside `corsPreflightHeaders`. Nothing was incorrect, because the predicate is expected to be pure with respect to one request. The cost is that `cors.origins` is a predicate precisely so it can be a lookup: an allowlist in Redis, a tenant query. The framework charged the caller's latency budget and their backend two to three times for an answer whose inputs did not change in between, and made a predicate with a counter in it count double. `handle()` now takes the headers the adapter already computed and hands them down, with `computeInjected` kept as the fallback for a caller that has none. `corsPreflightHeaders` extends that result instead of re-deriving it. The Node adapter was carrying its own copy of `computeInjected`, inlined; it uses the real one now, which is what removes the duplicate rather than papering over it. Measured against the built `dist/`, same script that produced the numbers in the issue: GET with Origin 2x -> 1x OPTIONS preflight 3x -> 1x buildFetch, Origin 2x -> 1x GET without Origin 0x -> 0x (never reached the predicate; unchanged) The risk here is not the call count, it is that `injected` carries the security headers onto every response shape — so the tests that matter are the existing ones across `transport-security`, `http-headers`, `fetch`, `parity` and `web-stream`, all green. The two new tests assert the count directly, on both adapters, which is the assertion that keeps it from drifting back. Closes #77. Signed-off-by: Diego Resendez --- src/http/core.ts | 17 ++++++++++++----- src/http/server.ts | 37 +++++++++++++++++++----------------- src/http/web.ts | 42 ++++++++++++++++++++++++----------------- src/security.ts | 8 ++++++-- test/http.test.ts | 35 ++++++++++++++++++++++++++++++++++ test/web-stream.test.ts | 22 +++++++++++++++++++++ 6 files changed, 120 insertions(+), 41 deletions(-) diff --git a/src/http/core.ts b/src/http/core.ts index f0264fb..ad7e732 100644 --- a/src/http/core.ts +++ b/src/http/core.ts @@ -212,6 +212,7 @@ export function handle( routes: RouteDef[], opts: HttpOptions | undefined, req: NeutralRequest, + injected?: Record, ): Promise { const bus = opts?.bus; @@ -227,10 +228,10 @@ export function handle( bus.hasListeners('route:unmatched') ) ) { - return dispatch(routes, opts, req, undefined, undefined); + return dispatch(routes, opts, req, undefined, undefined, injected); } - return observedDispatch(routes, opts, req, bus); + return observedDispatch(routes, opts, req, bus, injected); } async function observedDispatch( @@ -238,6 +239,7 @@ async function observedDispatch( opts: HttpOptions | undefined, req: NeutralRequest, bus: Bus, + injected?: Record, ): Promise { const watchingEnd = bus.hasListeners('request:end'); const startedAt = watchingEnd ? performance.now() : 0; @@ -251,7 +253,7 @@ async function observedDispatch( traceId: req.traceId, }); - const result = await dispatch(routes, opts, req, bus, trace); + const result = await dispatch(routes, opts, req, bus, trace, injected); if (watchingEnd) { // A preflight is a 204 the router never routed; a stream has no status of its own and is a 200 @@ -277,8 +279,13 @@ async function dispatch( req: NeutralRequest, bus: Bus | undefined, trace: Trace | undefined, + precomputed?: Record, ): Promise { - const injected = computeInjected(opts, req); + // Both adapters compute this before routing, because a response written above `handle()` — a + // shed 503, a 413 from the body reader — has to carry the same headers as one written below it. + // Recomputing here would run `security` and, worse, the `origins` predicate a second time for + // one request. `computeInjected` stays as the fallback for callers that have nothing yet. + const injected = precomputed ?? computeInjected(opts, req); let path: string; try { @@ -288,7 +295,7 @@ async function dispatch( } if (opts?.cors && req.method === 'OPTIONS' && req.headers['access-control-request-method']) { - return { preflight: corsPreflightHeaders(opts.cors, req, opts.logger) }; + return { preflight: corsPreflightHeaders(opts.cors, req, injected) }; } const matched = resolveRoute(routes, req.method, path); diff --git a/src/http/server.ts b/src/http/server.ts index 6f9033d..7b5202e 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -3,12 +3,11 @@ import type https from 'https'; import { createRequestGate } from './request-gate'; import { renderError, type ErrorRequest } from '../transformers'; import type { Bus } from '../bus'; -import { buildSecurityHeaders, resolveCors } from '../security'; import { readBody as readBodyBytes, deriveSecure, deriveIp } from './request'; import { pipeStream } from './stream'; import { attachWs } from './ws'; import { mergeInjectedHeaders } from './headers'; -import { handle, correlateRequest, type HandleResult, type Preflight } from './core'; +import { handle, correlateRequest, computeInjected, type HandleResult, type Preflight } from './core'; import type { BodyFailure, BodyReader } from './body'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import { nodeRequire } from '../node-require'; @@ -95,13 +94,12 @@ function createRequestHandler(cfg: HandlerConfig) { const secure = deriveSecure(req, trustProxy); // Derived before the body is read, so a 413 rejected below still carries an identity. const correlation = correlateRequest(req.headers); - const injected: Record = { ...buildSecurityHeaders(opts?.security ?? true, secure) }; + // One computation for the whole request: this object is patched into every response below, and + // handed to `handle()` so routing does not derive it a second time — `security` is pure, but + // `cors.origins` may be a predicate with a network call in it. + const injected = computeInjected(opts, { secure, headers: req.headers }); 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, opts?.logger)); - let result: HandleResult | Preflight; let acquired = false; const watchingEnd = bus?.hasListeners('request:end') ?? false; @@ -138,16 +136,21 @@ function createRequestHandler(cfg: HandlerConfig) { gate.release(); }); - result = await handle(routes, opts, { - ...correlation, - method: req.method ?? 'GET', - url: req.url ?? '/', - headers: req.headers, - readBody, - source: req, - secure, - ip: deriveIp(req, trustProxy), - }); + result = await handle( + routes, + opts, + { + ...correlation, + method: req.method ?? 'GET', + url: req.url ?? '/', + headers: req.headers, + readBody, + source: req, + secure, + ip: deriveIp(req, trustProxy), + }, + injected, + ); } finally { if (acquired) { acquired = false; diff --git a/src/http/web.ts b/src/http/web.ts index 69139a5..15bfdc5 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -173,23 +173,31 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) { acquired = true; - result = await handle(routes, opts, { - ...correlation, - method: request.method, - url: path, - headers, - readBody, - source: request, - secure, - // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the proxy is - // trusted, and take its first hop — an untrusted XFF is client-spoofable, and there's no socket - // peer address to fall back to on the fetch path, so the untrusted case is simply ''. - ip: opts?.trustProxy - ? String(headers['x-forwarded-for'] ?? '') - .split(',')[0] - .trim() - : '', - }); + result = await handle( + routes, + opts, + { + ...correlation, + method: request.method, + url: path, + headers, + readBody, + source: request, + secure, + // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the + // proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and + // there's no socket peer address to fall back to on the fetch path, so the untrusted case + // is simply ''. + ip: opts?.trustProxy + ? String(headers['x-forwarded-for'] ?? '') + .split(',')[0] + .trim() + : '', + }, + // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to + // one call per request. + injected, + ); } finally { // Release when routing/handling finishes, not when a returned stream finishes. // Long-lived streams therefore do not permanently consume the request budget. diff --git a/src/security.ts b/src/security.ts index 8dee23a..f36e809 100644 --- a/src/security.ts +++ b/src/security.ts @@ -128,9 +128,13 @@ export function resolveCors( export function corsPreflightHeaders( opts: CorsOptions, req: { headers: Record }, - logger?: Logger, + resolved?: Headers, ): Headers { - const headers = resolveCors(opts, req, logger); + // The caller has almost always resolved CORS already, one layer up, to seed the headers every + // response carries. Re-deriving here would consult `origins` a second time for the same request — + // and `origins` may be a predicate doing a network lookup. Copied rather than used in place: the + // preflight-only keys below belong to this 204, not to the shared object. + const headers: Headers = { ...resolved }; if (!headers['access-control-allow-origin']) return headers; // origin not allowed → bare 204 headers['access-control-allow-methods'] = (opts.methods ?? ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']).join( ', ', diff --git a/test/http.test.ts b/test/http.test.ts index 1e7bfc8..ff92d89 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -384,4 +384,39 @@ describe('request hardening', () => { server.close(); }); + + // `origins` is a predicate because the shapes it exists for are lookups — an allowlist in Redis, a + // tenant query. Running one twice for a GET and three times for a preflight charges the caller's + // latency budget and their backend for an answer whose inputs did not change in between. + it('consults a cors.origins predicate once per request, not once per header computation', async () => { + let calls = 0; + const server = createHttpServer( + [{ method: 'GET', pattern: '/ping', transport: 'buffer', handler }], + [], undefined, undefined, + { cors: { origins: () => { calls++; return true; } } }, + ); + await new Promise((r) => server.listen(0, r)); + const origin = { origin: 'https://a.com' }; + + const plain = await fetch(`${getUrl(server)}/ping`, { headers: origin }); + expect(plain.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(calls).toBe(1); + + calls = 0; + const preflight = await fetch(`${getUrl(server)}/ping`, { + method: 'OPTIONS', headers: { ...origin, 'access-control-request-method': 'GET' }, + }); + expect(preflight.status).toBe(204); + expect(preflight.headers.get('access-control-allow-methods')).toContain('GET'); + expect(preflight.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(calls).toBe(1); + + // No Origin header never reaches the predicate at all — that part was already right. + calls = 0; + await fetch(`${getUrl(server)}/ping`); + expect(calls).toBe(0); + + server.close(); + }); + }); diff --git a/test/web-stream.test.ts b/test/web-stream.test.ts index 54481f8..cbb2991 100644 --- a/test/web-stream.test.ts +++ b/test/web-stream.test.ts @@ -166,6 +166,28 @@ describe('buildFetch request gate', () => { const afterRelease = await fetchHandler(new Request('http://localhost/slow')); expect(afterRelease.status).toBe(200); }); + it('consults a cors.origins predicate once per request on the fetch path too', async () => { + let calls = 0; + const fetchHandler = buildFetch( + [{ method: 'GET', pattern: '/ok', transport: 'buffer', + handler: async () => ({ status: 200, headers: {}, body: 'ok' }) }], + { cors: { origins: () => { calls++; return true; } } }, + ); + + const res = await fetchHandler(new Request('http://localhost/ok', { headers: { origin: 'https://a.com' } })); + expect(res.headers.get('access-control-allow-origin')).toBe('https://a.com'); + expect(calls).toBe(1); + + calls = 0; + const preflight = await fetchHandler(new Request('http://localhost/ok', { + method: 'OPTIONS', + headers: { origin: 'https://a.com', 'access-control-request-method': 'GET' }, + })); + expect(preflight.status).toBe(204); + expect(preflight.headers.get('access-control-allow-methods')).toContain('GET'); + expect(calls).toBe(1); + }); + it('releases the slot when a streaming handler returns', async () => { async function* stream() { yield { n: 1 };