From 1f95de055372120abc9fd6d6f481705028aa327a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:19:45 -0600 Subject: [PATCH 01/41] fix(mesh): gate route RPCs on method and pattern The teapot matched an exported route on its pattern only, then ran the route for whatever method the peer sent, so exporting GET /x let an authenticated teacup call an unexported DELETE /x. Gate on "${method} ${pattern}". A teacup already sends HEAD on a remote GET as that GET (D16), so no HEAD mapping is needed. Refs: GHSA-4q43-x4fp-c273 Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 +++++++ src/mesh/teapot.ts | 5 ++++- test/mesh/teapot.test.ts | 24 ++++++++++++++++++++++++ 3 files changed, 35 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bcf4794..14b9864 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,13 @@ npm treats versions as semver and semver forbids leading zeros. ## [Unreleased] +### Security + +- **Mesh: a teapot checks the HTTP method of a route RPC, not just its pattern** + (GHSA-4q43-x4fp-c273). Exporting `GET /items/:id` let an authenticated teacup run an unexported + `DELETE /items/:id`, because the gate matched the pattern and the route ran for whatever method + the peer sent. Mesh is `@experimental`; no API change. + ## [26.11.0-rc.1] - 2026-11-17 ### Breaking diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 3984739..16da08e 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -178,7 +178,10 @@ function resolveRpc( return deps.resolveScope(name, ctx); } - if (![...exportedRoutes].some((key) => key.endsWith(` ${name}`))) throw notExported(name); + // Method and pattern, both: the route is run for the method the peer sends, so gating on the + // pattern alone let an export of `GET /x` reach an unexported `DELETE /x`. A teacup sends a HEAD + // on a remote GET as that GET (D16), so no HEAD mapping is needed here. + if (!exportedRoutes.has(`${ctx?.method} ${name}`)) throw notExported(name); return deps.resolveRoute(name, ctx); } diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index 8114dde..a3a1af4 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -134,6 +134,30 @@ describe('createMeshControl', () => { expect(res.error.status).toBe(403); }); + it('serves an exported route for its exported method', async () => { + const resolveRoute = vi.fn(async () => ({ status: 200, headers: {}, body: 'ok' })); + const t = fakeSocket(); + make({ resolveRoute }).handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: 'r1', kind: 'route', name: '/u/:id', ctx: { method: 'GET' } }); + expect(t.sent.find((f: any) => f.type === 'rpc-res')).toMatchObject({ id: 'r1', ok: true }); + expect(resolveRoute).toHaveBeenCalledOnce(); + }); + + it('refuses another method on an exported pattern without running it', async () => { + const resolveRoute = vi.fn(async () => ({ status: 200, headers: {}, body: 'ran' })); + const t = fakeSocket(); + make({ resolveRoute }).handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + for (const method of ['DELETE', 'POST', 'get', undefined]) { + await t.deliver({ type: 'rpc-req', id: String(method), kind: 'route', name: '/u/:id', ctx: { method } }); + } + const res = t.sent.filter((f: any) => f.type === 'rpc-res'); + expect(res).toHaveLength(4); + expect(res.every((f: any) => !f.ok && f.error.status === 403)).toBe(true); + expect(resolveRoute).not.toHaveBeenCalled(); + }); + it('propagates a thrown HttpError status in the error frame', async () => { const t = fakeSocket(); make({ From 07351683c58b0eb2400d598e46e6db7ae66e3dd4 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:20:10 -0600 Subject: [PATCH 02/41] fix(bus): isolate async listeners that reject Bus.emit caught a listener's synchronous throw, but an async listener fails by returning a rejected promise. Unhandled, that rejection exits Node with code 1, so one broken plugin listener killed the process on the first request. Attach a no-op rejection handler when a listener returns a thenable. Closes #70 Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 +++++++ src/bus.ts | 8 +++++++- test/bus.test.ts | 19 +++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 14b9864..417df6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,13 @@ npm treats versions as semver and semver forbids leading zeros. `DELETE /items/:id`, because the gate matched the pattern and the route ran for whatever method the peer sent. Mesh is `@experimental`; no API change. +### Fixed + +- **An async bus listener that rejects no longer exits the Node process** (#70). `Bus.emit` isolated + a listener that threw, but an `async` listener fails by rejecting, and that rejection went + unhandled, so a plugin's `on('request:end', async () => { throw … })` killed the process on the + first request. A rejection is now swallowed like a throw. + ## [26.11.0-rc.1] - 2026-11-17 ### Breaking diff --git a/src/bus.ts b/src/bus.ts index 002fd5d..9758a1a 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -193,7 +193,13 @@ export class Bus { emit(event: LifecycleEvent, payload: EventPayload): void { for (const listener of this.listeners.get(event) ?? []) { try { - listener(payload); + // An async listener's failure arrives as a rejection, not a throw. Unhandled, it exits Node + // (#70), so it gets the same isolation as a sync throw. + const result: unknown = listener(payload); + + if (typeof (result as PromiseLike | undefined)?.then === 'function') { + (result as PromiseLike).then(undefined, () => {}); + } } catch { /* observers must never break the pipeline */ } diff --git a/test/bus.test.ts b/test/bus.test.ts index addf68b..21aaf1e 100644 --- a/test/bus.test.ts +++ b/test/bus.test.ts @@ -26,3 +26,22 @@ test('a throwing subscriber does not break emit for others', () => { expect(() => bus.emit('request:step:error', { name: 's' })).not.toThrow(); expect(good).toHaveBeenCalled(); }); + +test('an async subscriber that rejects is isolated too (#70)', async () => { + const bus = new Bus(); + const unhandled = vi.fn(); + process.on('unhandledRejection', unhandled); + try { + const good = vi.fn(); + bus.on('request:end', async () => { + throw new Error('boom'); + }); + bus.on('request:end', good); + expect(() => bus.emit('request:end', { name: 'r' })).not.toThrow(); + expect(good).toHaveBeenCalled(); + await new Promise((resolve) => setTimeout(resolve, 10)); + expect(unhandled).not.toHaveBeenCalled(); + } finally { + process.off('unhandledRejection', unhandled); + } +}); From cf5b225bf15a3c4be21f82cf9e50294b980060da Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:22:01 -0600 Subject: [PATCH 03/41] fix(bun): keep quiet SSE and ndjson streams open Bun.serve cuts a request idle for idleTimeout (10s by default), which is shorter than the 15s SSE keep-alive ping, so a stream that went quiet was dropped with ECONNRESET. serveBun now calls server.timeout(request, 0) for stream responses only, so buffered requests keep Bun's idle protection. The method is cast locally to leave the exported BunServer type unchanged. Closes #71 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ src/bun.ts | 14 +++++++++++++- test/bun/sse-idle.test.ts | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) create mode 100644 test/bun/sse-idle.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 417df6b..f154d58 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,11 @@ npm treats versions as semver and semver forbids leading zeros. unhandled, so a plugin's `on('request:end', async () => { throw … })` killed the process on the first request. A rejection is now swallowed like a throw. +- **Bun no longer drops an SSE or ndjson stream that goes quiet for 10 seconds** (#71). `Bun.serve` + cuts a request idle for `idleTimeout` (10s by default), which is shorter than the 15s keep-alive + ping, so the client got `ECONNRESET`. `serveBun` now lifts the idle timeout for stream responses + only; buffered requests keep it. + ## [26.11.0-rc.1] - 2026-11-17 ### Breaking diff --git a/src/bun.ts b/src/bun.ts index b2d71d6..a0128ab 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -68,6 +68,9 @@ export interface BunServeOptions { } declare const Bun: { serve(options: BunNativeServeOptions): BunServer }; +/** Responses that stay open between writes: SSE and ndjson streams. */ +const STREAM_CONTENT_TYPE = /^(text\/event-stream|application\/x-ndjson)/; + /** Per-connection state stashed on ws.data between fetch (upgrade) and the open/message/close callbacks. */ interface BunConnData { wsReq: WsRequest; @@ -137,7 +140,16 @@ export async function serveBun(app: App, options?: BunServeOptions): Promise { + // Bun cuts a request idle for `idleTimeout` (default 10s), shorter than the SSE keep-alive + // ping, so a quiet stream was dropped (#71). Lift it for streams only: buffered requests keep + // Bun's idle protection. `timeout` is cast locally so the exported `BunServer` type stays as is. + if (STREAM_CONTENT_TYPE.test(response.headers.get('content-type') ?? '')) { + (server as BunServer & { timeout?(request: Request, seconds: number): void }).timeout?.(request, 0); + } + + return response; + }); }, websocket: { // The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before diff --git a/test/bun/sse-idle.test.ts b/test/bun/sse-idle.test.ts new file mode 100644 index 0000000..690b8f8 --- /dev/null +++ b/test/bun/sse-idle.test.ts @@ -0,0 +1,35 @@ +// #71: Bun.serve cuts a request idle for `idleTimeout` seconds (default 10), shorter than the SSE +// keep-alive ping (15s), so a quiet stream was dropped. `idleTimeout: 2` stands in for the default so +// the test does not wait 10s. Bun checks idleness coarsely (a 2.5s gap survived `idleTimeout: 1`), +// so the stream stays quiet for 6s: without the fix it is cut at about 4s. +// +// Run with: npm run test:bun (or: bun test test/bun/) +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createApp, Route, Module, Sse } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +@Route('/') +class Ctl { + @Sse('/quiet') quiet() { + return (async function* () { + yield { t: 1 }; + await Bun.sleep(6000); + yield { t: 2 }; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +test('serveBun keeps a quiet SSE stream open past Bun idleTimeout (#71)', async () => { + const server = await serveBun(createApp({ modules: [M] }), { port: 0, idleTimeout: 2 } as never); + try { + const res = await fetch(`http://127.0.0.1:${server.port}/quiet`, { headers: { accept: 'text/event-stream' } }); + const text = await res.text(); + expect(text).toContain('data: {"t":1}'); + expect(text).toContain('data: {"t":2}'); + } finally { + await server.close({ timeoutMs: 500 }); + } +}, 10_000); From ebb56d50b62609043caf39a76b503b2354ba38e1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:26:08 -0600 Subject: [PATCH 04/41] fix(ws): refuse cross-site WebSocket upgrades No adapter checked the Origin header, so a page on any site could open a WebSocket carrying the signed-in user's cookies and read what the handler streamed. CORS does not apply to WebSockets. An upgrade is now accepted when it has no Origin (not a browser), an Origin on the request's own host, or one cors.origins allows; anything else, Origin: null included, gets 403. Node checks in routeUpgrade; the fetch adapters (Deno, Bun, edge) check before upgrading, through a symbol-keyed check the app sets, like TLS_REQUESTED. The mesh control channel is exempt because it authenticates with its secret. The public API report is unchanged. Tests on Node, Deno, Bun and edge. Refs: GHSA-p697-fpqx-pgf3 Signed-off-by: Diego Resendez --- CHANGELOG.md | 9 +++++ README.md | 1 + src/app/index.ts | 14 ++++++- src/bun.ts | 5 ++- src/deno.ts | 5 ++- src/edge.ts | 4 ++ src/http/server.ts | 2 +- src/http/ws.ts | 17 +++++++- src/security.ts | 49 +++++++++++++++++++++++ test/bun/ws-origin.test.ts | 51 ++++++++++++++++++++++++ test/deno/ws-origin.test.ts | 60 ++++++++++++++++++++++++++++ test/edge/run.ts | 11 ++++++ test/ws-origin.test.ts | 79 +++++++++++++++++++++++++++++++++++++ 13 files changed, 302 insertions(+), 5 deletions(-) create mode 100644 test/bun/ws-origin.test.ts create mode 100644 test/deno/ws-origin.test.ts create mode 100644 test/ws-origin.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index f154d58..ce06215 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,15 @@ npm treats versions as semver and semver forbids leading zeros. `DELETE /items/:id`, because the gate matched the pattern and the route ran for whatever method the peer sent. Mesh is `@experimental`; no API change. +- **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, + Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket + with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket + hijacking); CORS does not apply to WebSockets. An upgrade is now accepted when it carries no + `Origin` (not a browser), an `Origin` on the same host as the request, or one `cors.origins` + allows. `Origin: null` is refused. The mesh control channel is exempt: it authenticates with its + secret. **Behaviour change:** a browser client served from another origin, or an app behind a proxy + that rewrites `Host`, now needs that origin in `cors.origins`. No API change. + ### Fixed - **An async bus listener that rejects no longer exits the Node process** (#70). `Bus.emit` isolated diff --git a/README.md b/README.md index fb0ed1a..b9ff36d 100644 --- a/README.md +++ b/README.md @@ -139,6 +139,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag. - **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you. +- **WebSocket upgrades from another site are refused** with `403`. A browser sends cookies with any page's upgrade and CORS does not cover WebSockets, so an upgrade carrying an `Origin` must come from the same host or from an origin `cors.origins` allows. Clients that send no `Origin` (servers, CLIs) are unaffected. Behind a proxy that rewrites `Host`, list your public origin in `cors.origins`. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. diff --git a/src/app/index.ts b/src/app/index.ts index 3b12075..56fff5a 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -45,7 +45,14 @@ import { getArgs, getHandlerNeeds, resolveArgs } from '../params'; import { buildOpenApi, type OpenApiInfo } from '../openapi'; import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; -import { TLS_REQUESTED, type TlsOptions, type SecurityOptions, type CorsOptions } from '../security'; +import { + TLS_REQUESTED, + WS_ORIGIN_CHECK, + wsOriginAllowed, + type TlsOptions, + type SecurityOptions, + type CorsOptions, +} from '../security'; import { buildRemote, type RemoteRoute as TeacupRemoteRoute } from '../mesh/teacup'; import { buildManifest, @@ -536,6 +543,11 @@ export function createApp(opts: AppOptions): App { // `serveDeno` and `serveBun` refuse an app that asked for TLS only Node's listener can give. [TLS_REQUESTED]: Boolean(opts.tls), + + // The fetch adapters refuse a cross-site upgrade before accepting it (GHSA-p697-fpqx-pgf3). The + // mesh control channel is exempt: it authenticates with its secret, not with cookies. + [WS_ORIGIN_CHECK]: (origin: string | null, host: string, path: string): boolean => + path === MESH_CONTROL_PATH || wsOriginAllowed(origin, host, opts.cors, logger), }); } diff --git a/src/bun.ts b/src/bun.ts index a0128ab..5cac9e0 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -1,7 +1,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; -import { refuseTls } from './security'; +import { refuseTls, refuseWsOrigin } from './security'; import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, @@ -129,6 +129,9 @@ export async function serveBun(app: App, options?: BunServeOptions): Promise { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const refused = refuseWsOrigin(app, request); + if (refused) return refused; + // Deno invalidates request connection metadata as soon as the upgrade is accepted. const wsRequest = toWsRequest(request, info.remoteAddr.hostname); const { socket, response } = Deno.upgradeWebSocket(request); diff --git a/src/edge.ts b/src/edge.ts index 8f141d4..635db24 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -2,6 +2,7 @@ import type { App } from './app/types'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { setProxyClient } from './http/peer'; import { MARK_EDGE } from './http/compression'; +import { refuseWsOrigin } from './security'; // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Declares only what we call; mirrors the real workerd signatures. @@ -36,6 +37,9 @@ export function edgeHandler( return (request, _env, ctx) => { if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const refused = refuseWsOrigin(app, request); + if (refused) return refused; + const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket]; server.accept(); // No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`. diff --git a/src/http/server.ts b/src/http/server.ts index db2c81b..98d5027 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -88,7 +88,7 @@ export function createHttpServer( server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; - attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits); + attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits, opts?.cors, opts?.logger); return server; } diff --git a/src/http/ws.ts b/src/http/ws.ts index 30f40d7..c6c5883 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -17,6 +17,8 @@ import type { WsRouteDef, MeshControl, RequestLimits } from './types'; import { normalizeRequestPath } from './router'; import { nodeRequire } from '../node-require'; import { MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot'; +import { wsOriginAllowed, type CorsOptions } from '../security'; +import type { Logger } from '../logger'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ function loadWss(): any | null { @@ -177,6 +179,8 @@ export function attachWs( meshControl?: MeshControl, streams?: Set<() => void>, limits?: RequestLimits, + cors?: CorsOptions, + logger?: Logger, ): void { if (wsRoutes.length === 0 && !meshControl) return; const WebSocketServer = loadWss(); @@ -200,7 +204,7 @@ export function attachWs( // Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an // uncaught exception that takes the whole process down, not a 500 for one client. try { - routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head); + routeUpgrade({ wss, meshWss, wsRoutes, bus, meshControl, streams, limits, cors, logger }, req, socket, head); } catch { if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error'); else socket.destroy(); @@ -218,6 +222,8 @@ interface UpgradeEnv { meshControl?: MeshControl; streams?: Set<() => void>; limits?: RequestLimits; + cors?: CorsOptions; + logger?: Logger; } /** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */ @@ -244,6 +250,15 @@ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, h return; } + // Cross-site WebSocket hijacking guard (GHSA-p697-fpqx-pgf3), after the control channel, which + // authenticates with its secret rather than cookies. The fetch adapters run the same check. + const origin = req.headers.origin; + + if (!wsOriginAllowed(origin, req.headers.host, env.cors, env.logger)) { + rejectUpgrade(socket, 403, 'Forbidden'); + return; + } + const route = matchWsRoute(wsRoutes, path); if (!route) { diff --git a/src/security.ts b/src/security.ts index 45d866e..e7cb3be 100644 --- a/src/security.ts +++ b/src/security.ts @@ -27,6 +27,55 @@ export function refuseTls(app: object, adapter: string): void { } } +/** + * Set on every app to the function the fetch adapters (`serveDeno`, `serveBun`, `edgeHandler`) call + * before they accept a WebSocket upgrade: `(origin, host, path) => allowed`. Symbol-keyed because it + * is adapter plumbing; see {@link wsOriginAllowed} and {@link refuseWsOrigin}. + */ +export const WS_ORIGIN_CHECK: unique symbol = Symbol.for('green-tea.ws-origin-check'); + +/** + * Whether a WebSocket upgrade from `origin` may be accepted (GHSA-p697-fpqx-pgf3). + * + * A browser attaches the site's cookies to an upgrade started by any page, and CORS does not apply to + * WebSockets, so without this check a page on another site could open a socket as the signed-in user + * (cross-site WebSocket hijacking). Allowed: no `Origin` at all (not a browser), the same host the + * request was sent to, or an origin `cors.origins` allows. Everything else, `null` included, is refused. + */ +export function wsOriginAllowed( + origin: string | null | undefined, + host: string | null | undefined, + cors?: CorsOptions, + logger?: Logger, +): boolean { + if (!origin) return true; + if (!isValidOrigin(origin)) return false; + + try { + if (host && new URL(origin).host === host.toLowerCase()) return true; + } catch { + return false; + } + + return cors ? originAllowed(cors.origins, origin, logger) : false; +} + +/** For the fetch adapters: a `403` to return instead of upgrading, or `undefined` to go ahead. */ +export function refuseWsOrigin(app: object, request: Request): Response | undefined { + const check = (app as { [WS_ORIGIN_CHECK]?: (origin: string | null, host: string, path: string) => boolean })[ + WS_ORIGIN_CHECK + ]; + const url = new URL(request.url); + + // The URL's host, not the `Host` header: Deno and Bun build the URL from that header anyway, and on + // the edge the URL is the one the client asked for while `Host` may name an internal hop. + if (!check || check(request.headers.get('origin'), url.host, url.pathname)) { + return undefined; + } + + return new Response('Forbidden', { status: 403 }); +} + /** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */ export interface CorsOptions { origins: string | string[] | '*' | ((origin: string) => boolean); diff --git a/test/bun/ws-origin.test.ts b/test/bun/ws-origin.test.ts new file mode 100644 index 0000000..7e42dc9 --- /dev/null +++ b/test/bun/ws-origin.test.ts @@ -0,0 +1,51 @@ +// GHSA-p697-fpqx-pgf3 on serveBun: a cross-site WebSocket upgrade is refused with 403 before Bun +// upgrades it. Same cases as test/ws-origin.test.ts (Node). +// +// Run with: npm run test:bun (or: bun test test/bun/) +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import net from 'node:net'; +import { createApp, Route, Ws, Module, ctx } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +@Route('/') +class Ctl { + @Ws('/echo') echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield msg; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +function upgradeStatus(port: number, origin?: string): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1', () => { + socket.write( + `GET /echo HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n' + + (origin === undefined ? '' : `Origin: ${origin}\r\n`) + + '\r\n', + ); + }); + socket.once('data', (chunk) => { + resolve(Number(chunk.toString('latin1').split(' ')[1])); + socket.destroy(); + }); + socket.once('error', reject); + }); +} + +test('serveBun refuses a cross-site WebSocket upgrade', async () => { + const server = await serveBun(createApp({ modules: [M], cors: { origins: ['https://good.example'] } }), { port: 0 }); + try { + expect(await upgradeStatus(server.port)).toBe(101); + expect(await upgradeStatus(server.port, `http://127.0.0.1:${server.port}`)).toBe(101); + expect(await upgradeStatus(server.port, 'https://good.example')).toBe(101); + expect(await upgradeStatus(server.port, 'https://evil.example')).toBe(403); + expect(await upgradeStatus(server.port, 'null')).toBe(403); + } finally { + await server.close({ timeoutMs: 500 }); + } +}); diff --git a/test/deno/ws-origin.test.ts b/test/deno/ws-origin.test.ts new file mode 100644 index 0000000..7a483ae --- /dev/null +++ b/test/deno/ws-origin.test.ts @@ -0,0 +1,60 @@ +// GHSA-p697-fpqx-pgf3 on serveDeno: a cross-site WebSocket upgrade is refused with 403 before Deno +// upgrades it. Same cases as test/ws-origin.test.ts (Node). +// +// Run with: npm run test:deno +import 'npm:reflect-metadata'; +import { assertEquals } from 'jsr:@std/assert'; +import { createApp, Route, Ws, Module, ctx } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Route('/') +class Ctl { + @Ws('/echo') echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield msg; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +async function upgradeStatus(port: number, origin?: string): Promise { + const conn = await Deno.connect({ hostname: '127.0.0.1', port }); + try { + await conn.write( + new TextEncoder().encode( + `GET /echo HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n' + + (origin === undefined ? '' : `Origin: ${origin}\r\n`) + + '\r\n', + ), + ); + const buf = new Uint8Array(256); + const n = (await conn.read(buf)) ?? 0; + return Number(new TextDecoder().decode(buf.subarray(0, n)).split(' ')[1]); + } finally { + conn.close(); + } +} + +Deno.test({ + name: 'serveDeno refuses a cross-site WebSocket upgrade', + sanitizeResources: false, + sanitizeOps: false, + async fn() { + const server = await serveDeno(createApp({ modules: [M], cors: { origins: ['https://good.example'] } }), { + port: 0, + onListen: () => {}, + }); + const port = (server.addr as Deno.NetAddr).port; + try { + assertEquals(await upgradeStatus(port), 101); + assertEquals(await upgradeStatus(port, `http://127.0.0.1:${port}`), 101); + assertEquals(await upgradeStatus(port, 'https://good.example'), 101); + assertEquals(await upgradeStatus(port, 'https://evil.example'), 403); + assertEquals(await upgradeStatus(port, 'null'), 403); + } finally { + await server.close({ timeoutMs: 500 }); + } + }, +}); diff --git a/test/edge/run.ts b/test/edge/run.ts index 591ee32..4edcd87 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -137,6 +137,17 @@ async function main() { }); assert.equal(got, 'echo:hi'); + // GHSA-p697-fpqx-pgf3: a cross-site upgrade is refused with 403 before the pair is created; a + // same-host Origin still upgrades. + const upgradeFrom = (origin: string) => + mf.dispatchFetch('http://localhost/rt/echo', { headers: { Upgrade: 'websocket', Origin: origin } }); + assert.equal((await upgradeFrom('https://evil.example')).status, 403, 'cross-site WebSocket upgrade'); + assert.equal((await upgradeFrom('null')).status, 403, 'null-origin WebSocket upgrade'); + const sameHost = await upgradeFrom('http://localhost'); + assert.equal(sameHost.status, 101, 'same-host WebSocket upgrade'); + sameHost.webSocket?.accept(); + sameHost.webSocket?.close(); + // #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves. const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', { headers: { Upgrade: 'websocket' }, diff --git a/test/ws-origin.test.ts b/test/ws-origin.test.ts new file mode 100644 index 0000000..4497eb5 --- /dev/null +++ b/test/ws-origin.test.ts @@ -0,0 +1,79 @@ +// GHSA-p697-fpqx-pgf3: a WebSocket upgrade from another site is refused with 403 (cross-site +// WebSocket hijacking). The Deno, Bun and edge suites repeat these cases on their adapters. +import 'reflect-metadata'; +import { describe, it, expect } from 'vitest'; +import net from 'node:net'; +import type { AddressInfo } from 'node:net'; +import { createApp, Route, Ws, Module, ctx, type CorsOptions } from '../src/index'; +import { wsOriginAllowed } from '../src/security'; + +@Route('/') +class Ctl { + @Ws('/echo') echo(@ctx() { inbound }: any) { + return (async function* () { + for await (const msg of inbound) yield msg; + })(); + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +/** Sends a raw upgrade request and resolves with the response's status code. */ +function upgradeStatus(port: number, origin?: string): Promise { + return new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1', () => { + socket.write( + `GET /echo HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` + + 'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n' + + (origin === undefined ? '' : `Origin: ${origin}\r\n`) + + '\r\n', + ); + }); + socket.once('data', (chunk) => { + resolve(Number(chunk.toString('latin1').split(' ')[1])); + socket.destroy(); + }); + socket.once('error', reject); + }); +} + +async function withServer(cors: CorsOptions | undefined, run: (port: number) => Promise) { + const server = await createApp({ modules: [M], cors }).listen(0); + try { + await run((server.address() as AddressInfo).port); + } finally { + server.close(); + } +} + +describe('WebSocket Origin check (Node)', () => { + it('accepts no Origin and a same-host Origin', () => + withServer(undefined, async (port) => { + expect(await upgradeStatus(port)).toBe(101); + expect(await upgradeStatus(port, `http://127.0.0.1:${port}`)).toBe(101); + })); + + it('refuses another site, and null, with 403', () => + withServer(undefined, async (port) => { + expect(await upgradeStatus(port, 'https://evil.example')).toBe(403); + expect(await upgradeStatus(port, 'null')).toBe(403); + })); + + it('accepts an origin cors.origins allows, and still refuses the rest', () => + withServer({ origins: ['https://good.example'] }, async (port) => { + expect(await upgradeStatus(port, 'https://good.example')).toBe(101); + expect(await upgradeStatus(port, 'https://evil.example')).toBe(403); + })); +}); + +describe('wsOriginAllowed', () => { + it('compares hosts case-insensitively and ignores a default port', () => { + expect(wsOriginAllowed('https://App.example', 'app.EXAMPLE')).toBe(true); + expect(wsOriginAllowed('https://app.example:443', 'app.example')).toBe(true); + expect(wsOriginAllowed('http://app.example:8080', 'app.example')).toBe(false); + }); + + it('denies when a cors predicate throws', () => { + expect(wsOriginAllowed('https://x.example', 'app.example', { origins: () => { throw new Error('x'); } })).toBe(false); + }); +}); From a71bd7be1068451ed0fec6413b0bef68e3905aad Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:37:11 -0600 Subject: [PATCH 05/41] fix(mesh): mask internal error messages across the hop A remote step that threw a plain Error sent its message to the teacup, which rendered it in a 500 to the end client. A local throw renders "Internal Server Error", so the hop leaked what the local path hides. The teapot now sends the real message only for an HttpError or a status below 500, and masks the rest; the full error stays in its mesh:rpc:error event. The 'cannot transport' diagnostic becomes an HttpError so it still reaches the developer. Same frame fields, no protocol change. Refs: GHSA-gm9h-7577-x57w Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 ++++++ src/mesh/teapot.ts | 16 ++++++++----- test/mesh/teapot.test.ts | 18 +++++++++++++++ test/mesh/transport.test.ts | 45 +++++++++++++++++++++++++++++++++++++ 4 files changed, 81 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ce06215..4b137bf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,13 @@ npm treats versions as semver and semver forbids leading zeros. `DELETE /items/:id`, because the gate matched the pattern and the route ran for whatever method the peer sent. Mesh is `@experimental`; no API change. +- **Mesh: an internal error on a teapot no longer reaches the teacup's client verbatim** + (GHSA-gm9h-7577-x57w). A remote step that threw a plain `Error` sent its message across the hop, + and the teacup rendered it in a `500`, so a message holding a connection string or a host reached + the end client; the same throw handled locally renders `Internal Server Error`. The teapot now + sends the real message only for an `HttpError` or a status below 500, and keeps the full error in + its `mesh:rpc:error` event. The "cannot transport" diagnostic is still delivered. No wire change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 16da08e..291675a 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -5,7 +5,7 @@ import crypto from 'node:crypto'; import type { Bus } from '../bus'; import { HELLO_FRAME_BYTES, sendWhenDrained, widenInbound, type WsSocket } from '../http/ws-core'; import type { ResponseShape } from '../pipeline'; -import { isHttpError } from '../signals'; +import { HttpError, isHttpError } from '../signals'; import { encode, decode, @@ -211,21 +211,27 @@ async function handleRpc( const offender = untransportable(result); if (offender) { - const error: any = new Error( + // An HttpError so its text crosses the hop: it is the framework's own diagnostic for a + // developer mistake and carries nothing from the application. + throw new HttpError( + 500, `mesh cannot transport '${name}': ${offender.path} is ${offender.what}. ` + 'The wire is JSON, so a mesh export carries data, never behaviour — export what the ' + 'handle produces rather than the handle.', ); - error.status = 500; - throw error; } await reply(socket, { type: 'rpc-res', id, ok: true, result }); } catch (err) { const status = isHttpError(err) ? err.status : ((err as any)?.status ?? 500); + // The teacup renders this message to its client, so only text meant for a client crosses: an + // HttpError's, or a status below 500 (e.g. `not exported`). Anything else is an internal error + // whose message may hold a connection string or a host, and is masked exactly as a local + // `errorToResponse` masks it. The full error stays on this side, in the event below. + const message = isHttpError(err) || status < 500 ? (err as Error).message : 'Internal Server Error'; deps.bus?.emit('mesh:rpc:error', { name, error: err }); - await reply(socket, { type: 'rpc-res', id, ok: false, error: { message: (err as Error).message, status } }); + await reply(socket, { type: 'rpc-res', id, ok: false, error: { message, status } }); } } diff --git a/test/mesh/teapot.test.ts b/test/mesh/teapot.test.ts index a3a1af4..6d6a50a 100644 --- a/test/mesh/teapot.test.ts +++ b/test/mesh/teapot.test.ts @@ -171,6 +171,24 @@ describe('createMeshControl', () => { expect(res).toMatchObject({ id: '9', ok: false, error: { message: 'nope', status: 401 } }); }); + it('masks an internal error message instead of sending it to the teacup (GHSA-gm9h-7577-x57w)', async () => { + const seen: unknown[] = []; + const bus = { emit: (e: string, p: { error: unknown }) => e === 'mesh:rpc:error' && seen.push(p.error) } as never; + const t = fakeSocket(); + make({ + bus, + resolveScope: async () => { + throw new Error('pg: password authentication failed for user admin@10.0.0.5'); + }, + }).handle(t.socket); + await t.deliver({ type: 'hello', v: V, secret: 'good' }); + await t.deliver({ type: 'rpc-req', id: '10', kind: 'scope', name: 'config', ctx: {} }); + const res: any = t.sent.find((f: any) => f.type === 'rpc-res'); + expect(res).toMatchObject({ id: '10', ok: false, error: { message: 'Internal Server Error', status: 500 } }); + // the teapot keeps the real error for its own observers + expect((seen[0] as Error).message).toMatch(/password authentication failed/); + }); + it('serves overlapping RPCs concurrently rather than head-of-line blocking', async () => { // the loop must not await handleRpc: a slow call would otherwise stall every later one. // fast is delivered second but resolves first, which can only happen if they overlap. diff --git a/test/mesh/transport.test.ts b/test/mesh/transport.test.ts index 8f720c6..8fd753d 100644 --- a/test/mesh/transport.test.ts +++ b/test/mesh/transport.test.ts @@ -91,3 +91,48 @@ describe('exporting a handle over the mesh', () => { } }); }); + +// GHSA-gm9h-7577-x57w: an internal error on the teapot reached the teacup's client verbatim. +@Step({ provides: 'billing', needs: [], export: true }) +class FailingBilling { + run(): never { + throw new Error('pg: password authentication failed for user admin@10.0.0.5'); + } +} +@Module({ mountpoint: '/api', steps: [FailingBilling] }) +class FailingTeapot {} + +@Route('/local') +class BillingCtl { + @Get('/bill') + bill(@needs('billing') billing: unknown) { + return { billing }; + } +} +@Module({ mountpoint: '/api', controllers: [BillingCtl] }) +class BillingTeacup {} + +describe('an internal error on the teapot', () => { + it('reaches the client as a generic 500, the way it would locally', async () => { + const teapot = createApp({ modules: [FailingTeapot], experimental: true, mesh: { secret: 'x' } }); + const server = await teapot.listen(0); + const port = (server.address() as { port: number }).port; + const teacup = createApp({ + modules: [BillingTeacup], + experimental: true, + mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x' }] }, + }); + + try { + const res = await teacup.fetch(new Request('http://x/api/local/bill')); + expect(res.status).toBe(500); + const text = await res.text(); + expect(text).not.toMatch(/password|10\.0\.0\.5/); + expect(text).toMatch(/Internal Server Error/); + } finally { + await teacup.close(); + await teapot.close(); + server.close(); + } + }); +}); From ba541ee6977656b752be2399da5b9b1578e833f9 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:53:31 -0600 Subject: [PATCH 06/41] fix(stream): mask internal error messages in SSE and ndjson frames A source that threw mid-stream sent err.message to the client verbatim, while the same throw on a buffered route renders Internal Server Error. The error frame now carries an HttpError's message and a generic one for anything else, on every adapter (they share the encoders). The stream:error event still receives the full error. The README notes how a failed stream ends, since onError cannot reach a response that has already sent its status. Refs: GHSA-235j-fx64-w9p9 Signed-off-by: Diego Resendez --- CHANGELOG.md | 6 ++++++ README.md | 2 +- src/encoders.ts | 10 +++++++++- test/encoders.test.ts | 17 +++++++++++++---- test/http.test.ts | 4 +++- test/stream-lifecycle-parity.test.ts | 4 +++- 6 files changed, 35 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b137bf..8e670a3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,12 @@ npm treats versions as semver and semver forbids leading zeros. sends the real message only for an `HttpError` or a status below 500, and keeps the full error in its `mesh:rpc:error` event. The "cannot transport" diagnostic is still delivered. No wire change. +- **A stream's error frame no longer shows the raw error message** (GHSA-235j-fx64-w9p9). When an + SSE or ndjson source threw mid-stream, the client received `err.message` verbatim, while the same + throw on a buffered route renders `Internal Server Error`. The frame now carries an `HttpError`'s + message and `Internal Server Error` for anything else; `stream:error` still gets the full error. + **Behaviour change** for clients that read the text of a non-HTTP error frame. No API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index b9ff36d..8740313 100644 --- a/README.md +++ b/README.md @@ -142,7 +142,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **WebSocket upgrades from another site are refused** with `403`. A browser sends cookies with any page's upgrade and CORS does not cover WebSockets, so an upgrade carrying an `Origin` must come from the same host or from an origin `cors.origins` allows. Clients that send no `Origin` (servers, CLIs) are unaffected. Behind a proxy that rewrites `Host`, list your public origin in `cors.origins`. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. -- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. +- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. A stream that fails after it started has already sent its status, so it ends with an error frame instead (`event: error` on SSE, a last `{"error"}` line on ndjson): it carries an `HttpError`'s message, and `Internal Server Error` for anything else. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. - **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. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **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. diff --git a/src/encoders.ts b/src/encoders.ts index 2e4d687..db730aa 100644 --- a/src/encoders.ts +++ b/src/encoders.ts @@ -1,3 +1,5 @@ +import { isHttpError } from './signals'; + /** * Serializes stream items into wire frames for a streaming transport (SSE, NDJSON). * `headers` is written once before the first frame; `ping` (if present) is sent periodically to keep the connection alive. @@ -9,7 +11,13 @@ export interface StreamEncoder { ping?(): string; } -const messageOf = (error: unknown): string => (error instanceof Error ? error.message : String(error)); +/** + * The text a stream's error frame may show its client: an `HttpError`'s message, which the app wrote + * for the client, and a generic one for anything else, exactly as a buffered route's 500 does. A raw + * `err.message` can hold a connection string or a host (GHSA-235j-fx64-w9p9); the full error still + * goes to the `stream:error` event. + */ +const messageOf = (error: unknown): string => (isHttpError(error) ? error.message : 'Internal Server Error'); // Registered globally rather than module-local: this package ships twice — a bundle on npm and raw // source on JSR — so two copies in one dependency tree is a real shape, and a marker that stopped diff --git a/test/encoders.test.ts b/test/encoders.test.ts index 5ff0a36..e391741 100644 --- a/test/encoders.test.ts +++ b/test/encoders.test.ts @@ -1,12 +1,18 @@ import { describe, it, expect } from 'vitest'; import { sseEncoder, ndjsonEncoder } from '../src/encoders'; +import { HttpError } from '../src/signals'; describe('sseEncoder', () => { it('frames data as SSE events', () => { expect(sseEncoder.encode({ a: 1 })).toBe('data: {"a":1}\n\n'); }); - it('frames errors as an SSE error event with only the message', () => { - expect(sseEncoder.encodeError(new Error('nope'))).toBe('event: error\ndata: {"error":"nope"}\n\n'); + it('frames an HttpError as an SSE error event with only its message', () => { + expect(sseEncoder.encodeError(new HttpError(409, 'nope'))).toBe('event: error\ndata: {"error":"nope"}\n\n'); + }); + it('masks any other error, like a buffered 500 (GHSA-235j-fx64-w9p9)', () => { + expect(sseEncoder.encodeError(new Error('db password=hunter2'))).toBe( + 'event: error\ndata: {"error":"Internal Server Error"}\n\n', + ); }); it('sets text/event-stream headers and has a ping', () => { expect(sseEncoder.headers['content-type']).toBe('text/event-stream'); @@ -19,8 +25,11 @@ describe('ndjsonEncoder', () => { it('frames one JSON line per item', () => { expect(ndjsonEncoder.encode({ a: 1 })).toBe('{"a":1}\n'); }); - it('frames errors as a terminal JSON line', () => { - expect(ndjsonEncoder.encodeError(new Error('nope'))).toBe('{"error":"nope"}\n'); + it('frames an HttpError as a terminal JSON line', () => { + expect(ndjsonEncoder.encodeError(new HttpError(409, 'nope'))).toBe('{"error":"nope"}\n'); + }); + it('masks any other error (GHSA-235j-fx64-w9p9)', () => { + expect(ndjsonEncoder.encodeError(new Error('db password=hunter2'))).toBe('{"error":"Internal Server Error"}\n'); }); it('sets ndjson content-type and has no ping', () => { expect(ndjsonEncoder.headers['content-type']).toBe('application/x-ndjson'); diff --git a/test/http.test.ts b/test/http.test.ts index 42a11c1..66ea7bc 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -85,7 +85,9 @@ describe('http streaming', () => { const text = await res.text(); expect(text).toContain('data: {"ok":true}\n\n'); expect(text).toContain('event: error'); - expect(text).toContain('kaboom'); + // masked like a buffered 500 (GHSA-235j-fx64-w9p9) + expect(text).toContain('Internal Server Error'); + expect(text).not.toContain('kaboom'); server.close(); }); diff --git a/test/stream-lifecycle-parity.test.ts b/test/stream-lifecycle-parity.test.ts index da2c864..a741fe7 100644 --- a/test/stream-lifecycle-parity.test.ts +++ b/test/stream-lifecycle-parity.test.ts @@ -80,7 +80,9 @@ describe('stream lifecycle events, on every adapter', () => { // indistinguishable from the connection dropping. expect(body).toContain('data: {"t":1}\n\n'); expect(body).toContain('event: error'); - expect(body).toContain('source died'); + // the client sees a generic message; the event keeps the real one (GHSA-235j-fx64-w9p9) + expect(body).toContain('Internal Server Error'); + expect(body).not.toContain('source died'); expect(seen).toEqual(['stream:open', 'stream:error', 'stream:close']); expect((errors[0] as Error).message).toBe('source died'); From 7daaa3434c52a1abf1e374804651a48116fd0f3c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:55:24 -0600 Subject: [PATCH 07/41] fix(proxy): take the right-most X-Forwarded-For hop under trustProxy ctx.ip came from the left-most X-Forwarded-For entry, which the client writes. A proxy appends the real address, so a client sending X-Forwarded-For: 6.6.6.6 was seen as 6.6.6.6, defeating per-IP rate limits, allowlists and audit logs. Take the right-most entry, the one the trusted proxy appended, on Node and the fetch adapters through one shared helper. A trailing blank entry falls back to the socket peer. Tests updated on Node, Deno, Bun. Refs: GHSA-53g8-83jp-gvw4 Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 +++++++ README.md | 2 +- src/http/request.ts | 12 +++++++++++- src/http/web.ts | 9 +++++---- test/bun/peer-ip.test.ts | 4 ++-- test/deno/peer-ip.test.ts | 4 ++-- test/fetch.test.ts | 5 +++-- test/transport-security.test.ts | 22 ++++++++++++++++++++++ 8 files changed, 53 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8e670a3..b823eff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -28,6 +28,13 @@ npm treats versions as semver and semver forbids leading zeros. message and `Internal Server Error` for anything else; `stream:error` still gets the full error. **Behaviour change** for clients that read the text of a non-HTTP error frame. No API change. +- **With `trustProxy`, `ctx.ip` is the right-most `X-Forwarded-For` entry** (GHSA-53g8-83jp-gvw4), on + every adapter. It was the left-most, which the client writes: a proxy appends the real address, so + a client that sent `X-Forwarded-For: 6.6.6.6` got `ctx.ip === '6.6.6.6'`, defeating per-IP rate + limits, allowlists and audit logs. **Behaviour change** behind a chain of several proxies, where + `ctx.ip` is now the address the last one saw; `cf-connecting-ip` on the edge is unchanged. No API + change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index 8740313..ecc802a 100644 --- a/README.md +++ b/README.md @@ -136,7 +136,7 @@ Same `@Route`, same handler shape, same `AsyncIterable` — real-time is not a s The parts a real API needs, owned by the framework rather than assembled in your application — and without growing the runtime dependency tree past `reflect-metadata`: -- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). +- **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). `ctx.ip` is the right-most `X-Forwarded-For` entry, the one your proxy appended: everything left of it came from the client. `trustProxy` assumes one proxy in front of the app; behind a chain (a CDN, then a load balancer), make the outermost hop set a header the app can trust, as Cloudflare does with `cf-connecting-ip`. - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag. - **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you. - **WebSocket upgrades from another site are refused** with `403`. A browser sends cookies with any page's upgrade and CORS does not cover WebSockets, so an upgrade carrying an `Origin` must come from the same host or from an origin `cors.origins` allows. Clients that send no `Origin` (servers, CLIs) are unaffected. Behind a proxy that rewrites `Host`, list your public origin in `cors.origins`. diff --git a/src/http/request.ts b/src/http/request.ts index a3c0333..8957b15 100644 --- a/src/http/request.ts +++ b/src/http/request.ts @@ -72,6 +72,16 @@ function firstToken(value: string | string[] | undefined): string | undefined { return first?.split(',')[0].trim(); } +/** + * The address the trusted proxy appended to `x-forwarded-for`: its right-most entry. Everything to + * its left arrived from the client, which can write any address there (GHSA-53g8-83jp-gvw4), so the + * left-most entry is the one value the header cannot vouch for. Shared with the fetch adapters. + */ +export function lastForwardedHop(value: string | string[] | null | undefined): string | undefined { + const joined = Array.isArray(value) ? value.join(',') : value; + return joined?.split(',').pop()?.trim() || undefined; +} + /** Determines whether the request arrived over HTTPS, honoring `x-forwarded-proto` when proxy is trusted. */ export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): boolean { if (trustProxy) { @@ -85,7 +95,7 @@ export function deriveSecure(req: http.IncomingMessage, trustProxy: boolean): bo /** Resolves the client IP, honoring `x-forwarded-for` when proxy is trusted. */ export function deriveIp(req: http.IncomingMessage, trustProxy: boolean): string { if (trustProxy) { - const forwarded = firstToken(req.headers['x-forwarded-for']); + const forwarded = lastForwardedHop(req.headers['x-forwarded-for']); if (forwarded) return forwarded; } diff --git a/src/http/web.ts b/src/http/web.ts index 639b35d..55c1661 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -12,6 +12,7 @@ import { } from './core'; import { mergeInjectedHeaders, toWebHeaders } from './headers'; import { peerOf, trustedProxyClient } from './peer'; +import { lastForwardedHop } from './request'; import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body'; import { HttpError } from '../signals'; import { renderError, type ErrorRequest } from '../transformers'; @@ -244,17 +245,17 @@ function outcomeToResponse( return new Response(body, { status: outcome.status, headers }); } -/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */ +/** The `x-forwarded-for` hop the trusted proxy appended (the right-most), else `''`. */ function forwardedFor(request: Request, opts: HttpOptions | undefined): string { if (!opts?.trustProxy) return ''; - return (request.headers.get('x-forwarded-for') ?? '').split(',')[0].trim(); + return lastForwardedHop(request.headers.get('x-forwarded-for')) ?? ''; } /** * `ctx.ip` on the fetch path, for `NeutralRequest.resolveIp`. Mirrors Node's `deriveIp` - * (src/http/request.ts): only trust `x-forwarded-for` when the proxy is trusted, and take its first - * hop, because an untrusted XFF is client-spoofable. Otherwise the socket peer, which only the Deno + * (src/http/request.ts): only trust `x-forwarded-for` when the proxy is trusted, and take the hop + * that proxy appended (the right-most), because an untrusted XFF is client-spoofable. Otherwise the socket peer, which only the Deno * and Bun adapters can supply; a bare `app.fetch` has none, so there the answer is still ''. Ahead of * both, under `trustProxy` only: the address the edge adapter read from `cf-connecting-ip`. * Cloudflare sets that header itself, while XFF can carry hops the client supplied, so on the edge diff --git a/test/bun/peer-ip.test.ts b/test/bun/peer-ip.test.ts index fcc9a14..9ede5fb 100644 --- a/test/bun/peer-ip.test.ts +++ b/test/bun/peer-ip.test.ts @@ -49,8 +49,8 @@ test.skipIf(!ipv6Available)('T3 serveBun: an IPv6 peer is passed through as Bun expect(await ipVia('::1')).toBe('::1'); }); -test('T4 serveBun: trustProxy takes the first x-forwarded-for hop', async () => { - const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } }); +test('T4 serveBun: trustProxy takes the x-forwarded-for hop the proxy appended', async () => { + const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '6.6.6.6, 203.0.113.7' } }); expect(ip).toBe('203.0.113.7'); }); diff --git a/test/deno/peer-ip.test.ts b/test/deno/peer-ip.test.ts index a126019..86eabc4 100644 --- a/test/deno/peer-ip.test.ts +++ b/test/deno/peer-ip.test.ts @@ -59,8 +59,8 @@ Deno.test({ }, }); -Deno.test('T4 serveDeno: trustProxy takes the first x-forwarded-for hop', async () => { - const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } }); +Deno.test('T4 serveDeno: trustProxy takes the x-forwarded-for hop the proxy appended', async () => { + const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '6.6.6.6, 203.0.113.7' } }); assertEquals(ip, '203.0.113.7'); }); diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 4d49b19..6481612 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -95,12 +95,13 @@ class IpCtl { class IpModule {} describe('app.fetch trustProxy gates x-forwarded-for', () => { - it('honors x-forwarded-for (first hop) when trustProxy is true', async () => { + it('honors x-forwarded-for (the hop the proxy appended) when trustProxy is true', async () => { const trustingApp = createApp({ modules: [IpModule], trustProxy: true }); + // `9.9.9.9` is what the client wrote; `1.1.1.1` is what the trusted proxy appended (GHSA-53g8-83jp-gvw4). const res = await trustingApp.fetch( new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9, 1.1.1.1' } }), ); - expect(await res.json()).toEqual({ ip: '9.9.9.9' }); + expect(await res.json()).toEqual({ ip: '1.1.1.1' }); }); it('ignores x-forwarded-for when trustProxy is off (default)', async () => { diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 7eecc02..20990d3 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -3,6 +3,7 @@ import https from 'https'; import WebSocket from 'ws'; import { createApp, Route, Get, Sse, Ws, Module, Transformer, inbound, channel, ctx } from '../src'; import { selfSignedTls } from './helpers/tls'; +import { lastForwardedHop } from '../src/http/request'; @Route('/') class Api { @@ -59,6 +60,16 @@ describe('trustProxy', () => { headers: { 'x-forwarded-proto': 'https', 'x-forwarded-for': '9.9.9.9' } }); expect(await r.json()).toEqual({ proto: 'https', ip: '9.9.9.9' }); }); + it('trustProxy takes the x-forwarded-for hop the proxy appended, not what the client wrote', async () => { + @Route('/') class P { @Get('/who') who(@ctx() c: any) { return { ip: c.ip }; } } + @Module({ mountpoint: '/', controllers: [P] }) class PMod {} + app = createApp({ modules: [PMod], trustProxy: true }); + const server = await app.listen(0); + const port = (server.address() as any).port; + // GHSA-53g8-83jp-gvw4: the client sent `6.6.6.6`; the proxy appended the real `203.0.113.7`. + const r = await fetch(`http://127.0.0.1:${port}/who`, { headers: { 'x-forwarded-for': '6.6.6.6, 203.0.113.7' } }); + expect(await r.json()).toEqual({ ip: '203.0.113.7' }); + }); it('without trustProxy, forwarded headers are ignored', async () => { @Route('/') class P { @Get('/who') who(@ctx() c: any) { return { proto: c.protocol }; } } @Module({ mountpoint: '/', controllers: [P] }) class PMod {} @@ -218,3 +229,14 @@ describe('CORS', () => { expect(vary).toContain('Origin'); }); }); + +describe('lastForwardedHop', () => { + it('takes the right-most entry, across repeated headers, and ignores blanks', () => { + expect(lastForwardedHop('1.1.1.1, 2.2.2.2')).toBe('2.2.2.2'); + expect(lastForwardedHop(['1.1.1.1', '2.2.2.2, 3.3.3.3'])).toBe('3.3.3.3'); + expect(lastForwardedHop(' 4.4.4.4 ')).toBe('4.4.4.4'); + expect(lastForwardedHop('')).toBeUndefined(); + expect(lastForwardedHop(undefined)).toBeUndefined(); + expect(lastForwardedHop('1.1.1.1, ')).toBeUndefined(); + }); +}); From 8649629b1e2969088e0c8979d445ad40a9315ea0 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:56:19 -0600 Subject: [PATCH 08/41] fix(cors): refuse origins '*' with credentials at boot The spec forbids Access-Control-Allow-Origin: * with credentials, so core honoured the combination by echoing every request origin, null included, with Allow-Credentials: true. Any site could then make credentialed reads. createApp now throws for it and names the alternatives: list the trusted origins, or write the intent as a predicate where it is visible. The option type is unchanged. Refs: GHSA-fccm-q62j-48hr Signed-off-by: Diego Resendez --- CHANGELOG.md | 6 ++++++ README.md | 2 +- src/app/index.ts | 2 ++ src/security.ts | 15 +++++++++++++++ test/transport-security.test.ts | 10 +++++++++- 5 files changed, 33 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b823eff..699b16b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -35,6 +35,12 @@ npm treats versions as semver and semver forbids leading zeros. `ctx.ip` is now the address the last one saw; `cf-connecting-ip` on the edge is unchanged. No API change. +- **`cors: { origins: '*', credentials: true }` fails `createApp`** (GHSA-fccm-q62j-48hr). The spec + forbids `*` with credentials, so core echoed every request origin, `null` included, with + `Access-Control-Allow-Credentials: true`, and any site could make credentialed reads. **Breaking** + for an app that set this combination: list the trusted origins, or write the intent as a + predicate (`origins: () => true`) so it is visible. The option type is unchanged. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index ecc802a..54667ac 100644 --- a/README.md +++ b/README.md @@ -138,7 +138,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **TLS → https/wss** natively, plus proxy-aware `trustProxy` (`X-Forwarded-*` → `ctx.protocol`/`ctx.ip`). `ctx.ip` is the right-most `X-Forwarded-For` entry, the one your proxy appended: everything left of it came from the client. `trustProxy` assumes one proxy in front of the app; behind a chain (a CDN, then a load balancer), make the outermost hop set a header the app can trust, as Cloudflare does with `cf-connecting-ip`. - **Secure by default.** `nosniff`, `X-Frame-Options`, `Referrer-Policy`, HSTS-when-secure — on every response, opt-out with one flag. -- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you. +- **CORS** with a guarded preflight and the credentials-never-`*` rule enforced for you: `origins: '*'` with `credentials: true` fails `createApp`, since honouring both means trusting every site with your users' cookies. Write the rule as a predicate if that is really what you want. - **WebSocket upgrades from another site are refused** with `403`. A browser sends cookies with any page's upgrade and CORS does not cover WebSockets, so an upgrade carrying an `Origin` must come from the same host or from an origin `cors.origins` allows. Clients that send no `Origin` (servers, CLIs) are unaffected. Behind a proxy that rewrites `Host`, list your public origin in `cors.origins`. - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. diff --git a/src/app/index.ts b/src/app/index.ts index 56fff5a..9a07499 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -48,6 +48,7 @@ import { Rooms } from '../rooms'; import { TLS_REQUESTED, WS_ORIGIN_CHECK, + assertCorsOptions, wsOriginAllowed, type TlsOptions, type SecurityOptions, @@ -299,6 +300,7 @@ export function createApp(opts: AppOptions): App { validateWsLimits(opts.limits); const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs); assertEtagOption(opts.etag); + assertCorsOptions(opts.cors); const bus = new Bus(); const logger = opts.logger ?? createDefaultLogger(); diff --git a/src/security.ts b/src/security.ts index e7cb3be..085362d 100644 --- a/src/security.ts +++ b/src/security.ts @@ -76,6 +76,21 @@ export function refuseWsOrigin(app: object, request: Request): Response | undefi return new Response('Forbidden', { status: 403 }); } +/** + * Refuses `cors: { origins: '*', credentials: true }` at boot (GHSA-fccm-q62j-48hr). The spec forbids + * `*` with credentials, so the only way to honour both was to echo every origin, `null` included, with + * `Access-Control-Allow-Credentials: true`: any site could then make credentialed reads. An app that + * really means that writes it as a predicate, where it is visible. + */ +export function assertCorsOptions(cors: CorsOptions | undefined): void { + if (cors?.origins === '*' && cors.credentials) { + throw new Error( + "cors: { origins: '*', credentials: true } would let every site make credentialed requests. " + + 'List the origins you trust, or pass a predicate such as `origins: (origin) => origin.endsWith(".example.com")`.', + ); + } +} + /** CORS policy. `origins` may be a literal, list, `'*'`, or a predicate. */ export interface CorsOptions { origins: string | string[] | '*' | ((origin: string) => boolean); diff --git a/test/transport-security.test.ts b/test/transport-security.test.ts index 20990d3..c07b79a 100644 --- a/test/transport-security.test.ts +++ b/test/transport-security.test.ts @@ -187,10 +187,18 @@ describe('CORS', () => { expect(pre.headers.get('x-content-type-options')).toBe('nosniff'); // security headers on preflight too }); + it("refuses origins '*' with credentials at boot (GHSA-fccm-q62j-48hr)", () => { + @Route('/') class C { @Get('/x') x() { return { ok: 1 }; } } + @Module({ mountpoint: '/', controllers: [C] }) class CMod {} + expect(() => createApp({ modules: [CMod], cors: { origins: '*', credentials: true } })).toThrow( + /credentialed requests[\s\S]*predicate/, + ); + }); + 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 } }); + app = createApp({ modules: [CMod], cors: { origins: () => true, 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' } }); From 3cf3c7efe20230717c89f1db1e663c0c82301c23 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 22:57:32 -0600 Subject: [PATCH 09/41] fix(static): never serve dotfiles Static serving returned any file under the root, so GET /.env served the file, and /.git/config or /.htpasswd would too if they ended up in the public directory. A path with any segment starting with '.' is now a miss (404), checked on the decoded path so %2e cannot slip past. /.well-known/ stays reachable for ACME and security.txt (RFC 8615); dotfiles inside it are still hidden. Refs: GHSA-hjcj-hr8v-rfg4 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ README.md | 2 +- src/views.ts | 14 ++++++++++++++ test/views-static.test.ts | 19 +++++++++++++++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 699b16b..1a6516c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,11 @@ npm treats versions as semver and semver forbids leading zeros. for an app that set this combination: list the trusted origins, or write the intent as a predicate (`origins: () => true`) so it is visible. The option type is unchanged. +- **`static` no longer serves dotfiles** (GHSA-hjcj-hr8v-rfg4). `GET /.env` returned the file, and so + would `/.git/config` or `/.htpasswd` in a public root. A path with any segment starting with `.` is + now a miss (`404`), except under `/.well-known/` (RFC 8615), where only dotfiles stay hidden. + **Behaviour change** for an app that served dotfiles on purpose. No API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index 54667ac..e08b1b3 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **Validation via [Standard Schema](https://standardschema.dev).** `@body(schema)` accepts zod, valibot, or arktype — you bring the validator, the core stays zero-dep. Invalid input → `422` with per-field issues; the parsed value reaches your handler typed. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. A stream that fails after it started has already sent its status, so it ends with an error frame instead (`event: error` on SSE, a last `{"error"}` line on ndjson): it carries an `HttpError`'s message, and `Internal Server Error` for anything else. -- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. +- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. It never serves a dotfile or anything under a dot directory (`/.env`, `/.git/config`), except under `/.well-known/`. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. - **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. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **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 })`. diff --git a/src/views.ts b/src/views.ts index 61be3a1..254d55c 100644 --- a/src/views.ts +++ b/src/views.ts @@ -218,6 +218,7 @@ export function buildStaticResolver(root: string | true, cacheControl = 'no-cach return undefined; } + if (isHiddenPath(rel)) return undefined; if (rel === '' || rel.endsWith('/')) rel += 'index.html'; const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel)); if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard @@ -233,6 +234,19 @@ export function buildStaticResolver(root: string | true, cacheControl = 'no-cach }; } +/** + * A path with a segment that starts with `.` (`/.env`, `/.git/config`, `/a/.htpasswd`) is never served + * from `static` (GHSA-hjcj-hr8v-rfg4): a dotfile in the public root is almost always there by accident, + * and it is a miss like any missing file. `/.well-known/` is the exception, because ACME challenges and + * `security.txt` live there by standard (RFC 8615); a dotfile *inside* it is still hidden. + */ +function isHiddenPath(rel: string): boolean { + const segments = rel.split('/').filter(Boolean); + const start = segments[0] === '.well-known' ? 1 : 0; + + return segments.slice(start).some((segment) => segment.startsWith('.')); +} + /** Turns `@Html` metadata into a response transformer at boot. String mode is fs-free; path/template modes read+cache the file. */ export function buildHtmlTransformer(meta: HtmlMeta, ctx: ViewsContext): TransformerFn { if (!meta.path) { diff --git a/test/views-static.test.ts b/test/views-static.test.ts index 9b4939e..ef97efd 100644 --- a/test/views-static.test.ts +++ b/test/views-static.test.ts @@ -16,6 +16,16 @@ writeFileSync(join(tmpdir(), 'gt-secret.txt'), 'TOP SECRET'); // Bytes that no text encoding round-trips: a NUL, a lone high byte, an invalid UTF-8 sequence. const binary = Buffer.from([0x00, 0x89, 0x50, 0x4e, 0x47, 0xff, 0xfe, 0x0d, 0x0a, 0x1a, 0x0a]); writeFileSync(join(root, 'pixel.bin'), binary); +// GHSA-hjcj-hr8v-rfg4: dotfiles that end up in a public root by accident. +writeFileSync(join(root, '.env'), 'SECRET=1'); +mkdirSync(join(root, '.git'), { recursive: true }); +writeFileSync(join(root, '.git', 'config'), '[core]'); +mkdirSync(join(root, 'sub', '.hidden'), { recursive: true }); +writeFileSync(join(root, 'sub', '.hidden', 'x.txt'), 'hidden'); +mkdirSync(join(root, '.well-known', 'acme-challenge'), { recursive: true }); +writeFileSync(join(root, '.well-known', 'security.txt'), 'Contact: x'); +writeFileSync(join(root, '.well-known', 'acme-challenge', 'tok'), 'tok.key'); +writeFileSync(join(root, '.well-known', '.secret'), 'no'); @Route('/api') class Api { @@ -54,6 +64,15 @@ describe('static serving', () => { it('returns 404 for a missing file', async () => { expect((await app.fetch(new Request('http://x/nope.html'))).status).toBe(404); }); + it('never serves a dotfile or a file under a dot directory (GHSA-hjcj-hr8v-rfg4)', async () => { + for (const path of ['/.env', '/.git/config', '/sub/.hidden/x.txt', '/%2eenv', '/.well-known/.secret']) { + expect((await app.fetch(new Request(`http://x${path}`))).status, path).toBe(404); + } + }); + it('still serves /.well-known/ (RFC 8615)', async () => { + expect(await (await app.fetch(new Request('http://x/.well-known/security.txt'))).text()).toBe('Contact: x'); + expect(await (await app.fetch(new Request('http://x/.well-known/acme-challenge/tok'))).text()).toBe('tok.key'); + }); it('rejects path traversal', async () => { const res = await app.fetch(new Request('http://x/../gt-secret.txt')); expect(res.status).toBe(404); From a663b8dc8f45aa86e5774d54c10ccc251e0c2571 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:01:11 -0600 Subject: [PATCH 10/41] fix(node): reap slow-header sockets and dead WebSocket peers Node checks headersTimeout and requestTimeout only every connectionsCheckingInterval, 30s by default, so a slow-header socket lived up to 40s. A WebSocket peer that disappeared without closing was never reaped at all. A few hundred of either filled the default maxConnections and every new connection was dropped. Create the server with a 1s connectionsCheckingInterval, and ping each Node WebSocket every 30s, terminating it if it missed the previous ping. The timer is unref'd and cleared on close. Refs: GHSA-g96c-wq2v-87vc Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 ++++ README.md | 2 +- src/http/server.ts | 8 +++- src/http/ws.ts | 32 +++++++++++++++- test/conn-reaping.test.ts | 78 +++++++++++++++++++++++++++++++++++++++ 5 files changed, 123 insertions(+), 4 deletions(-) create mode 100644 test/conn-reaping.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 1a6516c..49ba27c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -46,6 +46,13 @@ npm treats versions as semver and semver forbids leading zeros. now a miss (`404`), except under `/.well-known/` (RFC 8615), where only dotfiles stay hidden. **Behaviour change** for an app that served dotfiles on purpose. No API change. +- **Node reaps slow-header sockets and dead WebSocket peers promptly** (GHSA-g96c-wq2v-87vc). Node + checks `headersTimeout`/`requestTimeout` only every 30 seconds by default, so a slow-header socket + lived up to 40 seconds, and a WebSocket peer that vanished without closing held its slot forever: a + few hundred of either filled the default `maxConnections` and locked everyone else out. The check + now runs every second, and each Node WebSocket is pinged every 30 seconds and terminated if it + missed the previous ping. Browsers and `ws` clients answer pings on their own. No API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index e08b1b3..c2ef2b1 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. A stream that fails after it started has already sent its status, so it ends with an error frame instead (`event: error` on SSE, a last `{"error"}` line on ndjson): it carries an `HttpError`'s message, and `Internal Server Error` for anything else. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. It never serves a dotfile or anything under a dot directory (`/.env`, `/.git/config`), except under `/.well-known/`. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. -- **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. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. +- **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. Node checks the headers and request timeouts every second, so a slow-header socket is closed (`408`) about when its timeout runs out, and pings each WebSocket every 30 seconds, terminating one that missed the previous ping. A connection cap is still one global number: put per-IP connection limits at the proxy. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **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 })`. - **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`. diff --git a/src/http/server.ts b/src/http/server.ts index 98d5027..1e5e9c7 100644 --- a/src/http/server.ts +++ b/src/http/server.ts @@ -66,9 +66,13 @@ export function createHttpServer( const nodeHttps = nodeRequire('https'); // runtime-compatible; only @types differ (https.Server lacks the http-only timeout props) + // Node checks for expired `headersTimeout`/`requestTimeout` only every `connectionsCheckingInterval` + // (30s by default), so a slow-header socket lived up to 40s and a few hundred of them filled + // `maxConnections` (GHSA-g96c-wq2v-87vc). A 1s check closes them close to the timeout they broke. + const serverOptions = { connectionsCheckingInterval: 1_000 }; const server: http.Server = (opts?.tls - ? nodeHttps.createServer(opts.tls as https.ServerOptions, handler) - : nodeHttp.createServer(handler)) as unknown as http.Server; + ? nodeHttps.createServer({ ...(opts.tls as https.ServerOptions), ...serverOptions }, handler) + : nodeHttp.createServer(serverOptions, handler)) as unknown as http.Server; const maxConnections = opts?.limits?.maxConnections ?? 1000; if (maxConnections > 0) { diff --git a/src/http/ws.ts b/src/http/ws.ts index c6c5883..b500ca7 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -132,7 +132,16 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest { } /** Wraps a `ws` socket as a neutral WsSocket: inbound channel + abort on close + send/close/terminate. */ -function nodeSocket(ws: any): WsSocket { +/** + * Gap between protocol pings on a Node WebSocket. A peer that has not answered the previous ping by + * the next one is terminated, so a half-open connection (a client that vanished without a FIN) is + * reaped within about two intervals instead of holding its slot under `maxConnections` forever + * (GHSA-g96c-wq2v-87vc). Browsers and `ws` answer pings by themselves; nothing in the app sees them. + * Deno, Bun and the edge manage idle sockets in the runtime. + */ +export const WS_PING_MS = 30_000; + +export function nodeSocket(ws: any): WsSocket { const inbound = channel(); const ac = new AbortController(); // `drained` callers waiting for the send buffer to fall to the mark (#41). Released by a send @@ -145,8 +154,29 @@ function nodeSocket(ws: any): WsSocket { if (!backedUp()) release(); }; + let answered = true; + ws.on('pong', () => { + answered = true; + }); + const heartbeat = setInterval(() => { + if (!answered) { + (ws.terminate ?? ws.close).call(ws); + return; + } + + answered = false; + + try { + ws.ping(); + } catch { + /* closing; the close handler clears this timer */ + } + }, WS_PING_MS); + heartbeat.unref?.(); + ws.on('message', (data: Buffer) => inbound.push(data.toString())); ws.on('close', () => { + clearInterval(heartbeat); inbound.close(); ac.abort(); release(); diff --git a/test/conn-reaping.test.ts b/test/conn-reaping.test.ts new file mode 100644 index 0000000..9d501b9 --- /dev/null +++ b/test/conn-reaping.test.ts @@ -0,0 +1,78 @@ +// GHSA-g96c-wq2v-87vc: on Node, slow-header sockets and half-open WebSocket peers held their +// connection slot far longer than any timeout said, so a few hundred filled maxConnections. +import 'reflect-metadata'; +import { describe, it, expect, vi, afterEach } from 'vitest'; +import { EventEmitter } from 'node:events'; +import net from 'node:net'; +import type { AddressInfo } from 'node:net'; +import { createApp, Route, Get, Module } from '../src/index'; +import { nodeSocket, WS_PING_MS } from '../src/http/ws'; + +@Route('/') +class Ctl { + @Get('/x') x() { + return { ok: true }; + } +} +@Module({ mountpoint: '/', controllers: [Ctl] }) +class M {} + +describe('slow-header sockets', () => { + it('are closed close to headersTimeout, not up to 30s later', async () => { + const server = await createApp({ modules: [M], limits: { headersTimeoutMs: 300 } }).listen(0); + try { + const port = (server.address() as AddressInfo).port; + const started = Date.now(); + const closedAfter = await new Promise((resolve, reject) => { + const socket = net.connect(port, '127.0.0.1', () => socket.write('GET /x HTTP/1.1\r\nHost: x\r\n')); + socket.on('error', () => {}); + socket.resume(); // read, or the server's FIN after its 408 never surfaces as 'close' + socket.on('close', () => resolve(Date.now() - started)); + setTimeout(() => reject(new Error('socket still open after 5s')), 5_000).unref(); + }); + expect(closedAfter).toBeLessThan(2_500); + } finally { + server.close(); + } + }); +}); + +describe('Node WebSocket heartbeat', () => { + afterEach(() => vi.useRealTimers()); + + const fakeWs = () => + Object.assign(new EventEmitter(), { + readyState: 1, + bufferedAmount: 0, + ping: vi.fn(), + terminate: vi.fn(), + send: vi.fn(), + close: vi.fn(), + }); + + it('terminates a peer that does not answer a ping by the next one', () => { + vi.useFakeTimers(); + const ws = fakeWs(); + nodeSocket(ws); + vi.advanceTimersByTime(WS_PING_MS); + expect(ws.ping).toHaveBeenCalledOnce(); + expect(ws.terminate).not.toHaveBeenCalled(); + vi.advanceTimersByTime(WS_PING_MS); + expect(ws.terminate).toHaveBeenCalledOnce(); + }); + + it('keeps a peer that answers, and stops pinging once closed', () => { + vi.useFakeTimers(); + const ws = fakeWs(); + nodeSocket(ws); + for (let i = 0; i < 3; i++) { + vi.advanceTimersByTime(WS_PING_MS); + ws.emit('pong'); + } + expect(ws.terminate).not.toHaveBeenCalled(); + expect(ws.ping).toHaveBeenCalledTimes(3); + ws.emit('close'); + vi.advanceTimersByTime(WS_PING_MS * 3); + expect(ws.ping).toHaveBeenCalledTimes(3); + }); +}); From 8514b29c9944a231a0eb7f48f5cd3ca29de03018 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:02:41 -0600 Subject: [PATCH 11/41] fix(mesh): run only the exported step's closure on a remote call resolveScope seeded every provider and ran every step on the teapot for each remote step call. An unexported step's side effects fired once per RPC, and an unrelated step that threw broke every export. Slice each exported step's closure once when the control channel is built, the way finalizeGraph slices a route, and run only that. Unlike a route, always-on observer steps are not added: the teacup's own request already ran its observers. Closes #85 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++ src/app/index.ts | 22 +++++++++- test/mesh/step-isolation.test.ts | 74 ++++++++++++++++++++++++++++++++ 3 files changed, 99 insertions(+), 2 deletions(-) create mode 100644 test/mesh/step-isolation.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 49ba27c..52a4d94 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -64,6 +64,11 @@ npm treats versions as semver and semver forbids leading zeros. ### Fixed +- **Mesh: a remote step call runs only that step and what it needs** (#85). The teapot ran every one + of its steps on each call, so an unexported step's side effects fired once per RPC, and any + unrelated step that threw broke every export. A call now runs the exported step's own closure of + providers and steps, sliced once at boot like a route's. Mesh is `@experimental`; no API change. + - **An async bus listener that rejects no longer exits the Node process** (#70). `Bus.emit` isolated a listener that threw, but an `async` listener fails by rejecting, and that rejection went unhandled, so a plugin's `on('request:end', async () => { throw … })` killed the process on the diff --git a/src/app/index.ts b/src/app/index.ts index 9a07499..f43340f 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1696,14 +1696,32 @@ function buildMeshControl( const { bus, providedSeed, planSteps, onError, logger } = deps.deps; const manifest = buildManifest({ steps: exportedSteps, routes: exportedRoutes }); + // Each exported step runs with only what it needs: its own closure of providers and steps, sliced + // once here like a route's. Running every step on every call (#85) fired unexported side effects + // per RPC and let any unrelated step that threw break every export. Unlike a route, no always-on + // observer step is added: the teacup's own request already ran its observers. + const ordered = [...orderedProviders, ...orderedSteps]; + const slices = new Map( + exportedSteps.map((token) => { + const closure = new Set(subgraphFor([token], ordered)); + const providers = orderedProviders.filter((node) => closure.has(node)); + const steps = orderedSteps + .filter((node) => closure.has(node)) + .map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! })); + + return [token, { providers, steps }] as const; + }), + ); + const resolveScope = async (name: string, env: RequestEnvelope): Promise => { // context is intentionally `any`: providers and steps merge arbitrary keys into it const seed: any = { req: env, params: env.params, query: env.query, body: env.body, headers: env.headers }; + // The teapot gates names before this runs, so an exported token always has a slice. + const { providers, steps } = slices.get(name)!; - for (const provider of orderedProviders) + for (const provider of providers) if (container.has(provider.name)) Object.assign(seed, await container.resolve(provider.name)); - const steps = orderedSteps.map((step) => ({ name: step.name, origin: step.origin, run: runners.get(step.name)! })); // The caller's identity, adopted rather than replaced — the same rule an incoming // `x-request-id` gets, applied at the process boundary where it matters most. No `route`: // resolving a scope is not a route, and inventing one would put a token in a route label. diff --git a/test/mesh/step-isolation.test.ts b/test/mesh/step-isolation.test.ts new file mode 100644 index 0000000..6d783f4 --- /dev/null +++ b/test/mesh/step-isolation.test.ts @@ -0,0 +1,74 @@ +// #85: one remote step call ran every step on the teapot. It now runs the exported step's own +// closure, the way a route runs only the steps it needs. +import { describe, it, expect } from 'vitest'; +import { createApp, Step, Route, Get, Module, needs } from '../../src/index'; + +let unrelatedRuns = 0; +let baseRuns = 0; + +@Step({ provides: 'base', needs: [] }) +class Base { + run() { + baseRuns++; + return { base: 'b' }; + } +} +@Step({ provides: 'billing', needs: ['base'], export: true }) +class Billing { + run(ctx: { base: string }) { + return { billing: `bill:${ctx.base}` }; + } +} +@Step({ provides: 'unrelated', needs: [] }) +class Unrelated { + run() { + unrelatedRuns++; + return { unrelated: 1 }; + } +} +@Step({ provides: 'broken', needs: [] }) +class Broken { + run(): never { + throw new Error('unrelated step failed'); + } +} +@Module({ mountpoint: '/api', steps: [Base, Billing, Unrelated, Broken] }) +class TeapotModule {} + +@Route('/local') +class Ctl { + @Get('/bill') + bill(@needs('billing') billing: string) { + return { billing }; + } +} +@Module({ mountpoint: '/api', controllers: [Ctl] }) +class TeacupModule {} + +describe('a remote step call', () => { + it('runs the exported step and its ancestors only', async () => { + const teapot = createApp({ modules: [TeapotModule], experimental: true, mesh: { secret: 'x' } }); + const server = await teapot.listen(0); + const port = (server.address() as { port: number }).port; + const teacup = createApp({ + modules: [TeacupModule], + experimental: true, + mesh: { teapots: [{ url: `ws://127.0.0.1:${port}/__mesh__/control`, secret: 'x' }] }, + }); + + try { + for (let i = 0; i < 3; i++) { + const res = await teacup.fetch(new Request('http://x/api/local/bill')); + // an unrelated step that throws no longer breaks the export + expect(res.status).toBe(200); + expect(await res.json()).toEqual({ billing: 'bill:b' }); + } + expect(baseRuns).toBe(3); // an ancestor still runs, once per call + expect(unrelatedRuns).toBe(0); // a step nobody asked for does not + } finally { + await teacup.close(); + await teapot.close(); + server.close(); + } + }); +}); From 1360863e2562af2107107f964d9179b9af7e9c0c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:16:14 -0600 Subject: [PATCH 12/41] feat(mesh): refuse ws:// teapots off loopback unless allowInsecure The hello frame carries the teapot's secret verbatim, and a cleartext link to another machine only logged a warning, after createApp had already accepted the config. createApp now refuses a ws:// teapot whose host is not loopback, before anything connects. MeshConfig.allowInsecure opts in for networks that already encrypt the link, and each such teapot is still warned about. Loopback detection parses the URL, so [::1] and 127.0.0.0/8 are recognised (the old split on ':' misread IPv6 hosts). MeshConfig is mesh's own experimental surface (D19); the API report gains only allowInsecure. Closes #86 Signed-off-by: Diego Resendez --- CHANGELOG.md | 7 ++++++ api/index.api.md | 1 + src/app/index.ts | 51 +++++++++++++++++++++++++++----------- src/app/types.ts | 7 ++++++ test/mesh/envelope.test.ts | 31 +++++++++++++++-------- 5 files changed, 71 insertions(+), 26 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 52a4d94..e50c4fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,13 @@ npm treats versions as semver and semver forbids leading zeros. now runs every second, and each Node WebSocket is pinged every 30 seconds and terminated if it missed the previous ping. Browsers and `ws` clients answer pings on their own. No API change. +- **Mesh: a `ws://` teapot off loopback fails `createApp` unless `mesh.allowInsecure`** (#86). The + handshake sends the teapot's secret verbatim, and a cleartext link to another machine only logged + a warning. Use `wss://`, or set the new `MeshConfig.allowInsecure: true` when the network already + encrypts the link (a service mesh with mutual TLS); such a teapot is still logged as a warning. + Loopback (`localhost`, `127.0.0.0/8`, `[::1]`) is unaffected. Mesh is `@experimental`: the change + stays within `MeshConfig` (D19). + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/api/index.api.md b/api/index.api.md index 8be4257..74d8618 100644 --- a/api/index.api.md +++ b/api/index.api.md @@ -567,6 +567,7 @@ export const MESH_CONTROL_PATH = "/__mesh__/control"; // @public export interface MeshConfig { + allowInsecure?: boolean; bootTimeoutMs?: number; heartbeatMs?: number; onManifestChange?: 'refuse'; diff --git a/src/app/index.ts b/src/app/index.ts index f43340f..46478cd 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -304,6 +304,7 @@ export function createApp(opts: AppOptions): App { const bus = new Bus(); const logger = opts.logger ?? createDefaultLogger(); + assertTeapotTransport(opts.mesh, logger); if (opts.logRequests) logRequests(bus, logger); const container = new Container(); let server: http.Server | undefined; @@ -1150,24 +1151,45 @@ async function connectUntilDeadline( } } +/** Whether `url` is a `ws://` link that leaves this machine. Loopback has no network path to read. */ +function crossesNetworkInCleartext(url: string): boolean { + if (!url.startsWith('ws://')) return false; + let host: string; + + try { + host = new URL(url).hostname; + } catch { + return true; // not ours to parse; treat it as the case that needs an explicit opt-in + } + + return !(host === 'localhost' || host === '[::1]' || /^127(\.\d{1,3}){3}$/.test(host)); +} + /** - * Warn when a teapot's shared secret would cross a network in cleartext. + * Refuse a `ws://` teapot that is not on this machine, unless `allowInsecure` (#86). * - * The `hello` frame carries the secret verbatim, so `ws://` to anywhere but this machine puts it on - * the wire for anyone in the path to read. Loopback is exempt because there is no path. - * - * A warning rather than a refusal: a private network behind a service mesh that already does mutual - * TLS is a legitimate deployment, and green-tea cannot tell it apart from an exposed one. + * The `hello` frame carries the secret verbatim, so `ws://` to anywhere but loopback puts it on the + * wire for anyone in the path to read. Checked in `createApp`, before any connection, so the mistake + * is a boot error rather than a leak. A private network that already encrypts (a service mesh with + * mutual TLS) is a legitimate deployment green-tea cannot tell apart from an exposed one, so it can + * opt in, and is still warned about it. */ -function warnIfCleartext(url: string, logger: Logger): void { - if (!url.startsWith('ws://')) return; - const host = url.slice('ws://'.length).split('/')[0].split(':')[0]; - if (host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]') return; +function assertTeapotTransport(mesh: MeshConfig | undefined, logger: Logger): void { + for (const { url } of mesh?.teapots ?? []) { + if (!crossesNetworkInCleartext(url)) continue; - logger.warn( - `mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` + - 'use wss:// unless the link already runs inside an encrypted network.', - ); + if (!mesh?.allowInsecure) { + throw new Error( + `mesh: ${url} is not encrypted, and the shared secret is sent in the handshake. Use wss://, ` + + 'or set `mesh.allowInsecure: true` if the link already runs inside an encrypted network.', + ); + } + + logger.warn( + `mesh: ${url} is not encrypted, and the shared secret is sent in the handshake — ` + + 'allowed by `mesh.allowInsecure`; make sure the network encrypts it.', + ); + } } /** A route a teapot exported, and the teapot it came from. */ @@ -1482,7 +1504,6 @@ async function spliceRemoteScopes( try { for (const teapot of teapots) { - warnIfCleartext(teapot.url, logger); const holder: { link?: Link } = {}; const link = await connectUntilDeadline(mesh, bus, logger, teapot.url, () => connectTeapot(ctx, teapot, holder)); diff --git a/src/app/types.ts b/src/app/types.ts index e9ac091..bb0b045 100644 --- a/src/app/types.ts +++ b/src/app/types.ts @@ -194,6 +194,13 @@ export interface MeshConfig { * starts. To make a teapot's absence fatal, have something local `@needs` one of its tokens. */ bootTimeoutMs?: number; + /** + * Allow `ws://` teapots that are not on this machine (default: `false`). The handshake sends the + * teapot's secret verbatim, so without this `createApp` refuses a cleartext link off loopback. Set + * it only when the network already encrypts the link, for example a service mesh with mutual TLS; + * each such teapot is still logged as a warning. + */ + allowInsecure?: boolean; } /** diff --git a/test/mesh/envelope.test.ts b/test/mesh/envelope.test.ts index 8dcffe1..af94004 100644 --- a/test/mesh/envelope.test.ts +++ b/test/mesh/envelope.test.ts @@ -222,7 +222,20 @@ describe('cleartext secret warning', () => { } }); - it('warns when the secret would cross a network in cleartext', async () => { + it('refuses a remote ws:// teapot at createApp (#86)', () => { + const make = (url: string) => + createApp({ modules: [TeacupModule], experimental: true, mesh: { teapots: [{ url, secret: 'good' }] } }); + + for (const url of ['ws://10.255.255.1:9/__mesh__/control', 'ws://billing.internal/__mesh__/control']) { + expect(() => make(url), url).toThrow(/not encrypted[\s\S]*allowInsecure/); + } + // loopback and wss:// boot (nothing connects until the first request) + for (const url of ['ws://localhost:9/x', 'ws://127.0.0.2:9/x', 'ws://[::1]:9/x', 'wss://billing.example/x']) { + expect(() => make(url), url).not.toThrow(); + } + }); + + it('with mesh.allowInsecure, boots and still warns that the secret crosses in cleartext', async () => { const warned: string[] = []; const logger = { debug() {}, info() {}, warn: (m: string) => warned.push(m), error() {} }; @@ -230,17 +243,13 @@ describe('cleartext secret warning', () => { modules: [TeacupModule], experimental: true, logger, - // unreachable on purpose: the warning is emitted before the connection is attempted, - // because it is about what would be sent, not about what succeeded - mesh: { teapots: [{ url: 'ws://10.255.255.1:9/__mesh__/control', secret: 'good' }], timeoutMs: 300 }, + mesh: { + teapots: [{ url: 'ws://10.255.255.1:9/__mesh__/control', secret: 'good' }], + allowInsecure: true, + }, }); + await teacup.close(); - try { - await expect(teacup.fetch(new Request('http://x/api/local/who'))).rejects.toThrow(); - } finally { - await teacup.close(); - } - - expect(warned.some((m) => m.includes('not encrypted') && m.includes('wss://'))).toBe(true); + expect(warned.some((m) => m.includes('not encrypted') && m.includes('allowInsecure'))).toBe(true); }); }); From d9d7d494110de29c9154f7b76e18f9194a81a8d2 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:18:42 -0600 Subject: [PATCH 13/41] feat(mesh): refuse mesh on the edge with a clear error Mesh cannot run on Cloudflare Workers (no timingSafeEqual under nodejs_compat, no long-lived outbound sockets), but an app configured with it booted there and failed later, somewhere unrelated. createApp throws when it detects a Workers isolate, which covers a bare app.fetch export, and edgeHandler throws for an app configured with mesh through a symbol-keyed flag, like TLS_REQUESTED, for the Worker detection cannot see. The mesh option checks move out of createApp into assertMeshAllowed to keep it under the complexity limit. Tested in vitest and inside workerd. Closes #87 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ README.md | 2 +- src/app/index.ts | 31 +++++++++++++++++++++++-------- src/edge.ts | 3 ++- src/security.ts | 18 ++++++++++++++++++ test/edge/run.ts | 7 ++++++- test/edge/worker.ts | 11 +++++++++++ test/mesh/edge-refusal.test.ts | 27 +++++++++++++++++++++++++++ 8 files changed, 93 insertions(+), 11 deletions(-) create mode 100644 test/mesh/edge-refusal.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index e50c4fa..31bc788 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -60,6 +60,11 @@ npm treats versions as semver and semver forbids leading zeros. Loopback (`localhost`, `127.0.0.0/8`, `[::1]`) is unaffected. Mesh is `@experimental`: the change stays within `MeshConfig` (D19). +- **Mesh on the edge fails with an error that says so** (#87). Mesh cannot run on Cloudflare + Workers, but an app that configured it booted there and failed later, elsewhere. `createApp` with + `mesh` now throws when it detects a Workers isolate, and `edgeHandler` throws for such an app + whatever detection saw. Mesh is `@experimental`; no API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index c2ef2b1..c147138 100644 --- a/README.md +++ b/README.md @@ -308,7 +308,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h **What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists. -**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. +**Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide): `createApp` with `mesh` fails inside a Worker, and so does `edgeHandler` given such an app. Workers also require the `nodejs_compat` flag. Native TLS (`createApp({ tls })`) is Node's `listen()` only: `serveDeno()` and `serveBun()` reject an app that sets it rather than serve it as plain HTTP, so configure TLS on that runtime's server or at a proxy, as you would on the edge. With `compression`, core never encodes on the edge (Cloudflare does), and on Deno it runs zlib on the main thread, where Deno's own `automaticCompression` is the faster gzip. **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. diff --git a/src/app/index.ts b/src/app/index.ts index 46478cd..a03f5e1 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -9,7 +9,7 @@ import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } fro import type { HttpOptions } from '../http'; import { trustedProxyClient } from '../http/peer'; import { answerFetchProbe, buildFetch } from '../http/web'; -import { resolveCompression, edgeMarker, MARK_EDGE, type CompressionOptions } from '../http/compression'; +import { resolveCompression, edgeMarker, isWorkerd, MARK_EDGE, type CompressionOptions } from '../http/compression'; import { boundInbound, controlBounds, @@ -49,6 +49,8 @@ import { TLS_REQUESTED, WS_ORIGIN_CHECK, assertCorsOptions, + MESH_REQUESTED, + MESH_ON_EDGE, wsOriginAllowed, type TlsOptions, type SecurityOptions, @@ -284,19 +286,29 @@ export interface AppOptions { warnGraphDepth?: number | false; } -/** - * Build an {@link App} from the given modules and options. - * Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps - * the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}. - */ -export function createApp(opts: AppOptions): App { +/** Throws for a `mesh` config this app cannot run: without the opt-in, or inside a Worker. */ +function assertMeshAllowed(opts: AppOptions): void { + if (!opts.mesh) return; + // mesh is alpha: its API and wire protocol may change. Require an explicit opt-in. - if (opts.mesh && !opts.experimental) { + if (!opts.experimental) { throw new Error( 'mesh is an alpha feature — pass `experimental: true` to createApp to enable it (its API may change between releases)', ); } + // Detected here so a bare `export default { fetch: app.fetch }` on a Worker fails too; `edgeHandler` + // refuses explicitly through MESH_REQUESTED for a Worker detection cannot see (#87). + if (isWorkerd()) throw new Error(MESH_ON_EDGE); +} + +/** + * Build an {@link App} from the given modules and options. + * Wires providers, steps, controllers and plugins into a dependency graph; for non-mesh apps + * the graph is finalized eagerly, otherwise finalization is deferred to {@link App.listen}. + */ +export function createApp(opts: AppOptions): App { + assertMeshAllowed(opts); validateWsLimits(opts.limits); const health = resolveHealth(opts.health, opts.shutdownTimeoutMs, opts.teardownTimeoutMs); assertEtagOption(opts.etag); @@ -547,6 +559,9 @@ export function createApp(opts: AppOptions): App { // `serveDeno` and `serveBun` refuse an app that asked for TLS only Node's listener can give. [TLS_REQUESTED]: Boolean(opts.tls), + // `edgeHandler` refuses an app that configured mesh, which cannot run there (#87). + [MESH_REQUESTED]: Boolean(opts.mesh), + // The fetch adapters refuse a cross-site upgrade before accepting it (GHSA-p697-fpqx-pgf3). The // mesh control channel is exempt: it authenticates with its secret, not with cookies. [WS_ORIGIN_CHECK]: (origin: string | null, host: string, path: string): boolean => diff --git a/src/edge.ts b/src/edge.ts index 635db24..67807ab 100644 --- a/src/edge.ts +++ b/src/edge.ts @@ -2,7 +2,7 @@ import type { App } from './app/types'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { setProxyClient } from './http/peer'; import { MARK_EDGE } from './http/compression'; -import { refuseWsOrigin } from './security'; +import { refuseMeshOnEdge, refuseWsOrigin } from './security'; // Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types. // Declares only what we call; mirrors the real workerd signatures. @@ -33,6 +33,7 @@ declare const WebSocketPair: { new (): { 0: EdgeWebSocket; 1: EdgeWebSocket } }; export function edgeHandler( app: App, ): (request: Request, env?: unknown, ctx?: EdgeCtx) => Response | Promise { + refuseMeshOnEdge(app); (app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.(); return (request, _env, ctx) => { diff --git a/src/security.ts b/src/security.ts index 085362d..7e229b5 100644 --- a/src/security.ts +++ b/src/security.ts @@ -27,6 +27,24 @@ export function refuseTls(app: object, adapter: string): void { } } +/** + * Set on an app created with `mesh`, so `edgeHandler` can refuse it (#87). Mesh does not run on the + * edge: the teapot's secret check needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` + * lacks, and a teacup's links are long-lived outbound sockets a Worker cannot hold. Without this the + * app booted and failed later, somewhere else. Symbol-keyed because it is adapter plumbing. + */ +export const MESH_REQUESTED: unique symbol = Symbol.for('green-tea.mesh-requested'); + +/** The one message for mesh on the edge, from `createApp` (detected) or `edgeHandler` (explicit). */ +export const MESH_ON_EDGE = + 'mesh does not run on the edge (Cloudflare Workers): the teapot needs node:crypto timingSafeEqual and ' + + 'a teacup needs long-lived outbound sockets. Run mesh nodes on Node, Deno or Bun, and drop `mesh` here.'; + +/** Throws when `app` was created with `mesh` (#87). */ +export function refuseMeshOnEdge(app: object): void { + if ((app as { [MESH_REQUESTED]?: boolean })[MESH_REQUESTED]) throw new Error(MESH_ON_EDGE); +} + /** * Set on every app to the function the fetch adapters (`serveDeno`, `serveBun`, `edgeHandler`) call * before they accept a WebSocket upgrade: `(origin, host, path) => allowed`. Symbol-keyed because it diff --git a/test/edge/run.ts b/test/edge/run.ts index 4edcd87..d2863d7 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -204,6 +204,11 @@ async function main() { code: 1008, reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret', }); + // #87: mesh is refused inside workerd at createApp, naming the edge. + const meshRes = await mf.dispatchFetch('http://meshedge/'); + assert.equal(meshRes.status, 500, 'mesh on the edge fails createApp'); + assert.match(await meshRes.text(), /^mesh does not run on the edge/); + const reservedRes = await mf.dispatchFetch('http://reserved/'); assert.equal(reservedRes.status, 500); assert.match(await reservedRes.text(), /^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/); @@ -228,7 +233,7 @@ async function main() { assert.equal(ready.headers.get('cache-control'), 'no-store'); console.log( - 'edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + health — PASS', + 'edge (workerd via miniflare): HTTP 200 + cookies + etag/304 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path + mesh refused + health — PASS', ); } finally { await mf.dispose(); diff --git a/test/edge/worker.ts b/test/edge/worker.ts index 1e3bb77..62c3add 100644 --- a/test/edge/worker.ts +++ b/test/edge/worker.ts @@ -112,10 +112,21 @@ function reservedBoot(): Response { return new Response('booted', { status: 200 }); } +// #87: an app configured with mesh fails createApp inside workerd, with a message that says why. +function meshBoot(): Response { + try { + createApp({ modules: [M], experimental: true, mesh: { secret: 'x' } }); + } catch (error) { + return new Response((error as Error).message, { status: 500 }); + } + return new Response('booted', { status: 200 }); +} + export default { fetch: (request: Request, env?: unknown, ctx?: Parameters>[2]) => { const host = new URL(request.url).hostname; if (host === 'reserved') return reservedBoot(); + if (host === 'meshedge') return meshBoot(); return (handlers[host] ?? handlers.default)(request, env, ctx); }, }; diff --git a/test/mesh/edge-refusal.test.ts b/test/mesh/edge-refusal.test.ts new file mode 100644 index 0000000..02c26ce --- /dev/null +++ b/test/mesh/edge-refusal.test.ts @@ -0,0 +1,27 @@ +// #87: mesh cannot run on the edge, so an app that configures it is refused there with a message +// that says so, instead of booting and failing later. The workerd run is in test/edge/run.ts. +import { describe, it, expect, afterEach, vi } from 'vitest'; +import { createApp, Module } from '../../src/index'; +import { edgeHandler } from '../../src/edge'; + +@Module({ mountpoint: '/' }) +class M {} + +const meshApp = () => createApp({ modules: [M], experimental: true, mesh: { secret: 'x' } }); + +describe('mesh on the edge', () => { + afterEach(() => vi.unstubAllGlobals()); + + it('edgeHandler refuses an app configured with mesh', () => { + expect(() => edgeHandler(meshApp())).toThrow(/mesh does not run on the edge/); + }); + + it('createApp refuses mesh when it detects a Workers isolate', () => { + vi.stubGlobal('navigator', { userAgent: 'Cloudflare-Workers' }); + expect(meshApp).toThrow(/mesh does not run on the edge/); + }); + + it('leaves an app without mesh alone', () => { + expect(() => edgeHandler(createApp({ modules: [M] }))).not.toThrow(); + }); +}); From cee0d1f1a4347db669071b48643991b8cb2ae5fb Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:24:04 -0600 Subject: [PATCH 14/41] docs(example): mesh REST demo across two processes A billing teapot owns an in-memory ledger and exports a balance step and its REST routes; a shop teacup serves a checkout route that @needs('balance') like a local step, and serves billing's routes as its own. The walkthrough is in example/README.md. test/examples/mesh.test.ts runs it with billing as a real child process: requests across the hop, a validation error crossing with its status, 503 + retry-after after billing is killed, and recovery once it starts again on the same port. Billing is started with node --import tsx, because the tsx binary runs the app in a grandchild that a kill would leave behind. Refs: #88 Signed-off-by: Diego Resendez --- CHANGELOG.md | 9 ++++ example/README.md | 39 ++++++++++++++ example/mesh/billing.ts | 88 ++++++++++++++++++++++++++++++ example/mesh/shop.ts | 53 ++++++++++++++++++ test/examples/mesh.test.ts | 108 +++++++++++++++++++++++++++++++++++++ 5 files changed, 297 insertions(+) create mode 100644 example/mesh/billing.ts create mode 100644 example/mesh/shop.ts create mode 100644 test/examples/mesh.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 31bc788..8c731c9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,15 @@ npm treats versions as semver and semver forbids leading zeros. ## [Unreleased] +### Added + +- **A runnable mesh demo: one REST API across two processes** (#88). `example/mesh/` has a billing + teapot (a private ledger, an exported `balance` step and REST routes) and a shop teacup whose + checkout `@needs('balance')` like a local step and which serves billing's routes. The walkthrough + is in `example/README.md`, and `test/examples/mesh.test.ts` runs it with billing in a real child + process that it kills and restarts: `503` with `retry-after` while billing is down, then automatic + recovery. + ### Security - **Mesh: a teapot checks the HTTP method of a route RPC, not just its pattern** diff --git a/example/README.md b/example/README.md index e98d837..be99c28 100644 --- a/example/README.md +++ b/example/README.md @@ -7,6 +7,8 @@ npx tsx example/server.ts # the tour, below npx tsx example/crud.ts # a CRUD API over an in-memory store, on :3300 npx tsx example/chat.ts # WebSocket rooms, on ws://localhost:4100/chat/:room?token=... npx tsx example/graphql.ts # GraphQL queries and subscriptions over SSE, on :4200/graphql +npx tsx example/mesh/billing.ts # mesh teapot on :3401; then, in a second terminal: +npx tsx example/mesh/shop.ts # mesh teacup on :3400 (see Mesh, below) ``` `server.ts` demonstrates the typed context contract, graph-derived order, `app.inspect()`, a @@ -16,3 +18,40 @@ teacup. Try it with: ```bash curl -H 'x-token: u1' http://localhost:3000/api/users/9 ``` + +## Mesh: one REST API across two processes + +`example/mesh/` splits a small shop across two nodes. Mesh is alpha and needs +`createApp({ experimental: true })`; don't ship it to production yet. + +- **`billing.ts`** is the teapot. It owns the ledger (never exported: a mesh export carries data, + not handles) and exports a step, `balance`, plus its REST routes under `/billing`. +- **`shop.ts`** is the teacup. Its `GET /shop/checkout/:customer` does `@needs('balance')` exactly + as it would a local step; only the mesh config says that `balance` lives on billing. It also + serves billing's routes as if they were its own. + +Start billing first: checkout needs `balance` at boot, and a teacup refuses to boot without a +producer for a token it needs. + +```bash +npx tsx example/mesh/billing.ts # teapot on :3401 +npx tsx example/mesh/shop.ts # teacup on :3400 +``` + +```bash +curl localhost:3400/shop/checkout/ada # {"customer":"ada","due":40,"canCheckout":false} +curl -X POST -H 'content-type: application/json' \ + -d '{"amount":10}' localhost:3400/billing/invoices/ada # served by billing, through the shop +curl localhost:3400/billing/invoices/ada # both invoices +``` + +Stop billing and the shop keeps running: anything that needs billing answers `503` with +`retry-after` while the link reconnects. Start billing again and the shop reconnects on its own +within about a second. The ledger is in memory, so it starts over. + +The secret is `demo-secret` unless `MESH_SECRET` is set on both sides. `BILLING_PORT`, `SHOP_PORT` +and `BILLING_URL` move things around. `ws://` works here because both nodes are on loopback; to +another machine use `wss://`, or `createApp` refuses the link. + +`test/examples/mesh.test.ts` runs this walkthrough with billing in a real child process, killed and +restarted, so the demo cannot drift from what core does. diff --git a/example/mesh/billing.ts b/example/mesh/billing.ts new file mode 100644 index 0000000..4ca2a67 --- /dev/null +++ b/example/mesh/billing.ts @@ -0,0 +1,88 @@ +// The teapot: the billing service. It owns the ledger and exports two things over the mesh: +// a step (`balance`) another node can `@needs`, and its REST routes, which a teacup serves as if +// they were its own. The ledger itself is never exported: a mesh export carries data, not handles. +// +// npx tsx example/mesh/billing.ts # on :3401, or BILLING_PORT +// +// Mesh is alpha and behind `experimental: true`. See example/README.md for the walkthrough. +import { createApp, Provider, Step, Route, Get, Post, Module, needs, param, body, HttpError } from '../../src/index'; + +export interface Invoice { + id: number; + amount: number; + paid: boolean; +} + +export interface Ledger { + invoices(customer: string): Invoice[]; + add(customer: string, amount: number): Invoice; +} + +/** In-memory, so a restarted billing node starts empty. A real one would hold a database pool here. */ +@Provider({ provides: 'ledger' }) +class LedgerProvider { + provide(): { ledger: Ledger } { + const byCustomer = new Map([['ada', [{ id: 1, amount: 40, paid: false }]]]); + let next = 2; + + return { + ledger: { + invoices: (customer) => byCustomer.get(customer) ?? [], + add: (customer, amount) => { + const invoice = { id: next++, amount, paid: false }; + byCustomer.set(customer, [...(byCustomer.get(customer) ?? []), invoice]); + return invoice; + }, + }, + }; + } +} + +/** + * Exported: computed here, per request, from the caller's route params. A teacup that + * `@needs('balance')` gets this result; it never sees the ledger. + */ +@Step({ provides: 'balance', needs: ['ledger'], export: true }) +class BalanceStep { + run(ctx: { ledger: Ledger; params: { customer?: string } }) { + const customer = ctx.params.customer ?? ''; + const due = ctx.ledger + .invoices(customer) + .filter((invoice) => !invoice.paid) + .reduce((sum, invoice) => sum + invoice.amount, 0); + + return { balance: { customer, due } }; + } +} + +@Route('/billing') +class BillingController { + @Get('/invoices/:customer', { export: true }) + list(@needs('ledger') ledger: Ledger, @param('customer') customer: string) { + return { customer, invoices: ledger.invoices(customer) }; + } + + @Post('/invoices/:customer', { export: true }) + create(@needs('ledger') ledger: Ledger, @param('customer') customer: string, @body() data: { amount?: unknown }) { + const amount = Number(data?.amount); + if (!Number.isFinite(amount) || amount <= 0) throw new HttpError(422, 'amount must be a positive number'); + + return ledger.add(customer, amount); + } +} + +@Module({ mountpoint: '/', providers: [LedgerProvider], steps: [BalanceStep], controllers: [BillingController] }) +class BillingModule {} + +/** The secret every teacup must present. Set MESH_SECRET outside a demo. */ +export const MESH_SECRET = process.env.MESH_SECRET ?? 'demo-secret'; + +export const billing = createApp({ modules: [BillingModule], experimental: true, mesh: { secret: MESH_SECRET } }); + +if (require.main === module) { + billing.listen(Number(process.env.BILLING_PORT ?? 3401)).then((server) => { + const { port } = server.address() as { port: number }; + // The test reads this line to learn the port. + console.log(`billing (teapot) on http://127.0.0.1:${port}`); + }); +} diff --git a/example/mesh/shop.ts b/example/mesh/shop.ts new file mode 100644 index 0000000..dcf4df9 --- /dev/null +++ b/example/mesh/shop.ts @@ -0,0 +1,53 @@ +// The teacup: the shop. It serves its own checkout route, which `@needs('balance')` exactly as it +// would a local step, and it serves billing's exported routes as if they were its own. Nothing in +// the controller says where `balance` lives; only the mesh config does. +// +// npx tsx example/mesh/billing.ts # start the teapot first: checkout needs `balance` at boot +// npx tsx example/mesh/shop.ts # on :3400, or SHOP_PORT; BILLING_URL points at the teapot +// +// Mesh is alpha and behind `experimental: true`. See example/README.md for the walkthrough. +import { createApp, Route, Get, Module, needs, MESH_CONTROL_PATH } from '../../src/index'; + +interface Balance { + customer: string; + due: number; +} + +@Route('/shop') +class CheckoutController { + @Get('/checkout/:customer') + checkout(@needs('balance') balance: Balance) { + return { customer: balance.customer, due: balance.due, canCheckout: balance.due === 0 }; + } +} + +@Module({ mountpoint: '/', controllers: [CheckoutController] }) +class ShopModule {} + +/** + * `billingUrl` is the teapot's control channel. `ws://` is fine on loopback; to another machine use + * `wss://`, or `createApp` refuses (mesh.allowInsecure exists for networks that already encrypt). + */ +export function createShop(billingUrl: string, secret = process.env.MESH_SECRET ?? 'demo-secret') { + return createApp({ + modules: [ShopModule], + experimental: true, + mesh: { + teapots: [{ url: billingUrl, secret }], + // Quick retries so the demo recovers in about a second after billing comes back. + reconnect: { initialDelayMs: 100, maxDelayMs: 1_000 }, + bootTimeoutMs: 5_000, + }, + }); +} + +if (require.main === module) { + const billingUrl = process.env.BILLING_URL ?? `ws://127.0.0.1:3401${MESH_CONTROL_PATH}`; + + createShop(billingUrl) + .listen(Number(process.env.SHOP_PORT ?? 3400)) + .then((server) => { + const { port } = server.address() as { port: number }; + console.log(`shop (teacup) on http://127.0.0.1:${port}, billing at ${billingUrl}`); + }); +} diff --git a/test/examples/mesh.test.ts b/test/examples/mesh.test.ts new file mode 100644 index 0000000..aca665c --- /dev/null +++ b/test/examples/mesh.test.ts @@ -0,0 +1,108 @@ +// The mesh REST demo (example/mesh), across two real processes: billing runs as a child process so +// the test can kill it and start it again, and the shop runs here. Guards the demo against rot (#88). +import { describe, it, expect, afterAll } from 'vitest'; +import { spawn, type ChildProcess } from 'node:child_process'; +import { join } from 'node:path'; +import { MESH_CONTROL_PATH } from '../../src/index'; +import { createShop } from '../../example/mesh/shop'; + +const ROOT = join(__dirname, '..', '..'); + +/** Starts example/mesh/billing.ts as its own process and resolves once it is listening. */ +function startBilling(port = 0): Promise<{ child: ChildProcess; port: number }> { + // `node --import tsx` rather than the `tsx` binary, which runs the app in a child of its own: killing + // the wrapper would leave the real server up, and the test would never see billing die. + const child = spawn(process.execPath, ['--import', 'tsx', join(ROOT, 'example', 'mesh', 'billing.ts')], { + cwd: ROOT, + env: { ...process.env, BILLING_PORT: String(port) }, + stdio: ['ignore', 'pipe', 'inherit'], + }); + + return new Promise((resolve, reject) => { + let out = ''; + child.stdout!.on('data', (chunk) => { + out += chunk; + const match = /billing \(teapot\) on http:\/\/127\.0\.0\.1:(\d+)/.exec(out); + if (match) resolve({ child, port: Number(match[1]) }); + }); + child.once('exit', (code) => reject(new Error(`billing exited early (${code}): ${out}`))); + }); +} + +/** Polls until `check` passes; the mesh reacts to a dead or returning peer within a second or so. */ +async function eventually(check: () => Promise, ms = 8_000): Promise { + const deadline = Date.now() + ms; + + for (;;) { + try { + return await check(); + } catch (error) { + if (Date.now() > deadline) throw error; + await new Promise((resolve) => setTimeout(resolve, 100)); + } + } +} + +const children: ChildProcess[] = []; +let closeShop: (() => Promise) | undefined; + +afterAll(async () => { + await closeShop?.(); + for (const child of children) child.kill('SIGKILL'); +}); + +describe('mesh REST demo', () => { + it('serves across processes, answers 503 while billing is down, and recovers', async () => { + const first = await startBilling(); + children.push(first.child); + + const shop = createShop(`ws://127.0.0.1:${first.port}${MESH_CONTROL_PATH}`); + const server = await shop.listen(0); + closeShop = async () => { + await shop.close(); + server.close(); + }; + const base = `http://127.0.0.1:${(server.address() as { port: number }).port}`; + const get = (path: string) => fetch(`${base}${path}`); + const json = async (path: string): Promise => (await get(path)).json(); + + // A local route that needs a remote step: `balance` is computed on billing from this request's params. + expect(await (await get('/shop/checkout/ada')).json()).toEqual({ customer: 'ada', due: 40, canCheckout: false }); + + // Billing's own REST routes, served by the shop. + const created = await fetch(`${base}/billing/invoices/ada`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ amount: 10 }), + }); + expect(created.status).toBe(200); + expect(await created.json()).toMatchObject({ amount: 10, paid: false }); + expect((await json('/billing/invoices/ada')).invoices).toHaveLength(2); + expect((await json('/shop/checkout/ada')).due).toBe(50); + + // Billing's validation error crosses the hop with its status and message. + const invalid = await fetch(`${base}/billing/invoices/ada`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ amount: -1 }), + }); + expect(invalid.status).toBe(422); + + // Billing dies: both kinds of remote export answer 503 with retry-after, and the shop stays up. + first.child.kill('SIGKILL'); + await eventually(async () => { + const res = await get('/shop/checkout/ada'); + expect(res.status).toBe(503); + expect(res.headers.get('retry-after')).toBeTruthy(); + }); + expect((await get('/billing/invoices/ada')).status).toBe(503); + + // Billing comes back on the same port: the shop reconnects on its own and serves again. The + // ledger is in memory, so it starts over. + const second = await startBilling(first.port); + children.push(second.child); + await eventually(async () => { + expect(await (await get('/shop/checkout/ada')).json()).toEqual({ customer: 'ada', due: 40, canCheckout: false }); + }); + }, 30_000); +}); From 9187670a86e175feacb6ded401d88d375137ba77 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:32:44 -0600 Subject: [PATCH 15/41] fix(views): render templates in one pass, own keys only render() replaced {{{ }}} first and then ran {{ }} over the result, so a value inserted raw was scanned again: content holding {{ user.passwordHash }} rendered the hash. It also walked inherited members, so {{ constructor }} printed a function's source. Match both forms with one regex in one pass, so inserted values are never scanned, and resolve keys as own properties (hasOwnProperty; the tsconfig lib predates Object.hasOwn). Refs: GHSA-g86h-3r98-qm66 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ src/views.ts | 19 +++++++++++++++---- test/views.test.ts | 7 +++++++ 3 files changed, 27 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c731c9..4de374e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,11 @@ npm treats versions as semver and semver forbids leading zeros. `mesh` now throws when it detects a Workers isolate, and `edgeHandler` throws for such an app whatever detection saw. Mesh is `@experimental`; no API change. +- **The built-in template engine no longer renders what `{{{ }}}` inserted** (GHSA-g86h-3r98-qm66). + It ran `{{ }}` over the output of `{{{ }}}`, so raw content holding `{{ user.passwordHash }}` + rendered the hash. Both forms are now matched in one pass, and keys resolve to own properties only, + so `{{ constructor }}` renders empty instead of a function's source. No API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/src/views.ts b/src/views.ts index 254d55c..8cdb58e 100644 --- a/src/views.ts +++ b/src/views.ts @@ -20,11 +20,22 @@ function stringify(v: unknown): string { * `{{ a.b }}` walks nested keys, a missing key renders empty. No loops/conditionals/partials. */ export function render(source: string, data: unknown): string { + // Own keys only, so `{{ constructor }}` renders empty rather than a function's source. const lookup = (key: string): unknown => - key.split('.').reduce((obj, k) => (obj === null || obj === undefined ? undefined : obj[k]), data); - return source - .replace(/\{\{\{\s*([\w.]+)\s*\}\}\}/g, (_, key) => stringify(lookup(key))) - .replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => escapeHtml(stringify(lookup(key)))); + key + .split('.') + .reduce( + (obj, k) => + obj !== null && obj !== undefined && Object.prototype.hasOwnProperty.call(obj, k) ? obj[k] : undefined, + data, + ); + + // One pass over the source for both forms. Two passes ran `{{ }}` again over what `{{{ }}}` had + // inserted, so raw content holding `{{ user.passwordHash }}` rendered the hash + // (GHSA-g86h-3r98-qm66). Inserted values are never scanned. + return source.replace(/\{\{\{\s*([\w.]+)\s*\}\}\}|\{\{\s*([\w.]+)\s*\}\}/g, (_, raw, escaped) => + raw === undefined ? escapeHtml(stringify(lookup(escaped))) : stringify(lookup(raw)), + ); } const CONTENT_TYPES: Record = { diff --git a/test/views.test.ts b/test/views.test.ts index 2523385..9f64172 100644 --- a/test/views.test.ts +++ b/test/views.test.ts @@ -17,6 +17,13 @@ describe('render', () => { it('resolves nested keys and renders missing keys as empty', () => { expect(render('{{ user.name }}|{{ nope }}', { user: { name: 'Diego' } })).toBe('Diego|'); }); + it('never re-renders what {{{ x }}} inserted (GHSA-g86h-3r98-qm66)', () => { + const data = { bio: 'hi {{ secret }} {{{ secret }}}', secret: 'hash' }; + expect(render('{{{ bio }}}|{{ bio }}', data)).toBe('hi {{ secret }} {{{ secret }}}|hi {{ secret }} {{{ secret }}}'); + }); + it('reads own keys only, so inherited members render empty', () => { + expect(render('[{{ constructor }}][{{ user.toString }}][{{ name.length }}]', { user: {}, name: 'abc' })).toBe('[][][3]'); + }); }); describe('contentTypeFor', () => { From 08eeb2aab6cf1a3ea4dd3f593c15cd4b9a6d5f86 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:34:21 -0600 Subject: [PATCH 16/41] fix(body): treat a __proto__ field or file as an ordinary key Form field and file names come from the client. With bodyDuplicates: 'array', __proto__=a&__proto__=b assigned an array to the parsed body's __proto__, replacing its prototype, and a multipart file part named __proto__ did the same to body.files. Object.prototype itself was never touched. Read with hasOwnProperty and write with defineProperty, so __proto__ is just another own key in both the urlencoded and multipart paths. Refs: GHSA-g86h-3r98-qm66 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ src/multipart.ts | 26 ++++++++++++++++++++------ test/multipart.test.ts | 29 ++++++++++++++++++++++++++++- 3 files changed, 53 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4de374e..5158ea7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -79,6 +79,11 @@ npm treats versions as semver and semver forbids leading zeros. rendered the hash. Both forms are now matched in one pass, and keys resolve to own properties only, so `{{ constructor }}` renders empty instead of a function's source. No API change. +- **A form field or file named `__proto__` is an ordinary key** (GHSA-g86h-3r98-qm66). With + `bodyDuplicates: 'array'`, `__proto__=a&__proto__=b` replaced the parsed body's prototype, and a + multipart file part with that name did the same to `body.files`. Fields and files are now read and + written as own properties. The effect never reached `Object.prototype`. No API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/src/multipart.ts b/src/multipart.ts index b4735bd..a3ad397 100644 --- a/src/multipart.ts +++ b/src/multipart.ts @@ -35,13 +35,27 @@ export function extractBoundary(contentType: string): string | undefined { return boundary || undefined; } +/** + * Field and file names come from the client, and one of them may be `__proto__`. Plain reads and + * writes of that key hit the object's prototype: `fields.__proto__ = ['a','b']` turned the parsed + * body into an array-like (GHSA-g86h-3r98-qm66). These two read and write own properties only, so + * `__proto__` is just another field name. + */ +function ownValue(target: Record, key: string): T | undefined { + return Object.prototype.hasOwnProperty.call(target, key) ? target[key] : undefined; +} + +function setOwn(target: Record, key: string, value: T): void { + Object.defineProperty(target, key, { value, writable: true, enumerable: true, configurable: true }); +} + function addField(fields: MultipartBody['fields'], name: string, value: string, duplicates: 'array' | 'last'): void { if (duplicates === 'array') { - const existing = fields[name]; + const existing = ownValue(fields, name); if (Array.isArray(existing)) existing.push(value); - else fields[name] = [value]; + else setOwn(fields, name, [value]); } else { - fields[name] = value; // last-wins + setOwn(fields, name, value); // last-wins } } @@ -59,10 +73,10 @@ export function collapseDuplicates( } function addFile(files: MultipartBody['files'], name: string, file: UploadedFile): void { - const existing = files[name]; - if (existing === undefined) files[name] = file; + const existing = ownValue(files, name); + if (existing === undefined) setOwn(files, name, file); else if (Array.isArray(existing)) existing.push(file); - else files[name] = [existing, file]; + else setOwn(files, name, [existing, file]); } /** Lazily loads the optional `busboy` peer dependency, or null when it is not installed. */ diff --git a/test/multipart.test.ts b/test/multipart.test.ts index d4d01c0..865c11b 100644 --- a/test/multipart.test.ts +++ b/test/multipart.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { parseMultipart, extractBoundary } from '../src/multipart'; +import { parseMultipart, extractBoundary, collapseDuplicates } from '../src/multipart'; const B = 'X-BOUND'; function body(parts: string[]): Buffer { @@ -97,3 +97,30 @@ describe('parseMultipart', () => { await expect(parseMultipart(Buffer.from('garbage'), B, opts)).rejects.toThrow(); }); }); + +describe('a field or file named __proto__ (GHSA-g86h-3r98-qm66)', () => { + it('is an own key of the urlencoded body, and never its prototype', () => { + const pairs = new URLSearchParams('__proto__=a&__proto__=b&x=1'); + const arrays = collapseDuplicates(pairs, 'array'); + expect(Object.getPrototypeOf(arrays)).toBe(Object.prototype); + expect(Object.prototype.hasOwnProperty.call(arrays, '__proto__')).toBe(true); + expect(Object.getOwnPropertyDescriptor(arrays, '__proto__')?.value).toEqual(['a', 'b']); + expect((arrays as any).length).toBeUndefined(); + + const last = collapseDuplicates(new URLSearchParams('__proto__=a'), 'last'); + expect(Object.getPrototypeOf(last)).toBe(Object.prototype); + expect(Object.getOwnPropertyDescriptor(last, '__proto__')?.value).toBe('a'); + }); + + it('does the same for multipart fields and files', async () => { + const r = await parseMultipart( + body([field('__proto__', 'x'), field('__proto__', 'y'), file('__proto__', 'a', 'text/plain', 'A'), file('__proto__', 'b', 'text/plain', 'B')]), + B, + { maxParts: 1000, duplicates: 'array' }, + ); + expect(Object.getPrototypeOf(r.fields)).toBe(Object.prototype); + expect(Object.getPrototypeOf(r.files)).toBe(Object.prototype); + expect(Object.getOwnPropertyDescriptor(r.fields, '__proto__')?.value).toEqual(['x', 'y']); + expect((Object.getOwnPropertyDescriptor(r.files, '__proto__')?.value as unknown[]).length).toBe(2); + }); +}); From 0e4b51c22d09d856b083502264ea17cbc52fb51e Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:35:24 -0600 Subject: [PATCH 17/41] fix(params): resolve decorator keys as own properties A key the request did not send was looked up through the prototype, so @query('constructor') resolved to Object.prototype.constructor rather than undefined, and the same held for @body, @param, @header, @cookie and picked key lists. Read through hasOwnProperty. Headers still look up the lower-cased name. Refs: GHSA-g86h-3r98-qm66 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ src/params.ts | 7 ++++++- test/params.test.ts | 22 ++++++++++++++++++++++ 3 files changed, 33 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 5158ea7..869ef9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -84,6 +84,11 @@ npm treats versions as semver and semver forbids leading zeros. multipart file part with that name did the same to `body.files`. Fields and files are now read and written as own properties. The effect never reached `Object.prototype`. No API change. +- **`@query`, `@body`, `@param`, `@header` and `@cookie` read own keys only** + (GHSA-g86h-3r98-qm66). A key the request did not send resolved through the prototype, so + `@query('constructor')` returned `Object.prototype.constructor` instead of `undefined`. No API + change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/src/params.ts b/src/params.ts index 887b4e9..ce3f3b1 100644 --- a/src/params.ts +++ b/src/params.ts @@ -138,6 +138,8 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise; // Every adapter stores header names lower-cased, so `@header('Content-Type')` looks up // `content-type` (GitHub #37). A picked bag keeps the names as the handler wrote them. - const at = spec.source === 'headers' ? (key: string) => values[key.toLowerCase()] : (key: string) => values[key]; + // Own keys only: `@query('constructor')` on a request without that key is `undefined`, not + // `Object.prototype.constructor` (GHSA-g86h-3r98-qm66). + const own = (key: string) => (hasOwn.call(values, key) ? values[key] : undefined); + const at = spec.source === 'headers' ? (key: string) => own(key.toLowerCase()) : own; if (spec.keys) { const picked: Record = {}; diff --git a/test/params.test.ts b/test/params.test.ts index 98b8563..ac04bf5 100644 --- a/test/params.test.ts +++ b/test/params.test.ts @@ -219,3 +219,25 @@ describe('inheritance', () => { expect(getArgs(Child, 'other')).toEqual([{ index: 0, source: 'params', key: 'id' }]); }); }); + +test('a missing key resolves to undefined, never an inherited member (GHSA-g86h-3r98-qm66)', async () => { + class Inherited { + handler( + @query('constructor') _q: unknown, + @body('toString') _b: unknown, + @param('hasOwnProperty') _p: unknown, + @header('constructor') _h: unknown, + @query(['constructor', 'a']) _picked: unknown, + ) { + return null; + } + } + const args = await resolveArgs(getArgs(Inherited, 'handler'), { + query: { a: '1' }, + body: {}, + params: {}, + headers: {}, + }); + expect(args.slice(0, 4)).toEqual([undefined, undefined, undefined, undefined]); + expect(args[4]).toEqual({ constructor: undefined, a: '1' }); +}); From 843ba6b6061874ce068b92830bc2f71d7244ccb6 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:36:42 -0600 Subject: [PATCH 18/41] fix(fetch): honour X-Forwarded-Proto under trustProxy The fetch path took secure from the request URL's scheme only, so Deno and Bun behind a TLS-terminating proxy reported ctx.protocol 'http' and never sent HSTS, while Node read X-Forwarded-Proto under trustProxy. Mirror Node's deriveSecure on the fetch path, for both handled requests and health probes. Refs: GHSA-g86h-3r98-qm66 Signed-off-by: Diego Resendez --- CHANGELOG.md | 4 ++++ src/http/web.ts | 18 ++++++++++++++++-- test/fetch.test.ts | 19 +++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 869ef9d..97dcb78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -89,6 +89,10 @@ npm treats versions as semver and semver forbids leading zeros. `@query('constructor')` returned `Object.prototype.constructor` instead of `undefined`. No API change. +- **Deno, Bun and `app.fetch` honour `X-Forwarded-Proto` under `trustProxy`** + (GHSA-g86h-3r98-qm66), as Node always has. Behind a TLS-terminating proxy they reported + `ctx.protocol === 'http'` and never sent HSTS. No API change. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/src/http/web.ts b/src/http/web.ts index 55c1661..3a762ce 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -245,6 +245,20 @@ function outcomeToResponse( return new Response(body, { status: outcome.status, headers }); } +/** + * Whether the client's connection was HTTPS: `x-forwarded-proto` when the proxy is trusted, else the + * URL's scheme. Mirrors Node's `deriveSecure`. Without it, Deno and Bun behind a TLS-terminating proxy + * saw `http`, so `ctx.protocol` was wrong and HSTS was never sent (GHSA-g86h-3r98-qm66). + */ +function fetchSecure(request: Request, url: URL, opts: HttpOptions | undefined): boolean { + if (opts?.trustProxy) { + const proto = request.headers.get('x-forwarded-proto')?.split(',')[0].trim(); + if (proto) return proto === 'https'; + } + + return url.protocol === 'https:'; +} + /** The `x-forwarded-for` hop the trusted proxy appended (the right-most), else `''`. */ function forwardedFor(request: Request, opts: HttpOptions | undefined): string { if (!opts?.trustProxy) return ''; @@ -284,7 +298,7 @@ export function buildFetch(routes: RouteTable, opts: HttpOptions | undefined) { const headers = headersToRecord(request.headers); // Derived before the body is read, so a 413 rejected below still carries an identity. const correlation = correlateRequest(headers); - const secure = url.protocol === 'https:'; + const secure = fetchSecure(request, url, opts); // Computed up-front from the same inputs `handle()` uses, so a preflight — the one response // this adapter builds itself — carries the same security/CORS headers every other one does. const injected = computeInjected(opts, { secure, headers }); @@ -378,7 +392,7 @@ export function answerFetchProbe(request: Request, opts: HttpOptions | undefined if (!probe) return undefined; const injected = computeInjected(opts, { - secure: url.protocol === 'https:', + secure: fetchSecure(request, url, opts), headers: headersToRecord(request.headers), }); return new Response(probe.body || null, { diff --git a/test/fetch.test.ts b/test/fetch.test.ts index 6481612..b10f574 100644 --- a/test/fetch.test.ts +++ b/test/fetch.test.ts @@ -90,6 +90,9 @@ class IpCtl { @Get('/whoami') whoami(@ctx() c: any) { return { ip: c.ip }; } + @Get('/proto') proto(@ctx() c: any) { + return { protocol: c.protocol }; + } } @Module({ mountpoint: '/', controllers: [IpCtl] }) class IpModule {} @@ -400,3 +403,19 @@ describe('app.fetch bounded body reads (#105)', () => { expect(await res.json()).toEqual({}); }); }); + +describe('app.fetch trustProxy honours x-forwarded-proto (GHSA-g86h-3r98-qm66)', () => { + const viaTlsProxy = () => new Request('http://x/ip/proto', { headers: { 'x-forwarded-proto': 'https' } }); + + it('reports https and sends HSTS behind a trusted TLS proxy, like Node', async () => { + const res = await createApp({ modules: [IpModule], trustProxy: true }).fetch(viaTlsProxy()); + expect(await res.json()).toEqual({ protocol: 'https' }); + expect(res.headers.get('strict-transport-security')).toBeTruthy(); + }); + + it('ignores the header without trustProxy', async () => { + const res = await createApp({ modules: [IpModule] }).fetch(viaTlsProxy()); + expect(await res.json()).toEqual({ protocol: 'http' }); + expect(res.headers.get('strict-transport-security')).toBeNull(); + }); +}); From 88f967bd841d3412e8359109664ef06667655cdd Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:36:58 -0600 Subject: [PATCH 19/41] docs(routing): a decoded param can hold / and .. Segments are split before they are decoded, so /files/..%2F..%2Fetc gives name = '../../etc', and a catch-all can hold a/../../etc/passwd. That matches Express and is right for ids and slugs, but a handler that builds a filesystem path from a param can be walked out of its directory. Say so where routing is described, with the two ways to guard it. No behaviour change. Refs: GHSA-g86h-3r98-qm66 Signed-off-by: Diego Resendez --- CHANGELOG.md | 4 ++++ README.md | 2 ++ 2 files changed, 6 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 97dcb78..a1ac373 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -93,6 +93,10 @@ npm treats versions as semver and semver forbids leading zeros. (GHSA-g86h-3r98-qm66), as Node always has. Behind a TLS-terminating proxy they reported `ctx.protocol === 'http'` and never sent HSTS. No API change. +- **The README says that a decoded route param can hold `/` and `..`** (GHSA-g86h-3r98-qm66). + `/files/..%2F..%2Fetc` gives `name = "../../etc"`, as in Express. Nothing changes in routing; a + handler that builds a filesystem path from a param must contain it, or constrain the param. + - **WebSocket upgrades from another site are refused with `403`** (GHSA-p697-fpqx-pgf3), on Node, Deno, Bun and the edge. No adapter checked `Origin`, so a page on any site could open a WebSocket with the signed-in user's cookies and read what the handler streamed (cross-site WebSocket diff --git a/README.md b/README.md index c147138..8177aed 100644 --- a/README.md +++ b/README.md @@ -274,6 +274,8 @@ Patterns match by segment: static, constrained params such as `:id(\d+)`, plain @Get('/files/:path*') // /files/img/2026/logo.png → params.path = "img/2026/logo.png" ``` +**Params arrive decoded, and a decoded param can hold `/` and `..`.** The path is split into segments first and each segment decoded after, so `/files/..%2F..%2Fetc` matches `:name` with `name = "../../etc"`, and a catch-all can hold `a/../../etc/passwd`. That is what Express does too, and it is correct for an id or a slug. It matters the moment a param becomes a filesystem path: resolve it against its base directory and check the result is still inside, the way `static` does, or constrain it (`:name([\w-]+)`). + `@Head` and `@Options` provide explicit handlers. Otherwise a buffered GET can serve HEAD without a body, and OPTIONS on an existing path returns `204` with canonical `Allow`; other method mismatches return `405`. `/path` and `/path/` are equivalent, while repeated slashes and malformed encoding return `400` rather than being normalized ambiguously. Constraints use a deliberately safe regex subset. See the full [routing guide](https://green-tea.expressive-tea.io/docs/guides/routing/). Because that subset is linear, constraints are also compared at boot. Two routes that branch at the same segment, under the same prefix and method, fail `createApp`: From 5d901e86d18086a4cd2835194a73a717aa9084b1 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 19 Nov 2026 23:48:35 -0600 Subject: [PATCH 20/41] test: bind test servers to 127.0.0.1 so no socket can share their port Test clients connect to 127.0.0.1, but listen(0) with no host binds ::, and five tests bound 127.0.0.1 explicitly. On macOS a :: bind and a 127.0.0.1 bind are different sockets, so the OS can give a test server on :: a port another socket already holds on 127.0.0.1: another test file running in parallel, or another process. The client then reaches that one, and a fresh server "answered" 404, 403 or "Not yet implemented". A 127.0.0.1 bind is never given a port already taken on 127.0.0.1, and as the more specific bind it receives the traffic. A vitest setup file now supplies that host when a test server names none, and a guard test fails if it stops applying. With a host, Node resolves it before binding, so the nine ws test servers that read their port right after construction now wait for 'listening'. The T8 membership load test gets a 15s budget instead of the 5s default. Two full-suite loops in parallel: 8 failures in 60 runs before, 0 after. Binding everything to :: instead (tried first) still failed 1 in 30, against sockets outside the suite. Closes #59 Signed-off-by: Diego Resendez --- test/health.test.ts | 1 + test/http.test.ts | 4 ++-- test/listener-boundary.test.ts | 2 +- test/mesh/envelope.test.ts | 1 + test/mesh/heartbeat.test.ts | 11 ++++++----- test/mesh/link.test.ts | 28 ++++++++++++++++------------ test/mesh/membership.test.ts | 10 ++++++---- test/reserved-paths.test.ts | 12 +++++++----- test/router-parity/owner.test.ts | 2 +- test/setup/loopback.test.ts | 20 ++++++++++++++++++++ test/setup/loopback.ts | 27 +++++++++++++++++++++++++++ vitest.config.ts | 2 ++ 12 files changed, 90 insertions(+), 30 deletions(-) create mode 100644 test/setup/loopback.test.ts create mode 100644 test/setup/loopback.ts diff --git a/test/health.test.ts b/test/health.test.ts index 458c688..8b103e6 100644 --- a/test/health.test.ts +++ b/test/health.test.ts @@ -263,6 +263,7 @@ describe('CARD-17: health option validation and reserved paths', () => { it('a teapot route at /__ready__ fails the teacup splice while health is on', async () => { const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) wss.on('connection', (ws) => { ws.on('message', (data) => { if (decode(data.toString()).type === 'hello') { diff --git a/test/http.test.ts b/test/http.test.ts index 66ea7bc..f744448 100644 --- a/test/http.test.ts +++ b/test/http.test.ts @@ -187,7 +187,7 @@ describe('request hardening', () => { limits: { maxConnections: 1 }, }); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + await new Promise((resolve) => server.listen(0, resolve)); const address = server.address(); if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port'); @@ -330,7 +330,7 @@ describe('request hardening', () => { { limits: { maxConcurrentRequests: 1 } }, ); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + await new Promise((resolve) => server.listen(0, resolve)); const address = server.address(); if (!address || typeof address === 'string') throw new Error('server did not bind to a TCP port'); diff --git a/test/listener-boundary.test.ts b/test/listener-boundary.test.ts index caa015b..cc3a527 100644 --- a/test/listener-boundary.test.ts +++ b/test/listener-boundary.test.ts @@ -55,7 +55,7 @@ const servers: http.Server[] = []; async function start(routes: RouteDef[], opts: HttpOptions = {}, bus?: Bus): Promise { const server = createHttpServer([ok, ...routes], [], bus, undefined, opts); servers.push(server); - server.listen(0, '127.0.0.1'); + server.listen(0); // 127.0.0.1, via test/setup/loopback.ts (#59) await once(server, 'listening'); return (server.address() as net.AddressInfo).port; } diff --git a/test/mesh/envelope.test.ts b/test/mesh/envelope.test.ts index af94004..814dc04 100644 --- a/test/mesh/envelope.test.ts +++ b/test/mesh/envelope.test.ts @@ -97,6 +97,7 @@ describe('envelopeFrom', () => { describe('mesh rpc errors', () => { it('reports the token that failed, not the wire id', async () => { const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) wss.on('connection', (ws) => { let authed = false; ws.on('message', (data) => { diff --git a/test/mesh/heartbeat.test.ts b/test/mesh/heartbeat.test.ts index 2242f96..013ea83 100644 --- a/test/mesh/heartbeat.test.ts +++ b/test/mesh/heartbeat.test.ts @@ -11,8 +11,9 @@ const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} * half-open link: TCP still looks alive, the peer is not. Without a heartbeat a teacup only * finds out when a request pays the full rpc timeout. */ -function startTeapot(opts: { answerPings: boolean }) { +async function startTeapot(opts: { answerPings: boolean }) { const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) const seen: string[] = []; wss.on('connection', (ws) => { @@ -34,7 +35,7 @@ function startTeapot(opts: { answerPings: boolean }) { describe('mesh heartbeat', () => { it('pings the teapot and keeps the link alive while it pongs', async () => { - const t = startTeapot({ answerPings: true }); + const t = await startTeapot({ answerPings: true }); const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 }); await new Promise((r) => setTimeout(r, 120)); @@ -48,7 +49,7 @@ describe('mesh heartbeat', () => { it('closes the link when the teapot stops answering pings', async () => { // the half-open case: the socket never errors, the peer just stops talking - const t = startTeapot({ answerPings: false }); + const t = await startTeapot({ answerPings: false }); const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, timeoutMs: 10_000 }); await new Promise((r) => setTimeout(r, 200)); @@ -60,7 +61,7 @@ describe('mesh heartbeat', () => { }); it('emits mesh:disconnect when the heartbeat gives up', async () => { - const t = startTeapot({ answerPings: false }); + const t = await startTeapot({ answerPings: false }); const seen: string[] = []; const bus = { emit: (e: string, p: any) => seen.push(`${e}:${p.name}`), on: () => () => {} } as any; const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30, bus }); @@ -74,7 +75,7 @@ describe('mesh heartbeat', () => { }); it('does not ping before the handshake completes', async () => { - const t = startTeapot({ answerPings: true }); + const t = await startTeapot({ answerPings: true }); const link = await connectLink({ url: t.url, secret: 'good', heartbeatMs: 30 }); // hello must be first on the wire: an unauthenticated peer has no business pinging diff --git a/test/mesh/link.test.ts b/test/mesh/link.test.ts index e7e355f..24e1ca5 100644 --- a/test/mesh/link.test.ts +++ b/test/mesh/link.test.ts @@ -9,8 +9,9 @@ const V = MESH_PROTOCOL_VERSION; const env = { method: 'GET', params: {}, query: {}, body: undefined, headers: {} }; // teapot that validates secret 'good', returns a manifest, answers scope rpc (boom -> error) -function startTeapot(secret = 'good') { +async function startTeapot(secret = 'good') { const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) const names: string[] = []; // every rpc-req name received, in order wss.on('connection', (ws) => { let authed = false; @@ -33,8 +34,9 @@ function startTeapot(secret = 'good') { } // teapot that completes the handshake but NEVER answers rpc-req (for timeout) -function startSilentTeapot(secret = 'good') { +async function startSilentTeapot(secret = 'good') { const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) wss.on('connection', (ws) => { ws.on('message', (d) => { const f = decode(d.toString()); @@ -47,8 +49,9 @@ function startSilentTeapot(secret = 'good') { } // teapot running a future protocol: handshakes, but answers with a skewed manifest -function startSkewedTeapot() { +async function startSkewedTeapot() { const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) wss.on('connection', (ws) => { ws.on('message', () => ws.send(encode({ type: 'manifest', v: V + 1, steps: [], routes: [] } as any))); }); @@ -67,7 +70,7 @@ if (platform) CTORS.push(['the platform global WebSocket', platform]); describe('WebSocket client implementations', () => { it.each(CTORS)('handshakes and serves RPC over %s', async (_label, Ctor) => { - const t = startTeapot(); + const t = await startTeapot(); const link = await connectLink({ url: t.url, secret: 'good', Ctor }); expect(link.manifest.steps).toEqual(['auth']); @@ -85,6 +88,7 @@ describe('connectLink', () => { it('sends its protocol version in the hello', async () => { const seen: any[] = []; const wss = new WebSocketServer({ port: 0 }); + await new Promise((resolve) => wss.once('listening', resolve)); // bound before reading its port (#59) wss.on('connection', (ws) => ws.on('message', (d) => { seen.push(decode(d.toString())); @@ -99,40 +103,40 @@ describe('connectLink', () => { }); it('refuses a teapot on a different protocol version', async () => { - const t = startSkewedTeapot(); + const t = await startSkewedTeapot(); await expect(connectLink({ url: t.url, secret: 'good', timeoutMs: 500 })).rejects.toThrow(/version/i); t.close(); }); it('handshakes and exposes the manifest', async () => { - const t = startTeapot(); + const t = await startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); expect(link.manifest.steps).toEqual(['auth']); link.close(); t.close(); }); it('rpc resolves a result by id', async () => { - const t = startTeapot(); + const t = await startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); expect(await link.rpc('scope', 'auth', env)).toEqual({ got: 'auth' }); link.close(); t.close(); }); it('rpc rejects with an HttpError carrying the remote status', async () => { - const t = startTeapot(); + const t = await startTeapot(); const link = await connectLink({ url: t.url, secret: 'good' }); await expect(link.rpc('scope', 'boom', env)).rejects.toMatchObject({ status: 403, message: 'denied' }); link.close(); t.close(); }); it('rejects connect on bad secret', async () => { - const t = startTeapot(); + const t = await startTeapot(); await expect(connectLink({ url: t.url, secret: 'wrong', timeoutMs: 500 })).rejects.toThrow(); t.close(); }); it('times out an rpc when the teapot never answers', async () => { - const t = startSilentTeapot(); + const t = await startSilentTeapot(); const link = await connectLink({ url: t.url, secret: 'good', timeoutMs: 150 }); await expect(link.rpc('scope', 'whatever', env)).rejects.toThrow(/timeout/i); link.close(); t.close(); @@ -150,7 +154,7 @@ describe('connectLink', () => { const BackedCtor = Backed as unknown as SocketCtor; it('holds an rpc-req while the link is backed up, and sends it once it drains (#41)', async () => { - const t = startTeapot(); + const t = await startTeapot(); const link = await connectLink({ url: t.url, secret: 'good', Ctor: BackedCtor }); stalled = true; let settled = false; @@ -163,7 +167,7 @@ describe('connectLink', () => { }); it('times out an rpc still waiting for room, and never sends it (#41)', async () => { - const t = startTeapot(); + const t = await startTeapot(); const link = await connectLink({ url: t.url, secret: 'good', timeoutMs: 100, Ctor: BackedCtor }); stalled = true; await expect(link.rpc('scope', 'auth', env)).rejects.toMatchObject({ status: 504 }); diff --git a/test/mesh/membership.test.ts b/test/mesh/membership.test.ts index a6b8765..8045942 100644 --- a/test/mesh/membership.test.ts +++ b/test/mesh/membership.test.ts @@ -85,7 +85,7 @@ const FAST = { initialDelayMs: 20, maxDelayMs: 60 }; /** A port nothing listens on, that a teapot can take later. */ async function freePort(): Promise { const server = net.createServer(); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + await new Promise((resolve) => server.listen(0, resolve)); const { port } = server.address() as AddressInfo; await new Promise((resolve) => server.close(() => resolve())); return port; @@ -149,7 +149,7 @@ function teacup(ports: number[], mesh: Partial = {}, extra: { health open.unshift(app); // closed before the teapots const next = (name: string) => new Promise((resolve, reject) => { - const timer = setTimeout(() => reject(new Error(`no ${name} within 5s`)), 5000); + const timer = setTimeout(() => reject(new Error(`no ${name} within 12s`)), 12_000); waiting.set(name, [ ...(waiting.get(name) ?? []), (e) => { @@ -185,7 +185,7 @@ async function rawTeapotOn( routes: RouteEntry[], answer: unknown, ): Promise<{ close: () => Promise }> { - const wss = new WebSocketServer({ port, host: '127.0.0.1' }); + const wss = new WebSocketServer({ port }); wss.on('connection', (ws) => { ws.on('message', (data) => { const frame = decode(data.toString()); @@ -367,7 +367,9 @@ describe('mesh: remote routes follow teapot membership (CARD-19, D15)', () => { expect(statuses).toContain(404); expect(statuses).toContain(200); expect((await get(cup.app, '/api/remote/ping')).status).toBe(200); - }); + // 1 000 requests through the mesh is a load test by design; the default 5s ran out once in 30 + // full-suite runs under two parallel suites (#59). + }, 15_000); it('with reconnect: false a teapot absent at boot is not retried (no backoff to retry with)', async () => { const port = await freePort(); diff --git a/test/reserved-paths.test.ts b/test/reserved-paths.test.ts index 5853e44..23e38da 100644 --- a/test/reserved-paths.test.ts +++ b/test/reserved-paths.test.ts @@ -207,9 +207,11 @@ describe('CARD-21 T7: a teapot that advertises a route on the reserved path', () afterEach(() => wss?.close()); /** A hand-rolled teapot: a real one refuses such a route at its own boot, so only the wire can carry it. */ - function foreignTeapot(pattern: string): string { - wss = new WebSocketServer({ port: 0 }); - wss.on('connection', (ws) => { + async function foreignTeapot(pattern: string): Promise { + const server = new WebSocketServer({ port: 0 }); + wss = server; + await new Promise((resolve) => server.once('listening', resolve)); // bound before reading its port (#59) + server.on('connection', (ws) => { ws.on('message', (data) => { const frame = decode(data.toString()); if (frame.type === 'hello') { @@ -224,11 +226,11 @@ describe('CARD-21 T7: a teapot that advertises a route on the reserved path', () } }); }); - return `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`; + return `ws://127.0.0.1:${(server.address() as AddressInfo).port}/__mesh__/control`; } it('the teacup splice fails and names the teapot', async () => { - const url = foreignTeapot('/__mesh__/:x'); + const url = await foreignTeapot('/__mesh__/:x'); const teacup = createApp({ modules: [moduleWith([[Get, '/ok']])], experimental: true, diff --git a/test/router-parity/owner.test.ts b/test/router-parity/owner.test.ts index 367c41f..d6870ac 100644 --- a/test/router-parity/owner.test.ts +++ b/test/router-parity/owner.test.ts @@ -55,7 +55,7 @@ const quiet: Logger = { debug: () => {}, info: () => {}, warn: () => {}, error: /** A port nothing is listening on, that a teapot can take later. */ async function freePort(): Promise { const server = net.createServer(); - await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + await new Promise((resolve) => server.listen(0, resolve)); const { port } = server.address() as AddressInfo; await new Promise((resolve) => server.close(() => resolve())); return port; diff --git a/test/setup/loopback.test.ts b/test/setup/loopback.test.ts new file mode 100644 index 0000000..72a3161 --- /dev/null +++ b/test/setup/loopback.test.ts @@ -0,0 +1,20 @@ +// Guards test/setup/loopback.ts: if it stops applying, the port collisions behind #59 come back. +import { it, expect } from 'vitest'; +import { WebSocketServer } from 'ws'; +import { createApp, Module } from '../../src/index'; + +@Module({ mountpoint: '/' }) +class M {} + +it('test servers listen on 127.0.0.1 when no host is given', async () => { + const server = await createApp({ modules: [M] }).listen(0); + const wss = new WebSocketServer({ port: 0 }); + try { + await new Promise((resolve) => wss.once('listening', resolve)); + expect((server.address() as { address: string }).address).toBe('127.0.0.1'); + expect((wss.address() as { address: string }).address).toBe('127.0.0.1'); + } finally { + server.close(); + wss.close(); + } +}); diff --git a/test/setup/loopback.ts b/test/setup/loopback.ts new file mode 100644 index 0000000..3fbf5b9 --- /dev/null +++ b/test/setup/loopback.ts @@ -0,0 +1,27 @@ +// Test servers listen on 127.0.0.1 unless a test names a host (#59). +// +// Every test connects to 127.0.0.1, but `listen(0)` with no host binds `::`. On macOS a `::` bind and a +// `127.0.0.1` bind are different sockets, so the OS can hand a test server on `::` a port that another +// process, or another test file running in parallel, already holds on 127.0.0.1, and the test's client +// reaches that one instead: a fresh server "answered" 404, 403 or "Not yet implemented". A 127.0.0.1 +// bind is never given a port already taken on 127.0.0.1, and as the more specific bind it gets the +// traffic. A host makes Node resolve it before binding, so `address()` is only valid after 'listening': +// test helpers wait for it. Production code is untouched; this file is only in vitest's setupFiles. +import net from 'node:net'; + +const LOOPBACK = '127.0.0.1'; +const listen = net.Server.prototype.listen; + +net.Server.prototype.listen = function loopbackListen(this: net.Server, ...args: unknown[]) { + const [first, second] = args; + + if (typeof first === 'number') { + // listen(port), listen(port, cb), and `ws`'s listen(port, null, null, cb) + if (second == null) args.length > 1 ? (args[1] = LOOPBACK) : args.push(LOOPBACK); + else if (typeof second === 'function') args.splice(1, 0, LOOPBACK); + } else if (first !== null && typeof first === 'object' && !('path' in first) && !(first as { host?: unknown }).host) { + args[0] = { ...first, host: LOOPBACK }; + } + + return listen.apply(this, args as Parameters); +} as typeof listen; diff --git a/vitest.config.ts b/vitest.config.ts index 32a48dc..fb06e6f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -8,5 +8,7 @@ export default defineConfig({ // test/deno/** holds Deno.test files run separately via `npm run test:deno`; // they use `npm:`/`jsr:` specifiers vitest can't resolve. exclude: [...configDefaults.exclude, 'test/deno/**', 'test/bun/**', 'test/edge/**'], + // Test servers bind 127.0.0.1, so no other socket can share their port (#59). + setupFiles: ['test/setup/loopback.ts'], }, }); From fbbabe390144bf7173bac5d33e1871cba3f30ac6 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 00:37:14 -0600 Subject: [PATCH 21/41] ci(stage): stage stable versions too stage.yml refused any version without a pre-release suffix, because staging unpublishes and republishes the version it stages. That left the first stable release, the one most worth trying first, unable to go through Verdaccio. Verdaccio is a private registry used only to try a release before the public one, and nothing depends on a version there staying put, so overwriting a stable number costs nothing. Drop the guard. Closes #72 Signed-off-by: Diego Resendez --- .github/workflows/stage.yml | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) diff --git a/.github/workflows/stage.yml b/.github/workflows/stage.yml index 297746b..91062e6 100644 --- a/.github/workflows/stage.yml +++ b/.github/workflows/stage.yml @@ -32,20 +32,14 @@ jobs: continue-on-error: true - name: Validate release candidate run: npm run prepublishOnly - - name: Publish prerelease to Verdaccio + - name: Publish to Verdaccio env: NODE_AUTH_TOKEN: ${{ secrets.NPM_AUTH }} run: | npm config set //npm.svc.zoit.services/:_authToken "$NODE_AUTH_TOKEN" VER=$(node -p "require('./package.json').version") - # Staging overwrites the version it publishes, and a stable number that changes - # under an internal consumer is worse than no staging at all. This will need - # revisiting at the first stable release, which is exactly the one most worth - # staging: the answer is probably to stage it under a suffixed version rather - # than to drop the guard. - case "$VER" in - *-*) ;; - *) echo "Refusing to stage non-prerelease version: $VER" >&2; exit 1 ;; - esac + # Stable versions are staged too (#72). Verdaccio is a private staging registry used + # only to try a release before the public one, with no consumers that depend on a + # version staying put, so overwriting a stable number there costs nothing. npm unpublish "@green-tea/core@$VER" --registry https://npm.svc.zoit.services --force 2>/dev/null || true npm publish --ignore-scripts --registry https://npm.svc.zoit.services --tag stg From c35b9a45a267cdf8706e8d861367d7cbb7b90b40 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 00:37:44 -0600 Subject: [PATCH 22/41] docs: only the year breaks after stable The README let a breaking change ship in any monthly release after a two-release deprecation. Under CalVer YY.M.PATCH npm reads the year as the major version, so the default ^26.12.0 range accepts every 26.x month, removals included. After stable, breaking changes ship only in the first release of a year (YY.1.0). A deprecated API still works for at least two monthly releases, then waits for the next YY.1.0. A security fix that cannot be made without breaking an API is the one exception. CONTRIBUTING says the same for pull requests. Closes #75 Signed-off-by: Diego Resendez --- CONTRIBUTING.md | 2 +- README.md | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3159bed..7888767 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -151,7 +151,7 @@ Bun and the edge in its `runtimes` job. - Write tests for new behavior (TDD welcome). We use Vitest. - `complexity:check` caps the cognitive complexity of every function in `src/`. What it measures is how much you have to hold in your head to follow a function from top to bottom, and it charges nesting more heavily than branching: a condition inside a closure inside a function costs several times what the same condition costs at the top level. Going over the threshold is not a verdict on your code — it means one function has grown to ask too much of whoever reads it next. The fix is nearly always to lift a nested closure out to module scope, where its branches are charged once instead of three times over. Raising `COMPLEXITY_MAX` is not the fix, even though the script suggests it. - Keep runtime dependencies at zero beyond `reflect-metadata`. -- **The public API is frozen from RC.1, and `api/` is its record.** `api/*.api.md` holds one report per export-map entry, and `npm run api:check` fails when the build declares something they do not. If you meant to change the API, run `npm run build && npm run api` and commit the regenerated report with your change, so the reviewer reads the API change as a diff rather than finding it after release. From RC.1 to stable, releases are fixes only, so a pull request that changes a report needs the owner to reopen the freeze first. The policy is in the README under [API stability](./README.md#api-stability). The check also fails when a public signature names a type its entry point does not export, because a user would have no way to name it. Mesh is alpha, `@experimental` and outside the freeze. Mesh adapts to the stable API and never changes it. Its own surface is the exports tagged `@experimental`, the shape of `MeshConfig` behind the `mesh` option, and the `mesh:*` lifecycle events. A mesh change may alter those and nothing else. It cannot add a `createApp` option, an `App` method or a decorator, and it cannot change a stable type. If mesh needs something the stable API does not offer, it builds on what is there. It is still in the report, so a reviewer can confirm a mesh change touched only mesh. +- **The public API is frozen from RC.1, and `api/` is its record.** `api/*.api.md` holds one report per export-map entry, and `npm run api:check` fails when the build declares something they do not. If you meant to change the API, run `npm run build && npm run api` and commit the regenerated report with your change, so the reviewer reads the API change as a diff rather than finding it after release. From RC.1 to stable, releases are fixes only, so a pull request that changes a report needs the owner to reopen the freeze first. The policy is in the README under [API stability](./README.md#api-stability). After stable, only the year breaks: a pull request that removes or breaks a public API targets the next `YY.1.0` and waits for it, however long that is, unless it is a security fix that cannot be made any other way. The check also fails when a public signature names a type its entry point does not export, because a user would have no way to name it. Mesh is alpha, `@experimental` and outside the freeze. Mesh adapts to the stable API and never changes it. Its own surface is the exports tagged `@experimental`, the shape of `MeshConfig` behind the `mesh` option, and the `mesh:*` lifecycle events. A mesh change may alter those and nothing else. It cannot add a `createApp` option, an `App` method or a decorator, and it cannot change a stable type. If mesh needs something the stable API does not offer, it builds on what is there. It is still in the report, so a reviewer can confirm a mesh change touched only mesh. - A new option or method on a public interface has to change that interface too. An implementation that grows a parameter without `src/app/types.ts` growing it as well is unreachable for anyone consuming the package. - New public API needs a doc note in `README.md`, **and a companion pull request to [green-tea-docs](https://github.com/Expressive-Tea/green-tea-docs) updating the page that documents it.** It is a second pull request because a pull request cannot span two repositories — link the two to each other so a reviewer can see both. The documentation site used to be built by this repository's CI, so a stale page broke the build; it is now a separate repository that imports nothing from here, and nothing fails when the two disagree. Issue #18 happened when the two still lived together, which is the reason this line exists rather than a hope. If you would rather not write the docs change, say so in your pull request and a maintainer will — an unmentioned API change is the failure this line exists to prevent, not an unwritten page. - If your change only works on one runtime, say so in the pull request. green-tea runs on Node, Deno, Bun and the edge, and behavior that quietly differs between them is treated as a bug — an explicit "not available here" is fine, silence is not. diff --git a/README.md b/README.md index 8177aed..239ebcc 100644 --- a/README.md +++ b/README.md @@ -365,7 +365,9 @@ consumer would have received. ## Versioning -green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. A version tells you *when* it shipped, not how many breaking changes preceded it — those are always called out in the [CHANGELOG](./CHANGELOG.md). +green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. + +**After the first stable release, only the year breaks.** A release inside a year (`26.12.0`, `27.3.1`) never removes or breaks a public API, so the range npm writes by default, `^26.12.0`, is safe to take. Breaking changes ship only in the first release of a year (`27.1.0`, `28.1.0`), and that is the only kind of release you have to read before upgrading. npm reads the year as the major version, so a `^` range never crosses into it on its own. Every breaking change is called out under `### Breaking` in the [CHANGELOG](./CHANGELOG.md). **Before the first stable release**, versions carry a pre-release suffix on the calendar version, and each one publishes under the npm dist-tag of its channel: release candidates (`-rc.N`, e.g. `26.11.0-rc.1`) under `rc`, betas (`-beta.N`) under `beta`. The `beta` tag stays on the last beta, `26.9.0-beta.2`. Until a stable release exists there is nothing else to install, so `latest` follows the newest prerelease too — today `npm install @green-tea/core` and `@green-tea/core@rc` resolve to the same version. Install with the explicit `@rc` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. @@ -374,7 +376,7 @@ green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first **From the first release candidate (RC.1) the public API is frozen.** The public API is everything exported from the four entry points: `@green-tea/core`, `/deno`, `/bun` and `/edge`. - **RC.1 to stable: fixes only.** No release in that window adds, removes, renames or narrows a public API. It also deprecates nothing. If a fix needs an API change, the freeze is reopened, and the change is called out under `### Breaking` in the CHANGELOG. -- **After stable, deprecations come before removals.** A deprecated API keeps working for at least two monthly releases. It carries JSDoc `@deprecated` naming its replacement. Where it has a runtime path, it warns once per process through `app.logger`, never `console`. It is removed only in a release whose CHANGELOG lists the removal under `### Breaking`. +- **After stable, deprecations come before removals, and removals wait for the year.** A deprecated API keeps working for at least two monthly releases. It carries JSDoc `@deprecated` naming its replacement. Where it has a runtime path, it warns once per process through `app.logger`, never `console`. It is removed only in the first release of a year (`YY.1.0`), whose CHANGELOG lists the removal under `### Breaking`. So something deprecated in `26.4.0` goes in `27.1.0`, and something deprecated in `26.12.0`, too late for two monthly releases before January, goes in `28.1.0`. The one exception is a security fix that cannot be made without breaking an API: it ships when it is ready, under both `### Security` and `### Breaking`. - **Every API change shows up in review.** [`api/`](./api) holds the committed API report for each entry point, and CI fails when the build no longer matches it. A deliberate change regenerates the report in the same pull request. - **Mesh is alpha and outside the promise.** It is `@experimental` and gated behind `createApp({ experimental: true })`, so it may change in any release. Mesh adapts to the stable API and never changes it. Its own surface is the exports tagged `@experimental`, the shape of `MeshConfig` behind the `mesh` option, and the `mesh:*` lifecycle events. A mesh change may alter those and nothing else. It cannot add a `createApp` option, an `App` method or a decorator, and it cannot change a stable type. If mesh needs something the stable API does not offer, it builds on what is there. Its exports still appear in the reports, so those changes still show up in review. From 9d55a9f5b0a5d5570aa3f6dedd9e27db67d31b86 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 00:37:58 -0600 Subject: [PATCH 23/41] docs(security): publish the support table SECURITY.md promised a real table once stable shipped. The latest monthly release gets bug and security fixes; the one before it gets security fixes for three months after the latest ships, as patch releases; nothing older is supported, and features are never backported. Pre-releases: only the latest. Kept small on purpose, for a one-person project. The README's Versioning section links it. Closes #74 Signed-off-by: Diego Resendez --- README.md | 2 +- SECURITY.md | 17 +++++++++++++++-- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 239ebcc..99004c3 100644 --- a/README.md +++ b/README.md @@ -367,7 +367,7 @@ consumer would have received. green-tea uses **calendar versioning**: `YY.M.PATCH` (e.g. `26.8.0` = the first release cut in August 2026, patch 0). The month is **not** zero-padded — npm treats versions as semver, which forbids leading zeros. -**After the first stable release, only the year breaks.** A release inside a year (`26.12.0`, `27.3.1`) never removes or breaks a public API, so the range npm writes by default, `^26.12.0`, is safe to take. Breaking changes ship only in the first release of a year (`27.1.0`, `28.1.0`), and that is the only kind of release you have to read before upgrading. npm reads the year as the major version, so a `^` range never crosses into it on its own. Every breaking change is called out under `### Breaking` in the [CHANGELOG](./CHANGELOG.md). +**After the first stable release, only the year breaks.** A release inside a year (`26.12.0`, `27.3.1`) never removes or breaks a public API, so the range npm writes by default, `^26.12.0`, is safe to take. Breaking changes ship only in the first release of a year (`27.1.0`, `28.1.0`), and that is the only kind of release you have to read before upgrading. npm reads the year as the major version, so a `^` range never crosses into it on its own. Every breaking change is called out under `### Breaking` in the [CHANGELOG](./CHANGELOG.md). Which releases get fixes, and for how long, is in [SECURITY.md](./SECURITY.md#supported-versions). **Before the first stable release**, versions carry a pre-release suffix on the calendar version, and each one publishes under the npm dist-tag of its channel: release candidates (`-rc.N`, e.g. `26.11.0-rc.1`) under `rc`, betas (`-beta.N`) under `beta`. The `beta` tag stays on the last beta, `26.9.0-beta.2`. Until a stable release exists there is nothing else to install, so `latest` follows the newest prerelease too — today `npm install @green-tea/core` and `@green-tea/core@rc` resolve to the same version. Install with the explicit `@rc` tag anyway: the day a stable ships, `latest` moves to it and your installs stay on the channel you meant. diff --git a/SECURITY.md b/SECURITY.md index c6ed18e..1109ce7 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -48,8 +48,21 @@ out after the work. ## Supported versions -While the package is in beta, only the most recent `26.x.y-beta.N` receives fixes. There is no -backport channel yet; when the first stable ships, this section gets the real table. +| Version | Bug fixes | Security fixes | +| --- | --- | --- | +| The latest monthly release (`YY.M.x`) | Yes | Yes | +| The monthly release before it | No | For 3 months after the latest one ships | +| Anything older | No | No | +| Pre-releases (`-beta.N`, `-rc.N`) | Only the latest, until the stable release that follows it | Same | + +A fix lands in the latest release first. A security fix is also backported, as a patch release of +the previous month's line, while that line is inside its three months. Features are never +backported. This is deliberately small: the project is one person, and a promise that only holds +in a good month is worse than a short one that holds. There is no long-term support line. + +Breaking changes ship only in the first release of a year (see +[Versioning](./README.md#versioning)), so moving to the latest release within a year is meant to be +safe, and is the expected way to stay supported. ## Scope From a687aca44445ca2a90fba004b75529defbb1744c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 01:28:10 -0600 Subject: [PATCH 24/41] perf(params): resolve decorator keys without a closure per call The own-key fix (GHSA-g86h-3r98-qm66) added a second closure to resolveOne, which runs for every decorated argument of every request. An A/B against develop measured param at -3.4% and 'param, 50 routes' at -6.3% with non-overlapping ranges. Move the lookup into a module-level ownKey(values, key, lowerCase), so resolveOne allocates nothing per call. Re-measured with 5 rounds: param +0.9%, 'param, 50 routes' +2.5%, 'param, 200 routes' -0.4%, validate -1.3%, all overlapping; an A/A run on develop spans -1.3% to +0.6%. Measured on Node only; Deno and Bun share the code but were not run. Signed-off-by: Diego Resendez --- src/params.ts | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/src/params.ts b/src/params.ts index ce3f3b1..d2da15d 100644 --- a/src/params.ts +++ b/src/params.ts @@ -140,6 +140,17 @@ export async function resolveArgs(specs: ArgSpec[], context: Context): Promise, key: string, lowerCase: boolean): unknown { + const name = lowerCase ? key.toLowerCase() : key; + return hasOwn.call(values, name) ? values[name] : undefined; +} + function resolveOne(spec: ArgSpec, context: Context): unknown { if (spec.source === 'ctx') return context; // `cookies` is a seed token like `headers`, but parsed on demand rather than seeded on every request. @@ -149,20 +160,16 @@ function resolveOne(spec: ArgSpec, context: Context): unknown { const bag = spec.source === 'cookies' ? cookiesOf(context) : context[spec.source]; if (typeof bag !== 'object' || bag === null) return bag; // can't pick from a non-object; return as-is const values = bag as Record; - // Every adapter stores header names lower-cased, so `@header('Content-Type')` looks up - // `content-type` (GitHub #37). A picked bag keeps the names as the handler wrote them. - // Own keys only: `@query('constructor')` on a request without that key is `undefined`, not - // `Object.prototype.constructor` (GHSA-g86h-3r98-qm66). - const own = (key: string) => (hasOwn.call(values, key) ? values[key] : undefined); - const at = spec.source === 'headers' ? (key: string) => own(key.toLowerCase()) : own; + const lowerCase = spec.source === 'headers'; + // A picked bag keeps the names as the handler wrote them. if (spec.keys) { const picked: Record = {}; - for (const key of spec.keys) picked[key] = at(key); + for (const key of spec.keys) picked[key] = ownKey(values, key, lowerCase); return picked; } - if (spec.key !== undefined) return at(spec.key); + if (spec.key !== undefined) return ownKey(values, spec.key, lowerCase); return values; } From 31e287abc797a5b7ccd2035d8dd4c7578c37073c Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 01:36:54 -0600 Subject: [PATCH 25/41] fix(bus): log a failing listener once through the app logger Bus.emit swallowed a listener's throw or rejection without a trace, so a broken metrics or logger plugin went silent and nothing said why. createApp now registers a reporter for the bus it builds, and the first failure of each listener is warned through app.logger with the event name; later failures of the same listener stay quiet. The reporter lives in a WeakMap inside bus.ts, outside the public barrel, so the exported Bus type and the API report are unchanged. The success path of emit is untouched. Closes #77 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 ++ bench/compare-results.json | 109 +++++++++++++++++++++++++++++++++++++ src/app/index.ts | 8 ++- src/bus.ts | 36 +++++++++++- test/bus.test.ts | 47 +++++++++++++++- 5 files changed, 200 insertions(+), 5 deletions(-) create mode 100644 bench/compare-results.json diff --git a/CHANGELOG.md b/CHANGELOG.md index a1ac373..ca7d3b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,6 +113,11 @@ npm treats versions as semver and semver forbids leading zeros. unrelated step that threw broke every export. A call now runs the exported step's own closure of providers and steps, sliced once at boot like a route's. Mesh is `@experimental`; no API change. +- **A bus listener that throws is logged once** (#77). `Bus.emit` isolated a failing listener without + a word, so a broken metrics or logger plugin produced nothing and gave no signal. The app's + `logger` now warns the first time a listener throws or rejects, naming the event; that listener's + later failures stay quiet. The `Bus` type is unchanged. + - **An async bus listener that rejects no longer exits the Node process** (#70). `Bus.emit` isolated a listener that threw, but an `async` listener fails by rejecting, and that rejection went unhandled, so a plugin's `on('request:end', async () => { throw … })` killed the process on the diff --git a/bench/compare-results.json b/bench/compare-results.json new file mode 100644 index 0000000..94d0961 --- /dev/null +++ b/bench/compare-results.json @@ -0,0 +1,109 @@ +{ + "rounds": 5, + "duration": 6, + "conns": 100, + "rows": [ + { + "name": "param", + "base": 91040, + "head": 91882.67, + "delta": 0.925604130052722, + "separated": false, + "samples": { + "base": [ + 91424, + 90837.34, + 90250.67, + 91040, + 91861.34 + ], + "head": [ + 91498.67, + 91904, + 93749.34, + 91050.67, + 91882.67 + ] + } + }, + { + "name": "validate (POST)", + "base": 71210.67, + "head": 70272, + "delta": -1.3181592028273266, + "separated": false, + "samples": { + "base": [ + 71008, + 70933.34, + 71210.67, + 71274.67, + 71605.34 + ], + "head": [ + 69962.67, + 71989.34, + 71765.34, + 70272, + 70090.67 + ] + } + }, + { + "name": "param, 50 routes", + "base": 90005.34, + "head": 92256, + "delta": 2.5005849652920635, + "separated": false, + "samples": { + "base": [ + 90005.34, + 91210.67, + 89856, + 92949.34, + 89781.34 + ], + "head": [ + 91904, + 92501.34, + 92256, + 92832, + 91808 + ] + } + }, + { + "name": "param, 200 routes", + "base": 91349.34, + "head": 90944, + "delta": -0.44372515444555655, + "separated": false, + "samples": { + "base": [ + 89866.67, + 91445.34, + 91157.34, + 91349.34, + 91434.67 + ], + "head": [ + 91221.34, + 87104, + 90634.67, + 90944, + 91818.67 + ] + } + } + ], + "cors": { + "base": { + "get": 1, + "preflight": 1 + }, + "head": { + "get": 1, + "preflight": 1 + } + } +} \ No newline at end of file diff --git a/src/app/index.ts b/src/app/index.ts index a03f5e1..69fc5c6 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1,5 +1,5 @@ import type http from 'http'; -import { Bus, type Events } from '../bus'; +import { Bus, reportListenerErrors, type Events } from '../bus'; import { createDefaultLogger, logRequests, type Logger } from '../logger'; import { Container } from '../container'; import { topoSort, topoLevels, subgraphFor, GraphNode, nearest } from '../graph'; @@ -316,6 +316,12 @@ export function createApp(opts: AppOptions): App { const bus = new Bus(); const logger = opts.logger ?? createDefaultLogger(); + reportListenerErrors(bus, (event, error) => + logger.warn(`a listener on '${event}' threw and was skipped; further failures of that listener are not logged`, { + event, + err: error instanceof Error ? error.message : String(error), + }), + ); assertTeapotTransport(opts.mesh, logger); if (opts.logRequests) logRequests(bus, logger); const container = new Container(); diff --git a/src/bus.ts b/src/bus.ts index 9758a1a..c89691a 100644 --- a/src/bus.ts +++ b/src/bus.ts @@ -162,6 +162,20 @@ export interface Events { on: Bus['on']; } +/** + * Where a bus reports a listener that failed. Kept outside the class, so the exported `Bus` type is + * unchanged under the API freeze; `createApp` registers its logger here for the bus it builds. + */ +const listenerErrorReporters = new WeakMap void>(); + +/** Listeners already reported, so a broken one logs once rather than on every event (#77). */ +const reportedListeners = new WeakSet<(p: EventPayload) => void>(); + +/** Internal: route listener failures on `bus` to `report`, once per listener. Not in the public barrel. */ +export function reportListenerErrors(bus: Bus, report: (event: LifecycleEvent, error: unknown) => void): void { + listenerErrorReporters.set(bus, report); +} + /** In-process pub/sub for framework lifecycle events; observer failures are swallowed so they never break the pipeline. */ export class Bus { private readonly listeners = new Map void>>(); @@ -189,6 +203,19 @@ export class Bus { return listenerSet !== undefined && listenerSet.size > 0; } + private reportFailure(event: LifecycleEvent, listener: (p: EventPayload) => void, error: unknown): void { + const report = listenerErrorReporters.get(this); + if (!report || reportedListeners.has(listener)) return; + + reportedListeners.add(listener); + + try { + report(event, error); + } catch { + /* a broken logger must not break the pipeline either */ + } + } + /** Dispatch `payload` to every listener of `event`; a throwing listener is isolated and does not affect the others. */ emit(event: LifecycleEvent, payload: EventPayload): void { for (const listener of this.listeners.get(event) ?? []) { @@ -198,10 +225,13 @@ export class Bus { const result: unknown = listener(payload); if (typeof (result as PromiseLike | undefined)?.then === 'function') { - (result as PromiseLike).then(undefined, () => {}); + (result as PromiseLike).then(undefined, (error: unknown) => + this.reportFailure(event, listener, error), + ); } - } catch { - /* observers must never break the pipeline */ + } catch (error) { + // observers must never break the pipeline, but a silent failure hides a broken plugin (#77) + this.reportFailure(event, listener, error); } } } diff --git a/test/bus.test.ts b/test/bus.test.ts index 21aaf1e..e9a0d82 100644 --- a/test/bus.test.ts +++ b/test/bus.test.ts @@ -1,5 +1,5 @@ import { expect, test, vi } from 'vitest'; -import { Bus } from '../src/bus'; +import { Bus, reportListenerErrors } from '../src/bus'; test('subscribers receive emitted events', () => { const bus = new Bus(); @@ -45,3 +45,48 @@ test('an async subscriber that rejects is isolated too (#70)', async () => { process.off('unhandledRejection', unhandled); } }); + +test('a failing listener is reported once, sync or async, and others still run (#77)', async () => { + const bus = new Bus(); + const reports: string[] = []; + reportListenerErrors(bus, (event, error) => reports.push(`${event}:${(error as Error).message}`)); + const good = vi.fn(); + bus.on('request:end', () => { + throw new Error('sync'); + }); + bus.on('request:end', async () => { + throw new Error('async'); + }); + bus.on('request:end', good); + + for (let i = 0; i < 3; i++) bus.emit('request:end', { name: 'r' }); + await new Promise((resolve) => setTimeout(resolve, 10)); + + expect(good).toHaveBeenCalledTimes(3); + expect(reports.sort()).toEqual(['request:end:async', 'request:end:sync']); +}); + +test('a reporter that throws does not escape emit', () => { + const bus = new Bus(); + reportListenerErrors(bus, () => { + throw new Error('logger down'); + }); + bus.on('request:end', () => { + throw new Error('boom'); + }); + expect(() => bus.emit('request:end', { name: 'r' })).not.toThrow(); +}); + +test('createApp logs a broken plugin listener once, through its logger (#77)', async () => { + const { createApp, Route, Get, Module } = await import('../src/index'); + @Route('/') class Ctl { @Get('/x') x() { return { ok: true }; } } + @Module({ mountpoint: '/', controllers: [Ctl] }) class M {} + const warned: string[] = []; + const logger = { debug() {}, info() {}, error() {}, warn: (m: string) => warned.push(m) }; + const broken = { name: 'broken-metrics', mount: (api: any) => api.bus.on('request:end', () => { throw new Error('nope'); }) }; + const app = createApp({ modules: [M], plugins: [broken], logger }); + + for (let i = 0; i < 3; i++) expect((await app.fetch(new Request('http://x/x'))).status).toBe(200); + + expect(warned.filter((m) => m.includes("listener on 'request:end' threw"))).toHaveLength(1); +}); From 111eb0b81b6e047c828b7bea4600fa562a8cc6dd Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 01:38:39 -0600 Subject: [PATCH 26/41] fix(adapters): warn when Deno, Bun or the edge ignore a Node-only limit limits.maxConnections and the request, headers and keep-alive timeouts apply only to Node's listen(). serveDeno, serveBun and edgeHandler ignored them silently, which the cross-repo rules call a bug. The app records which of them it was given, under a symbol like TLS_REQUESTED, and each of the three adapters warns once through app.logger, naming them. Nothing is mapped: Bun's idleTimeout is not equivalent to any of the three. Tested on Node (edgeHandler), Deno and Bun; the API report is unchanged. Closes #76 Signed-off-by: Diego Resendez --- CHANGELOG.md | 5 +++++ README.md | 2 +- src/app/index.ts | 5 +++++ src/bun.ts | 3 ++- src/deno.ts | 3 ++- src/edge.ts | 3 ++- src/http/types.ts | 6 +++--- src/security.ts | 28 +++++++++++++++++++++++++++ test/bun/node-only-limits.test.ts | 20 +++++++++++++++++++ test/deno/node-only-limits.test.ts | 28 +++++++++++++++++++++++++++ test/node-only-limits.test.ts | 31 ++++++++++++++++++++++++++++++ 11 files changed, 127 insertions(+), 7 deletions(-) create mode 100644 test/bun/node-only-limits.test.ts create mode 100644 test/deno/node-only-limits.test.ts create mode 100644 test/node-only-limits.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index ca7d3b7..ae7ae15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,6 +113,11 @@ npm treats versions as semver and semver forbids leading zeros. unrelated step that threw broke every export. A call now runs the exported step's own closure of providers and steps, sliced once at boot like a route's. Mesh is `@experimental`; no API change. +- **Deno, Bun and the edge say when they ignore a Node-only limit** (#76). `limits.maxConnections`, + `requestTimeoutMs`, `headersTimeoutMs` and `keepAliveTimeoutMs` apply only to Node's `listen()`, + and the other adapters ignored them without a word. `serveDeno`, `serveBun` and `edgeHandler` + now warn through the app's logger, naming each one the app set. No API change. + - **A bus listener that throws is logged once** (#77). `Bus.emit` isolated a failing listener without a word, so a broken metrics or logger plugin produced nothing and gave no signal. The app's `logger` now warns the first time a listener throws or rejects, naming the event; that listener's diff --git a/README.md b/README.md index 99004c3..6ac4118 100644 --- a/README.md +++ b/README.md @@ -144,7 +144,7 @@ without growing the runtime dependency tree past `reflect-metadata`: - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. A stream that fails after it started has already sent its status, so it ends with an error frame instead (`event: error` on SSE, a last `{"error"}` line on ndjson): it carries an `HttpError`'s message, and `Internal Server Error` for anything else. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. It never serves a dotfile or anything under a dot directory (`/.env`, `/.git/config`), except under `/.well-known/`. Static files carry a weak `ETag`, `Last-Modified` and `Cache-Control: no-cache` (change it with `static: { dir, cacheControl }`), and a conditional request gets a `304` without the file being read. `createApp({ etag: true })` does the same for buffered `GET`/`HEAD` handler responses, and `createApp({ compression: true })` compresses text responses and event streams with gzip or br. It uses `node:zlib` on Node, Deno and Bun, and leaves encoding to the platform on the edge. -- **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. Node checks the headers and request timeouts every second, so a slow-header socket is closed (`408`) about when its timeout runs out, and pings each WebSocket every 30 seconds, terminating one that missed the previous ping. A connection cap is still one global number: put per-IP connection limits at the proxy. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. +- **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. Node checks the headers and request timeouts every second, so a slow-header socket is closed (`408`) about when its timeout runs out, and pings each WebSocket every 30 seconds, terminating one that missed the previous ping. A connection cap is still one global number: put per-IP connection limits at the proxy. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. The connection cap and the three timeouts are Node-only: `serveDeno`, `serveBun` and `edgeHandler` log a warning naming any of them the app set, rather than ignore them silently. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **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 })`. - **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`. diff --git a/src/app/index.ts b/src/app/index.ts index 69fc5c6..7c44bde 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -50,6 +50,8 @@ import { WS_ORIGIN_CHECK, assertCorsOptions, MESH_REQUESTED, + NODE_ONLY_LIMITS, + nodeOnlyLimits, MESH_ON_EDGE, wsOriginAllowed, type TlsOptions, @@ -565,6 +567,9 @@ export function createApp(opts: AppOptions): App { // `serveDeno` and `serveBun` refuse an app that asked for TLS only Node's listener can give. [TLS_REQUESTED]: Boolean(opts.tls), + // `serveDeno`, `serveBun` and `edgeHandler` warn that they ignore these (#76). + [NODE_ONLY_LIMITS]: nodeOnlyLimits(opts.limits), + // `edgeHandler` refuses an app that configured mesh, which cannot run there (#87). [MESH_REQUESTED]: Boolean(opts.mesh), diff --git a/src/bun.ts b/src/bun.ts index 5cac9e0..13e5b89 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -1,7 +1,7 @@ import { channel } from './channel'; import type { Channel } from './channel'; import type { App } from './app/types'; -import { refuseTls, refuseWsOrigin } from './security'; +import { refuseTls, refuseWsOrigin, warnNodeOnlyLimits } from './security'; import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, @@ -123,6 +123,7 @@ export async function serveBun(app: App, options?: BunServeOptions): Promise Response | Promise { refuseMeshOnEdge(app); + warnNodeOnlyLimits(app, 'edgeHandler'); (app as { [MARK_EDGE]?: () => void })[MARK_EDGE]?.(); return (request, _env, ctx) => { diff --git a/src/http/types.ts b/src/http/types.ts index c467ad8..0b31ecf 100644 --- a/src/http/types.ts +++ b/src/http/types.ts @@ -14,9 +14,9 @@ export interface RequestLimits { maxBodyBytes?: number; // default 1_000_000 maxConnections?: number; // default 1000; <= 0 means unlimited (Node only) maxConcurrentRequests?: number; // default unlimited; <= 0 means unlimited - requestTimeoutMs?: number; // default 30_000 - headersTimeoutMs?: number; // default 10_000 - keepAliveTimeoutMs?: number; // default 5_000 + requestTimeoutMs?: number; // default 30_000 (Node only; serveDeno/serveBun/edgeHandler warn that they ignore it) + headersTimeoutMs?: number; // default 10_000 (Node only, as above) + keepAliveTimeoutMs?: number; // default 5_000 (Node only, as above) maxParts?: number; // default 1000 /** * Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default diff --git a/src/security.ts b/src/security.ts index 7e229b5..72ddcc4 100644 --- a/src/security.ts +++ b/src/security.ts @@ -27,6 +27,34 @@ export function refuseTls(app: object, adapter: string): void { } } +/** + * The `limits` keys only Node's listener applies, set on the app as the ones the caller gave, so the + * other adapters can say they ignore them (#76) rather than ignore them silently. Symbol-keyed + * because it is adapter plumbing. + */ +export const NODE_ONLY_LIMITS: unique symbol = Symbol.for('green-tea.node-only-limits'); + +const NODE_ONLY_LIMIT_KEYS = ['maxConnections', 'requestTimeoutMs', 'headersTimeoutMs', 'keepAliveTimeoutMs'] as const; + +/** The Node-only `limits` keys present in `limits`, for {@link NODE_ONLY_LIMITS}. */ +export function nodeOnlyLimits( + limits: { [K in (typeof NODE_ONLY_LIMIT_KEYS)[number]]?: number } | undefined, +): string[] { + return NODE_ONLY_LIMIT_KEYS.filter((key) => limits?.[key] !== undefined); +} + +/** Warns, once per adapter call, that `adapter` does not apply the Node-only limits the app set. */ +export function warnNodeOnlyLimits(app: object, adapter: string): void { + const keys = (app as { [NODE_ONLY_LIMITS]?: string[] })[NODE_ONLY_LIMITS] ?? []; + if (keys.length === 0) return; + + (app as { logger?: Logger }).logger?.warn( + `${adapter} does not apply limits.${keys.join(', limits.')}: only Node's listen() does. ` + + "Set the equivalent on the runtime's server or at the proxy in front of it.", + { adapter, ignored: keys }, + ); +} + /** * Set on an app created with `mesh`, so `edgeHandler` can refuse it (#87). Mesh does not run on the * edge: the teapot's secret check needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` diff --git a/test/bun/node-only-limits.test.ts b/test/bun/node-only-limits.test.ts new file mode 100644 index 0000000..6593d56 --- /dev/null +++ b/test/bun/node-only-limits.test.ts @@ -0,0 +1,20 @@ +// #76 on serveBun: Node-only limits are reported, not silently ignored. +// Run with: npm run test:bun +import 'reflect-metadata'; +import { test, expect } from 'bun:test'; +import { createApp, Module } from '../../src/index.ts'; +import { serveBun } from '../../src/bun.ts'; + +@Module({ mountpoint: '/' }) +class M {} + +test('serveBun warns that it ignores Node-only limits', async () => { + const warned: string[] = []; + const logger = { debug() {}, info() {}, error() {}, warn: (m: string) => warned.push(m) }; + const server = await serveBun(createApp({ modules: [M], logger, limits: { headersTimeoutMs: 5 } }), { port: 0 }); + try { + expect(warned.some((m) => m.startsWith('serveBun does not apply limits.headersTimeoutMs'))).toBe(true); + } finally { + await server.close({ timeoutMs: 500 }); + } +}); diff --git a/test/deno/node-only-limits.test.ts b/test/deno/node-only-limits.test.ts new file mode 100644 index 0000000..f973501 --- /dev/null +++ b/test/deno/node-only-limits.test.ts @@ -0,0 +1,28 @@ +// #76 on serveDeno: Node-only limits are reported, not silently ignored. +// Run with: npm run test:deno +import 'npm:reflect-metadata'; +import { assert } from 'jsr:@std/assert'; +import { createApp, Module } from '../../src/index.ts'; +import { serveDeno } from '../../src/deno.ts'; + +@Module({ mountpoint: '/' }) +class M {} + +Deno.test({ + name: 'serveDeno warns that it ignores Node-only limits', + sanitizeResources: false, + sanitizeOps: false, + async fn() { + const warned: string[] = []; + const logger = { debug() {}, info() {}, error() {}, warn: (m: string) => warned.push(m) }; + const server = await serveDeno(createApp({ modules: [M], logger, limits: { maxConnections: 5 } }), { + port: 0, + onListen: () => {}, + }); + try { + assert(warned.some((m) => m.startsWith('serveDeno does not apply limits.maxConnections'))); + } finally { + await server.close({ timeoutMs: 500 }); + } + }, +}); diff --git a/test/node-only-limits.test.ts b/test/node-only-limits.test.ts new file mode 100644 index 0000000..c7b7799 --- /dev/null +++ b/test/node-only-limits.test.ts @@ -0,0 +1,31 @@ +// #76: limits only Node's listener applies are reported by the adapters that ignore them, instead of +// being ignored silently. The Deno and Bun suites check serveDeno and serveBun the same way. +import 'reflect-metadata'; +import { describe, it, expect } from 'vitest'; +import { createApp, Module } from '../src/index'; +import { edgeHandler } from '../src/edge'; + +@Module({ mountpoint: '/' }) +class M {} + +const capture = () => { + const warned: { message: string; fields: unknown }[] = []; + const logger = { debug() {}, info() {}, error() {}, warn: (message: string, fields?: unknown) => warned.push({ message, fields }) }; + return { warned, logger }; +}; + +describe('Node-only limits on another adapter', () => { + it('edgeHandler names each one the app set', () => { + const { warned, logger } = capture(); + edgeHandler(createApp({ modules: [M], logger, limits: { requestTimeoutMs: 1, keepAliveTimeoutMs: 2, maxBodyBytes: 3 } })); + expect(warned).toHaveLength(1); + expect(warned[0].message).toMatch(/edgeHandler does not apply limits\.requestTimeoutMs, limits\.keepAliveTimeoutMs/); + expect(warned[0].fields).toEqual({ adapter: 'edgeHandler', ignored: ['requestTimeoutMs', 'keepAliveTimeoutMs'] }); + }); + + it('stays quiet when none is set', () => { + const { warned, logger } = capture(); + edgeHandler(createApp({ modules: [M], logger, limits: { maxBodyBytes: 3 } })); + expect(warned).toEqual([]); + }); +}); From e1b702b400a722e60aa466e28b6fe941a6d9f573 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 09:23:13 -0600 Subject: [PATCH 27/41] fix(stream): one close reaction per stream, not one per event Both stream loops raced the source's next() against the connection's close with Promise.race. Each call leaves a reaction on the close promise that is freed only when the client disconnects, so a long-lived SSE or ndjson stream grew the heap with every event: the new soak job measured ~0.4 MB/s on a 1 kHz stream (heap 20 -> 41 MB in 90 s), and flat at 12.7 MB with this fix. raceUntil(stop) keeps a single reaction on stop and settles the one call in flight. Same semantics: the value, undefined once stop resolves, stop's reason if it rejects. Used by pipeStream (Node: next() and the drain wait) and asReadableStream (Deno, Bun, edge). No API change. Bench on jarvis (Node 22 in Docker, cpuset 6,7,14,15, bench/compare.ts, 5 rounds x 10 s, 100 connections), against the parent commit: sse 100 events 3,508 -> 4,264 req/s +21.5% sse 100 events + gzip 410 -> 426 req/s +4.0% A/A on the same box: -1.1% and +0.2%, ranges overlapping. A first version that wrapped the resolvers in a closure per call measured -6.4%; this one hands them to then() directly. Deno, Bun and the edge (asReadableStream) were not benchmarked. Found by #80. Signed-off-by: Diego Resendez --- CHANGELOG.md | 6 ++++++ src/channel.ts | 37 +++++++++++++++++++++++++++++++++++++ src/http/stream.ts | 8 ++++---- src/http/web.ts | 6 +++--- test/channel.test.ts | 27 ++++++++++++++++++++++++++- 5 files changed, 76 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ae7ae15..b59fcdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -108,6 +108,12 @@ npm treats versions as semver and semver forbids leading zeros. ### Fixed +- **A long-lived SSE or ndjson stream no longer grows the heap with every event** (found by the soak + job, #80). Each event raced the source's `next()` against the connection's close with + `Promise.race`, which leaves a reaction on the close promise per call until the client + disconnects: about 0.4 MB/s of heap on a 1 kHz stream, on Node, Deno, Bun and the edge. One + reaction per stream now. No API change. + - **Mesh: a remote step call runs only that step and what it needs** (#85). The teapot ran every one of its steps on each call, so an unexported step's side effects fired once per RPC, and any unrelated step that threw broke every export. A call now runs the exported step's own closure of diff --git a/src/channel.ts b/src/channel.ts index 435856e..cbea15c 100644 --- a/src/channel.ts +++ b/src/channel.ts @@ -28,6 +28,43 @@ export function releaseIterator(iterator: AsyncIterator | undefined): v } } +/** + * Internal: races each promise it is given against one long-lived `stop`, without leaking. + * `Promise.race([p, stop])` leaves a reaction on `stop` per call, and they are only freed when + * `stop` settles, so a stream that sends for an hour kept one per event: the soak job measured + * ~0.4 MB/s of heap on a 1 kHz SSE stream (#80). Here `stop` holds a single reaction, which settles + * the call in flight. One call at a time, as the stream loops use it. Not exported from the package. + */ +export function raceUntil(stop: Promise): (p: Promise) => Promise { + // 0 pending, 1 resolved, 2 rejected. The resolvers of the call in flight are kept bare and passed + // straight to `then`, with no wrapper closure per call: this runs once per stream event. + let ended = 0; + let reason: unknown; + let wake: ((v: undefined) => void) | undefined; + let fail: ((e: unknown) => void) | undefined; + + stop.then( + () => { + ended = 1; + wake?.(undefined); + }, + (err: unknown) => { + ended = 2; + reason = err; + fail?.(err); + }, + ); + + return (p: Promise) => { + if (ended) return ended === 1 ? Promise.resolve(undefined) : Promise.reject(reason); + return new Promise((resolve, reject) => { + wake = resolve; // a stale resolver left here after p settles is harmless: settling twice is a no-op + fail = reject; + p.then(resolve, reject); + }); + }; +} + /** * Internal: reads a channel synchronously, inside `push`, rather than through an async iterator * that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst diff --git a/src/http/stream.ts b/src/http/stream.ts index 100fda5..cfb72f8 100644 --- a/src/http/stream.ts +++ b/src/http/stream.ts @@ -5,7 +5,7 @@ import type { Transport } from '../metadata'; import type { Bus, Correlation } from '../bus'; import type { NeutralOutcome } from './core'; import { frameSink } from './compression'; -import { releaseIterator } from '../channel'; +import { raceUntil, releaseIterator } from '../channel'; const PING_MS = 15_000; @@ -81,16 +81,16 @@ export async function pipeStream( const onClose = once(res, 'close'); // `next()` is raced against the disconnect (GitHub #40): an idle source's may never settle, and // waiting on it kept this loop and its closer alive long after the client had gone. - const gone = onClose.then(() => undefined); + const untilGone = raceUntil(onClose); try { while (true) { - const step = await Promise.race([iterator.next(), gone]); + const step = await untilGone(iterator.next()); if (!step || step.done) break; const { value } = step; if (!sink.write(encoder.encode(value))) { - await Promise.race([once(sink.drains, 'drain'), onClose]); + await untilGone(once(sink.drains, 'drain')); if (res.destroyed) break; // let finally clean up } } diff --git a/src/http/web.ts b/src/http/web.ts index 3a762ce..bd128d7 100644 --- a/src/http/web.ts +++ b/src/http/web.ts @@ -21,7 +21,7 @@ import { answerProbe } from './health'; import { currentRoutes } from './router'; import { compressOutcome, compressWebStream } from './compression'; import type { NeutralOutcome } from './core'; -import { releaseIterator } from '../channel'; +import { raceUntil, releaseIterator } from '../channel'; /** * Wraps an AsyncIterable as a web ReadableStream, encoding each value. Cancels the source on stream @@ -46,7 +46,7 @@ export function asReadableStream( let closed = false; // Settles on `cancel`, so a `pull` waiting on an idle source's `next()` stops waiting (GitHub #40). let cancelled!: (step: undefined) => void; - const gone = new Promise((resolve) => (cancelled = resolve)); + const untilGone = raceUntil(new Promise((resolve) => (cancelled = resolve))); const close = (): void => { if (closed) return; @@ -60,7 +60,7 @@ export function asReadableStream( }, async pull(controller) { try { - const step = await Promise.race([iterator.next(), gone]); + const step = await untilGone(iterator.next()); if (!step) return; const { value, done } = step; diff --git a/test/channel.test.ts b/test/channel.test.ts index cf7d4d3..17e76f8 100644 --- a/test/channel.test.ts +++ b/test/channel.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { channel, isAsyncIterable } from '../src/channel'; +import { channel, isAsyncIterable, raceUntil } from '../src/channel'; const collect = async (it: AsyncIterable, n: number): Promise => { const out: T[] = []; @@ -72,3 +72,28 @@ describe('channel', () => { expect((await a.next()).done).toBe(true); }); }); + +describe('raceUntil (#80)', () => { + it('settles with the promise while stop is pending', async () => { + const until = raceUntil(new Promise(() => {})); + expect(await until(Promise.resolve(1))).toBe(1); + await expect(until(Promise.reject(new Error('x')))).rejects.toThrow('x'); + }); + + it('settles the call in flight, and every later one, with undefined once stop resolves', async () => { + let stop!: () => void; + const until = raceUntil(new Promise((r) => (stop = r))); + const inFlight = until(new Promise(() => {})); + stop(); + expect(await inFlight).toBeUndefined(); + expect(await until(new Promise(() => {}))).toBeUndefined(); + }); + + it('rejects with the reason stop rejects with', async () => { + let fail!: (e: unknown) => void; + const until = raceUntil(new Promise((_, r) => (fail = r))); + const inFlight = until(new Promise(() => {})); + fail(new Error('reset')); + await expect(inFlight).rejects.toThrow('reset'); + }); +}); From 0850e165dd7d4268c533eaedb724f13217033486 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 09:23:16 -0600 Subject: [PATCH 28/41] fix(channel): cap each subscriber at 1024 values by default channel() buffered without limit per subscriber, so a slow SSE client on a busy channel or room grew server memory without bound. The default is now 1024, dropping the oldest, as an explicit { buffer } already did; { buffer: Infinity } keeps the old behaviour. WebSocket inbound channels pass Infinity explicitly: they are bounded per frame by boundInbound (#107), and dropping a client's frame silently would be wrong. Behaviour change, no API change. Closes #82 Signed-off-by: Diego Resendez --- CHANGELOG.md | 8 ++++++++ README.md | 2 +- src/bun.ts | 2 +- src/channel.ts | 12 ++++++++++-- src/http/ws-adapter.ts | 2 +- src/http/ws.ts | 2 +- test/channel.test.ts | 10 +++++++++- 7 files changed, 31 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b59fcdc..366080c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -106,6 +106,14 @@ npm treats versions as semver and semver forbids leading zeros. secret. **Behaviour change:** a browser client served from another origin, or an app behind a proxy that rewrites `Host`, now needs that origin in `cors.origins`. No API change. +### Changed + +- **`channel()` buffers 1024 values per subscriber by default, dropping the oldest** (#82). The + default was unbounded, so a slow SSE or WebSocket client on a busy channel or room grew server + memory without limit. Pass `channel({ buffer: Infinity })` for the old behaviour. **Behaviour + change** for a subscriber that falls more than 1024 values behind. WebSocket inbound queues are + unchanged (bounded per frame by `limits`). No API change. + ### Fixed - **A long-lived SSE or ndjson stream no longer grows the heap with every event** (found by the soak diff --git a/README.md b/README.md index 6ac4118..cc113cc 100644 --- a/README.md +++ b/README.md @@ -108,7 +108,7 @@ The primitive never changes — it's always an `AsyncIterable`. What changes is **Your wire contract is what you declared, never what you happened to return.** A buffered route that returns an iterable, or a streaming route that returns a plain value, fails loudly with a `TransportMismatchError` — green-tea will not quietly switch a route's transport because of a return type. Refactoring a handler's internals can't change how it talks to the client. -Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it. +Fan-out is a primitive too: `channel()` is a **multicast** `AsyncIterable` (bounded, drop-oldest: 1024 values per subscriber unless you pass `channel({ buffer })`) so one source feeds many subscribers, and `rooms` are named broadcast hubs — publish once, every connection in the room receives it. ```typescript @Route('/live') diff --git a/src/bun.ts b/src/bun.ts index 13e5b89..748eddd 100644 --- a/src/bun.ts +++ b/src/bun.ts @@ -133,7 +133,7 @@ export async function serveBun(app: App, options?: BunServeOptions): Promise extends Channel { [CHANNEL_TAP](sink: ChannelSink): () => void; } +/** + * Internal: the per-subscriber cap when `channel()` is given none (#82). Unbounded before, so a slow SSE + * client on a busy channel grew server memory without limit. Not exported from the package. + */ +export const DEFAULT_CHANNEL_BUFFER = 1024; + interface Sub { iterator: AsyncIterator; push(value: T, cap: number): void; @@ -153,10 +159,12 @@ function newSub(onReturn: () => void): Sub { /** * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. - * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). + * @param opts.buffer Per-subscriber queue cap; drops the oldest value when exceeded (default: + * {@link DEFAULT_CHANNEL_BUFFER}). Pass `Infinity` to never drop, at the cost of unbounded memory + * for a subscriber that stops reading. */ export function channel(opts: { buffer?: number } = {}): Channel { - const cap = opts.buffer ?? Infinity; + const cap = opts.buffer ?? DEFAULT_CHANNEL_BUFFER; const subs = new Set, 'iterator'>>(); let done = false; let closedFlag = false; diff --git a/src/http/ws-adapter.ts b/src/http/ws-adapter.ts index de1ef06..5861ac9 100644 --- a/src/http/ws-adapter.ts +++ b/src/http/ws-adapter.ts @@ -62,7 +62,7 @@ export interface EventfulSocket { * than the socket, so it builds its own {@link WsSocket} over state stashed on `ws.data`. */ export function eventSocket(host: EventfulSocket): WsSocket { - const inbound = channel(); + const inbound = channel({ buffer: Infinity }); // ponytail: bounded per frame by boundInbound (#107), never by drop-oldest const ac = new AbortController(); host.addEventListener('message', (event) => { diff --git a/src/http/ws.ts b/src/http/ws.ts index b500ca7..7a63ffd 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -142,7 +142,7 @@ function nodeWsRequest(req: http.IncomingMessage): WsRequest { export const WS_PING_MS = 30_000; export function nodeSocket(ws: any): WsSocket { - const inbound = channel(); + const inbound = channel({ buffer: Infinity }); // ponytail: bounded per frame by boundInbound (#107), never by drop-oldest const ac = new AbortController(); // `drained` callers waiting for the send buffer to fall to the mark (#41). Released by a send // callback, which `ws` runs once that frame is written to the TCP socket, or by the close. diff --git a/test/channel.test.ts b/test/channel.test.ts index 17e76f8..bf0a706 100644 --- a/test/channel.test.ts +++ b/test/channel.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect } from 'vitest'; -import { channel, isAsyncIterable, raceUntil } from '../src/channel'; +import { channel, DEFAULT_CHANNEL_BUFFER, isAsyncIterable, raceUntil } from '../src/channel'; const collect = async (it: AsyncIterable, n: number): Promise => { const out: T[] = []; @@ -61,6 +61,14 @@ describe('channel', () => { expect((await it.next()).done).toBe(true); }); + it('buffers at most DEFAULT_CHANNEL_BUFFER per subscriber by default (#82)', async () => { + const ch = channel(); + const it = ch[Symbol.asyncIterator](); + for (let i = 0; i <= DEFAULT_CHANNEL_BUFFER; i++) ch.push(i); // one past the cap: 0 is dropped + ch.close(); + expect((await it.next()).value).toBe(1); + }); + it('.return() on one subscriber does not affect the other', async () => { const ch = channel(); const a = ch[Symbol.asyncIterator](); From 5bb848ae69e357df9bd5cd898291a5a3cb65c7c8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Fri, 20 Nov 2026 09:23:19 -0600 Subject: [PATCH 29/41] fix(dev-endpoints): SRI on /__graph__, no provider names in /__ready__ /__graph__ loaded Cytoscape, dagre and cytoscape-dagre from jsDelivr with no integrity check. Each script now carries a sha384 integrity attribute and crossorigin="anonymous". /__ready__ listed degraded provider names in its public body. It now answers {"status":"degraded"}; the names stay in the boot warning and app.degraded(). The router parity test pins a sha256 of the graph page captured at ed47836. It now hashes the page with the SRI attributes removed, so it still pins the rest of the page against the original capture without regenerating it. Behaviour change for a probe client that read "degraded". No API change. Closes #83 Signed-off-by: Diego Resendez --- CHANGELOG.md | 10 ++++++++++ README.md | 2 +- src/app/index.ts | 2 +- src/graph-viz.ts | 6 +++--- src/http/health.ts | 6 +++--- test/bun/health.test.ts | 4 ++-- test/deno/health.test.ts | 4 ++-- test/graph-viz.test.ts | 6 ++++++ test/health.test.ts | 10 +++++----- test/router-introspection-parity.test.ts | 8 +++++--- 10 files changed, 38 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 366080c..0ff6ace 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -114,6 +114,16 @@ npm treats versions as semver and semver forbids leading zeros. change** for a subscriber that falls more than 1024 values behind. WebSocket inbound queues are unchanged (bounded per frame by `limits`). No API change. +- **`/__ready__` no longer lists degraded provider names** (#83). The body is + `{"status":"degraded"}`; the names stay in the boot log and `app.degraded()`. **Behaviour + change** for a probe client that read `degraded`. No API change. + +### Security + +- **`/__graph__` pins its three CDN scripts with Subresource Integrity** (#83). A compromised or + altered CDN copy of Cytoscape or dagre is refused by the browser instead of running on the dev + graph page. No API change. + ### Fixed - **A long-lived SSE or ndjson stream no longer grows the heap with every event** (found by the soak diff --git a/README.md b/README.md index cc113cc..ab7e142 100644 --- a/README.md +++ b/README.md @@ -147,7 +147,7 @@ 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. Node checks the headers and request timeouts every second, so a slow-header socket is closed (`408`) about when its timeout runs out, and pings each WebSocket every 30 seconds, terminating one that missed the previous ping. A connection cap is still one global number: put per-IP connection limits at the proxy. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. The connection cap and the three timeouts are Node-only: `serveDeno`, `serveBun` and `edgeHandler` log a warning naming any of them the app set, rather than ignore them silently. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults. - **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 })`. -- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers that failed) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`. +- **Liveness and readiness probes.** `createApp({ health: true })` serves `/__live__` and `/__ready__`. Readiness reports `booting`, `ok`, `degraded` (optional providers failed; their names go to the boot log and `app.degraded()`, never to the public body) or `draining` (from the moment `close()` starts). Probes are answered ahead of the pipeline: they are never shed and never show up in lifecycle events or request logs. `health: { drainDelayMs }` keeps the listener open for that window after `close()` starts, so a load balancer reads the `503` before connections drain. The edge never reports `draining`, because it has no `close()`. - **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. diff --git a/src/app/index.ts b/src/app/index.ts index 7c44bde..9c1eb73 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -147,7 +147,7 @@ export interface AppOptions { * * - `/__live__` answers `200 {"status":"ok"}` whenever the process answers. * - `/__ready__` answers `503 {"status":"booting"}` until `boot()` resolves, then - * `200 {"status":"ok"}` or `200 {"status":"degraded","degraded":[…]}` (see `app.degraded()`), + * `200 {"status":"ok"}` or `200 {"status":"degraded"}` (names in the boot log and `app.degraded()`), * and `503 {"status":"draining"}` from the moment `close()` starts. * * Probes skip the pipeline: no step, provider, plugin or `onError` runs and no lifecycle event is diff --git a/src/graph-viz.ts b/src/graph-viz.ts index 2169c03..aa64f5e 100644 --- a/src/graph-viz.ts +++ b/src/graph-viz.ts @@ -86,9 +86,9 @@ export function graphHtml(view: GraphView): string { return ` green-tea graph - - - + + +