From 2c00cc340710c899bb173d45ddc6dfde76a2859a Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 22 Oct 2026 23:55:22 -0500 Subject: [PATCH 1/2] feat(mesh)!: reserve /__mesh__/control on every adapter (CARD-21, #126) The Node upgrade listener only intercepted /__mesh__/control when a mesh control channel was configured; otherwise a user @Ws route there was served. app.upgrade (Deno, Bun, edge) always checked the path first and closed 1008. The same app therefore worked on Node and was refused everywhere else. D17 makes the path reserved in every app, mesh or not: - createApp fails when a @Ws, @Stream or HTTP route claims the path, naming the declaration. A literal pattern is checked by equality, a parameterised one (/__mesh__/:x, /__mesh__/:rest*) by matching the reserved path against it. Patterns whose first segment is not the literal __mesh__ (/:org/:repo, /:rest*) still boot: the adapters answer the path before route matching, so those routes never see it. - A route exported by a teapot is checked during the teacup splice. - The Node listener, with no control channel, accepts the upgrade and closes 1008 with the reason app.upgrade gives. The reason is now one shared constant. The check lives in src/http/reserved-paths.ts so CARD-17 can add /__live__ and /__ready__ to the same list. BREAKING CHANGE: an app that declares a route at /__mesh__/control, or a pattern under /__mesh__/ that matches it, now fails createApp. Signed-off-by: Diego Resendez --- CHANGELOG.md | 15 +++ src/app/index.ts | 31 ++++- src/http/reserved-paths.ts | 49 +++++++ src/http/ws.ts | 21 +++ src/mesh/teapot.ts | 14 +- test/bun/ws.test.ts | 28 ++++ test/deno/ws.test.ts | 40 ++++++ test/edge/run.ts | 12 +- test/edge/worker.ts | 28 +++- test/reserved-paths.test.ts | 247 ++++++++++++++++++++++++++++++++++++ 10 files changed, 478 insertions(+), 7 deletions(-) create mode 100644 src/http/reserved-paths.ts create mode 100644 test/reserved-paths.test.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index 880157d..e2b8c7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -74,6 +74,21 @@ npm treats versions as semver and semver forbids leading zeros. another name fails as well, whatever order things are registered in. `overrides` keep working: they replace the runner of an existing token and add no producer. Observer steps that provide nothing are unaffected. The official plugins already follow name = node name = token. +- **`/__mesh__/control` is reserved in every app, mesh or not** (#126). A `@Ws`, `@Stream` or HTTP + route that claims it — `@Ws('/__mesh__/control')`, `@Get('/__mesh__/control')`, + `@Ws('/__mesh__/:x')`, `/__mesh__/:rest*`, or a mountpoint that adds up to one of these — now + fails `createApp`, naming the declaration and the reserved path. A route exported by a teapot is + checked the same way, and fails the teacup's boot. Before, the Node listener served a user route + there whenever no mesh control channel was configured, while `app.upgrade` (Deno, Bun, the edge) + always refused it, so the same route worked on one runtime and not the others. A pattern whose + first segment is not the literal `__mesh__` (`/:org/:repo`, `/:rest*`) still boots; the reserved + path is answered ahead of the route table on every runtime, so such a route never sees it. + + An upgrade to `/__mesh__/control` on an app with no control channel is now refused identically + everywhere: the Node listener accepts it and closes `1008` with + `mesh control channel not enabled: this app exports nothing, or has no mesh.secret`, as + `app.upgrade` already did. An app with no `@Ws`/`@Stream` routes and no mesh attaches no upgrade + listener on Node, as before, so there the request still reaches the HTTP route table. ### Added diff --git a/src/app/index.ts b/src/app/index.ts index 82e537e..b8f2291 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -45,13 +45,14 @@ import { connectLink, isPermanentRefusal, type Link } from '../mesh/link'; import { Rooms } from '../rooms'; import type { TlsOptions, SecurityOptions, CorsOptions } from '../security'; import { buildRemote } from '../mesh/teacup'; -import { buildManifest, createMeshControl, MESH_CONTROL_PATH } from '../mesh/teapot'; +import { buildManifest, createMeshControl, MESH_CONTROL_DISABLED_REASON, MESH_CONTROL_PATH } from '../mesh/teapot'; import type { MeshControl } from '../http'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { compilePattern, markRemoteRoute, normalizeRequestPath } from '../http/router'; import { routeConflict, type Precedence, type RouteConflict } from '../http/route-conflicts'; +import { assertNotReserved, type ReservedPath } from '../http/reserved-paths'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types'; @@ -221,6 +222,8 @@ export function createApp(opts: { const viewsCtx: ViewsContext = { views: opts.views, viewEngine: opts.viewEngine }; const registry = collectModules(opts.modules, viewsCtx); const { providerNodes, stepNodes, runners, providerMeta, routePlans } = registry; + const reserved = reservedPaths(); + assertNoReservedRoutes(routePlans, reserved); const teardown = buildTeardownRegistry(opts.hooks, opts.teardownTimeoutMs, opts.shutdownTimeoutMs); mountPlugins(opts.plugins, bus, registry, teardown); provideBuiltins(registry, logger, bus); @@ -252,7 +255,7 @@ export function createApp(opts: { // can only be built here, after finalize(), and never at construction time. const prepareGraph = async (): Promise => { if (opts.mesh && !booted) { - const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger); + const spliced = await spliceRemoteScopes(opts.mesh, bus, registry, logger, reserved); remoteRoutes = spliced.remoteRoutes; meshLinks.push(...spliced.meshLinks); // Without this the error is `missing dependency: auth needed by getUser` and says nothing @@ -632,6 +635,24 @@ function resolveTransformer( return buildHtmlTransformer(html, viewsCtx); } +/** + * The paths this app answers itself, ahead of the route table (D17). + * + * `/__mesh__/control` is reserved in every app, mesh or not: whether a route there is served must not + * depend on the runtime or on whether a mesh happens to be configured. + */ +function reservedPaths(): ReservedPath[] { + return [{ path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' }]; +} + +/** Fails the boot when a declared route claims a reserved path (see {@link assertNotReserved}). */ +function assertNoReservedRoutes(routePlans: RoutePlan[], reserved: readonly ReservedPath[]): void { + for (const plan of routePlans) { + const kind = plan.transport === 'ws' ? '@Ws' : plan.transport === 'negotiate' ? '@Stream' : plan.method; + assertNotReserved(plan.pattern, `route ${kind} ${plan.pattern} at ${plan.declaration}`, reserved); + } +} + /** Reads every module's metadata into a fresh {@link Registry} of graph nodes, runners and exports. */ function collectModules(modules: Ctor[], viewsCtx: ViewsContext): Registry { const registry = emptyRegistry(); @@ -976,6 +997,7 @@ async function spliceRemoteScopes( bus: Bus, registry: Registry, logger: Logger, + reserved: readonly ReservedPath[], ): Promise<{ remoteRoutes: RouteDef[]; meshLinks: Link[]; absent: string[] }> { const remoteRoutes: RouteDef[] = []; const meshLinks: Link[] = []; @@ -1015,6 +1037,9 @@ async function spliceRemoteScopes( for (const route of routes) { const display = `${route.method} ${route.pattern}`; + // A teapot's own boot refuses such a route, but the manifest is whatever arrives on the wire: + // an older or foreign teapot could still advertise one, and the teacup must not splice it. + assertNotReserved(route.pattern, `mesh: remote route '${display}' from ${teapot.url}`, reserved); const key = `${route.method} ${compilePattern(route.pattern).shape}`; const owner = routeOwners.get(key); @@ -1431,7 +1456,7 @@ function buildAppUpgrade( // an explicit refusal, not "no matching ws route": the path is reserved either way, and a // peer that reached a teapot with nothing exported deserves to be told which it was if (!meshControl) { - ready.close(1008, 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret'); + ready.close(1008, MESH_CONTROL_DISABLED_REASON); return; } diff --git a/src/http/reserved-paths.ts b/src/http/reserved-paths.ts new file mode 100644 index 0000000..7a55875 --- /dev/null +++ b/src/http/reserved-paths.ts @@ -0,0 +1,49 @@ +import { compilePattern, matchPattern } from './router'; + +/** + * A path the framework answers itself, ahead of the route table, so no declared route may claim it. + * + * Each adapter intercepts these before route matching. A user route that could also match one would + * be served on some code paths and shadowed on others, which is exactly the "works on Node, refused + * on Deno" split a reserved path exists to prevent, so the boot refuses it instead. + */ +export interface ReservedPath { + /** The concrete request path, e.g. `/__mesh__/control`. */ + path: string; + /** What the framework serves there, for the error message (e.g. `the mesh control channel`). */ + purpose: string; +} + +/** + * Returns the reserved path `pattern` would claim, or `undefined` when it claims none. + * + * A pattern claims a reserved path when it matches it *and* its first segment is the reserved path's + * own first segment, spelled literally. The literal-prefix half is deliberate: `/:org/:repo` or a + * `/:rest*` fallback also match `/__mesh__/control`, but they never ask for it — the adapter intercepts + * the reserved path before matching, so such a route simply never sees that one path, the same way + * on every runtime. Refusing them would fail the boot of ordinary apps for a path they never named. + * A literal pattern is therefore checked by equality and a parameterised one (`/__mesh__/:x`, + * `/__mesh__/:rest*`) by matching the reserved path against it. + */ +export function claimedReservedPath(pattern: string, reserved: readonly ReservedPath[]): ReservedPath | undefined { + const first = compilePattern(pattern).segments[0]; + if (first?.kind !== 'static') return undefined; + + return reserved.find( + (entry) => entry.path.split('/')[1] === first.value && matchPattern(pattern, entry.path) !== undefined, + ); +} + +/** + * Throws when `pattern` claims a reserved path. `subject` names the declaration for the message, + * e.g. `route GET /__mesh__/control at Chat.control`. + */ +export function assertNotReserved(pattern: string, subject: string, reserved: readonly ReservedPath[]): void { + const claimed = claimedReservedPath(pattern, reserved); + if (!claimed) return; + + throw new Error( + `${subject} uses the reserved path ${claimed.path} (${claimed.purpose}) — ` + + 'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.', + ); +} diff --git a/src/http/ws.ts b/src/http/ws.ts index cfc7e7a..c5d7130 100644 --- a/src/http/ws.ts +++ b/src/http/ws.ts @@ -13,6 +13,7 @@ import { 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'; /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ function loadWss(): any | null { @@ -62,6 +63,18 @@ function handleMeshUpgrade( return true; } +/** Accepts an upgrade to the reserved mesh path on an app without a control channel, then closes it 1008. */ +function refuseMeshUpgrade(wss: any, req: http.IncomingMessage, socket: any, head: Buffer): void { + if (!wss) { + rejectUpgrade(socket, 501, 'Not Implemented'); + return; + } + + wss.handleUpgrade(req, socket, head, (ws: { close(code: number, reason: string): void }) => + ws.close(1008, MESH_CONTROL_DISABLED_REASON), + ); +} + /** Builds the neutral WsRequest from a Node upgrade request. Same values the old open() read from req.socket. */ function nodeWsRequest(req: http.IncomingMessage): WsRequest { return { @@ -157,6 +170,14 @@ function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, h if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return; + // The reserved path with no control channel: refused exactly as `app.upgrade` refuses it on Deno, + // Bun and the edge — accept, then close 1008 with the same reason (D17). Never falls through to the + // ws route table: the boot already refuses any route that claims this path. + if (path === MESH_CONTROL_PATH) { + refuseMeshUpgrade(wss, req, socket, head); + return; + } + const route = matchWsRoute(wsRoutes, path); if (!route) { diff --git a/src/mesh/teapot.ts b/src/mesh/teapot.ts index 3c4e651..014fcf4 100644 --- a/src/mesh/teapot.ts +++ b/src/mesh/teapot.ts @@ -17,9 +17,21 @@ import { type Frame, } from './protocol'; -/** WebSocket path where a teapot exposes its mesh control channel. */ +/** + * WebSocket path where a teapot exposes its mesh control channel. + * + * Reserved in every app, mesh or not (D17): `createApp` refuses a route that claims it, and an upgrade + * to it on an app without a control channel closes `1008` on every adapter. + */ export const MESH_CONTROL_PATH = '/__mesh__/control'; +/** + * Close reason for an upgrade to {@link MESH_CONTROL_PATH} on an app with no control channel. One + * string shared by `app.upgrade` and the Node listener, so every adapter refuses it identically (D17). + */ +export const MESH_CONTROL_DISABLED_REASON = + 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret'; + /** * How long an unauthenticated peer may hold the control channel open before it is hung up on. * diff --git a/test/bun/ws.test.ts b/test/bun/ws.test.ts index 910a198..52b37d4 100644 --- a/test/bun/ws.test.ts +++ b/test/bun/ws.test.ts @@ -139,3 +139,31 @@ test('serveBun: ws message size default is 1 MiB', async () => { server.stop(true); } }); + +// CARD-21 (D17): the reserved mesh path is refused the way the Node listener refuses it, and a route +// that claims it fails createApp here too. +test('serveBun: /__mesh__/control without a control channel closes 1008; a route there fails createApp', async () => { + @Route('/') + class Claims { + @Ws('/__mesh__/control') + control() { + return (async function* () {})(); + } + } + @Module({ mountpoint: '/', controllers: [Claims] }) + class ClaimsModule {} + expect(() => createApp({ modules: [ClaimsModule] })).toThrow( + /^route @Ws \/__mesh__\/control at Claims\.control uses the reserved path/, + ); + + const app = createApp({ modules: [M] }); + const server = await serveBun(app, { port: 0 }); + try { + expect((await exchange(server.port, '/__mesh__/control', [])).close).toEqual({ + code: 1008, + reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret', + }); + } finally { + server.stop(true); + } +}); diff --git a/test/deno/ws.test.ts b/test/deno/ws.test.ts index d713b90..6b7f316 100644 --- a/test/deno/ws.test.ts +++ b/test/deno/ws.test.ts @@ -181,3 +181,43 @@ Deno.test('serveDeno: ws message size default is 1 MiB', async () => { await server.shutdown(); } }); + +// CARD-21 (D17): the reserved mesh path is refused the way the Node listener refuses it, and a route +// that claims it fails createApp here too. +Deno.test('serveDeno: /__mesh__/control without a control channel closes 1008; a route there fails createApp', async () => { + @Route('/') + class Claims { + @Ws('/__mesh__/control') + control() { + return (async function* () {})(); + } + } + @Module({ mountpoint: '/', controllers: [Claims] }) + class ClaimsModule {} + let message = ''; + try { + createApp({ modules: [ClaimsModule] }); + } catch (error) { + message = (error as Error).message; + } + assertEquals(message.startsWith('route @Ws /__mesh__/control at Claims.control uses the reserved path'), true); + + const app = createApp({ modules: [M] }); + let port = 0; + const server = await serveDeno(app, { + port: 0, + onListen: (addr) => { + port = addr.port; + }, + }); + await new Promise((resolve) => setTimeout(resolve, 50)); + + try { + assertEquals((await exchange(port, '/__mesh__/control', [])).close, { + code: 1008, + reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret', + }); + } finally { + await server.shutdown(); + } +}); diff --git a/test/edge/run.ts b/test/edge/run.ts index c080839..d72823b 100644 --- a/test/edge/run.ts +++ b/test/edge/run.ts @@ -161,8 +161,18 @@ async function main() { assert.equal(await wsIp('localhost', cf), 'ip:', 'T4 edge WS without trustProxy'); assert.equal(await wsIp('trusted', cf), 'ip:1.2.3.4', 'T5 edge WS under trustProxy'); + // CARD-21 (D17): the reserved mesh path closes 1008 with the Node listener's reason, and a route + // that claims it fails createApp. + assert.deepEqual((await exchange(mf, 'http://localhost/__mesh__/control', [])).close, { + code: 1008, + reason: 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret', + }); + 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/); + console.log( - 'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy — PASS', + 'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy + reserved path — PASS', ); } finally { await mf.dispose(); diff --git a/test/edge/worker.ts b/test/edge/worker.ts index 904f7e5..b3e3453 100644 --- a/test/edge/worker.ts +++ b/test/edge/worker.ts @@ -70,7 +70,31 @@ const handlers: Record> = { trusted: edgeHandler(trusted), }; +// CARD-21 (D17): a route on the reserved mesh path must fail createApp inside workerd too. Built per +// request on the `reserved` host so a regression answers with a status instead of breaking the worker. +@Route('/') +class Claims { + @Ws('/__mesh__/control') + control() { + return (async function* () {})(); + } +} +@Module({ mountpoint: '/', controllers: [Claims] }) +class ClaimsModule {} + +function reservedBoot(): Response { + try { + createApp({ modules: [ClaimsModule] }); + } 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]) => - (handlers[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx), + fetch: (request: Request, env?: unknown, ctx?: Parameters>[2]) => { + const host = new URL(request.url).hostname; + if (host === 'reserved') return reservedBoot(); + return (handlers[host] ?? handlers.default)(request, env, ctx); + }, }; diff --git a/test/reserved-paths.test.ts b/test/reserved-paths.test.ts new file mode 100644 index 0000000..5853e44 --- /dev/null +++ b/test/reserved-paths.test.ts @@ -0,0 +1,247 @@ +/** + * CARD-21 (#126, D17): `/__mesh__/control` is reserved in every app, mesh or not. Boot refuses a route + * that claims it, and an upgrade to it on an app without a control channel is refused the same way + * by the Node listener and by `app.upgrade`. Deno, Bun and workerd repeat T1/T5 in their own suites. + */ +import 'reflect-metadata'; +import { describe, it, expect, afterEach } from 'vitest'; +import type { AddressInfo } from 'net'; +import type http from 'http'; +import WebSocket, { WebSocketServer } from 'ws'; +import { createApp, Route, Get, Post, Ws, Stream, Module, param, MESH_CONTROL_PATH } from '../src/index'; +import type { RouteDecorator } from '../src/metadata'; +import { channel } from '../src/channel'; +import type { WsRequest, WsSocket } from '../src/http/ws-core'; +import { claimedReservedPath } from '../src/http/reserved-paths'; +import { encode, decode, MESH_PROTOCOL_VERSION } from '../src/mesh/protocol'; + +const REASON = 'mesh control channel not enabled: this app exports nothing, or has no mesh.secret'; +const RESERVED = [{ path: MESH_CONTROL_PATH, purpose: 'the mesh control channel' }]; + +type Decl = [RouteDecorator, string]; + +/** One controller under `mountpoint`, a handler per declaration (`h0`, `h1`, …). */ +function moduleWith(decls: Decl[], mountpoint = '/', name = 'Routes') { + const Routes = { [name]: class {} }[name]; + + decls.forEach(([decorator, path], index) => { + const handler = `h${index}`; + Object.defineProperty(Routes.prototype, handler, { + value: (p: Record) => + (async function* () { + yield { route: handler, params: p }; + })(), + configurable: true, + }); + param()(Routes.prototype, handler, 0); + decorator(path)(Routes.prototype, handler, Object.getOwnPropertyDescriptor(Routes.prototype, handler)!); + }); + + Route('/')(Routes); + class RoutesModule {} + Module({ mountpoint, controllers: [Routes] })(RoutesModule); + return RoutesModule; +} + +const bootError = (decls: Decl[], mountpoint?: string): string => { + try { + createApp({ modules: [moduleWith(decls, mountpoint)] }); + } catch (error) { + return (error as Error).message; + } + + throw new Error('expected the app to refuse to boot'); +}; + +describe('CARD-21: a route on the reserved mesh path fails createApp', () => { + it('T1: @Ws(/__mesh__/control) on a non-mesh app', () => { + expect(bootError([[Ws, '/__mesh__/control']])).toBe( + 'route @Ws /__mesh__/control at Routes.h0 uses the reserved path /__mesh__/control (the mesh control channel) — ' + + 'green-tea answers that path itself on every runtime, so no route may declare it. Move the route.', + ); + }); + + it('T2: @Get(/__mesh__/control)', () => { + expect(bootError([[Get, '/__mesh__/control']])).toMatch( + /^route GET \/__mesh__\/control at Routes\.h0 uses the reserved path \/__mesh__\/control/, + ); + }); + + it('T3: @Ws(/__mesh__/:x) — a parameterised pattern is checked by matching', () => { + expect(bootError([[Ws, '/__mesh__/:x']])).toMatch(/^route @Ws \/__mesh__\/:x at Routes\.h0 uses the reserved path/); + }); + + it('@Stream, other methods, catch-alls, a trailing slash and a mountpoint are caught too', () => { + expect(bootError([[Stream, '/__mesh__/control']])).toMatch(/^route @Stream \/__mesh__\/control at/); + expect(bootError([[Post, '/__mesh__/control']])).toMatch(/^route POST /); + expect(bootError([[Get, '/__mesh__/:rest*']])).toMatch(/uses the reserved path/); + expect(bootError([[Get, '/__mesh__/control/']])).toMatch(/uses the reserved path/); + expect(bootError([[Get, '/control']], '/__mesh__')).toMatch(/^route GET \/__mesh__\/control at/); + expect(bootError([[Get, '/__mesh__/:x(c.*)']])).toMatch(/uses the reserved path/); + }); + + it('a mesh-enabled app gets the same refusal: the reservation does not depend on the mesh', () => { + expect(() => + createApp({ + modules: [moduleWith([[Ws, '/__mesh__/control']])], + experimental: true, + mesh: { secret: 's' }, + }), + ).toThrow(/uses the reserved path \/__mesh__\/control/); + }); + + it('patterns that do not name the reserved prefix still boot (the path is carved out of them)', () => { + expect(() => + createApp({ + modules: [ + moduleWith([ + [Get, '/:org/:repo'], + [Get, '/__mesh__/other'], + [Get, '/__mesh__/:x(\\d+)'], + [Get, '/__mesh__'], + [Get, '/__mesh__/control/deeper'], + ]), + ], + }), + ).not.toThrow(); + expect(() => createApp({ modules: [moduleWith([[Ws, '/:a/:b']])] })).not.toThrow(); + expect(() => createApp({ modules: [moduleWith([[Get, '/:rest*']])] })).not.toThrow(); + }); + + it('claimedReservedPath: literal by equality, parameterised by matching, prefix spelled literally', () => { + expect(claimedReservedPath('/__mesh__/control', RESERVED)).toEqual(RESERVED[0]); + expect(claimedReservedPath('/__mesh__/:x', RESERVED)).toEqual(RESERVED[0]); + expect(claimedReservedPath('/__mesh__/:rest*', RESERVED)).toEqual(RESERVED[0]); + expect(claimedReservedPath('/:a/control', RESERVED)).toBeUndefined(); + expect(claimedReservedPath('/:rest*', RESERVED)).toBeUndefined(); + expect(claimedReservedPath('/', RESERVED)).toBeUndefined(); + expect(claimedReservedPath('/__mesh__/:x(\\d+)', RESERVED)).toBeUndefined(); + }); +}); + +/** Drives `app.upgrade` with an in-memory socket and records what it sent and how it closed. */ +async function viaAppUpgrade(app: ReturnType, path: string) { + const sent: unknown[] = []; + const closes: Array<{ code?: number; reason?: string }> = []; + const ac = new AbortController(); + let open = true; + const socket: WsSocket = { + inbound: channel(), + abort: ac.signal, + get isOpen() { + return open; + }, + send: (data) => sent.push(data), + close: (code, reason) => { + open = false; + closes.push({ code, reason }); + ac.abort(); + }, + terminate: () => { + open = false; + ac.abort(); + }, + }; + const request: WsRequest = { url: path, headers: {}, protocol: 'http', ip: '127.0.0.1' }; + await app.upgrade(request, socket); + return { sent, closes }; +} + +/** Opens a `ws` client on the Node listener and resolves with the HTTP status or the close frame. */ +function viaNodeUpgrade(port: number, path: string) { + return new Promise<{ status: number; close?: { code: number; reason: string } }>((resolve) => { + const client = new WebSocket(`ws://127.0.0.1:${port}${path}`); + client.on('unexpected-response', (_req, res) => { + resolve({ status: res.statusCode ?? 0 }); + res.resume(); + client.terminate(); + }); + client.on('close', (code, reason) => resolve({ status: 101, close: { code, reason: String(reason) } })); + client.on('error', () => {}); + }); +} + +describe('CARD-21: an upgrade to the reserved path on an app with no control channel', () => { + const servers: http.Server[] = []; + + afterEach(async () => { + await Promise.all(servers.splice(0).map((server) => new Promise((resolve) => server.close(resolve)))); + }); + + const ordinary = () => moduleWith([[Ws, '/echo']], '/', 'Ordinary'); + + it('T4: the Node listener accepts and closes 1008 with the app.upgrade reason', async () => { + const app = createApp({ modules: [ordinary()] }); + const server = await app.listen(0); + servers.push(server); + + expect(await viaNodeUpgrade((server.address() as AddressInfo).port, '/__mesh__/control')).toEqual({ + status: 101, + close: { code: 1008, reason: REASON }, + }); + }); + + it('T4: a teapot with no exports (mesh configured, no control channel) refuses the same way on Node', async () => { + const app = createApp({ modules: [ordinary()], experimental: true, mesh: {} }); + const server = await app.listen(0); + servers.push(server); + + expect(await viaNodeUpgrade((server.address() as AddressInfo).port, '/__mesh__/control')).toEqual({ + status: 101, + close: { code: 1008, reason: REASON }, + }); + }); + + it('T5: app.upgrade closes 1008 with the same reason', async () => { + const app = createApp({ modules: [ordinary()] }); + expect(await viaAppUpgrade(app, '/__mesh__/control')).toEqual({ + sent: [], + closes: [{ code: 1008, reason: REASON }], + }); + }); +}); + +describe('CARD-21 T7: a teapot that advertises a route on the reserved path', () => { + let wss: WebSocketServer | undefined; + + 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) => { + ws.on('message', (data) => { + const frame = decode(data.toString()); + if (frame.type === 'hello') { + ws.send( + encode({ + type: 'manifest', + v: MESH_PROTOCOL_VERSION, + steps: [], + routes: [{ method: 'GET', pattern }], + }), + ); + } + }); + }); + return `ws://127.0.0.1:${(wss.address() as AddressInfo).port}/__mesh__/control`; + } + + it('the teacup splice fails and names the teapot', async () => { + const url = foreignTeapot('/__mesh__/:x'); + const teacup = createApp({ + modules: [moduleWith([[Get, '/ok']])], + experimental: true, + mesh: { teapots: [{ url, secret: 's' }] }, + }); + + try { + await expect(teacup.ready()).rejects.toThrow( + `mesh: remote route 'GET /__mesh__/:x' from ${url} uses the reserved path /__mesh__/control ` + + '(the mesh control channel)', + ); + } finally { + await teacup.close(); + } + }); +}); -- 2.54.1 From 9977d14605d45a3fd6e8d9f11bd53375742161ad Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 22 Oct 2026 23:55:24 -0500 Subject: [PATCH 2/2] test(router-parity): reserved mesh path refused on Node for CARD-21 (owner approval required) Golden update for ws-node-upgrade.json, needs owner approval (CARD-08 rule). The WS parity fixture declared @Ws('/__mesh__/control') to capture the old adapter split: the Node listener served it (101, the route's frame, close 1005), app.upgrade refused it (1008). Under D17 that route fails createApp, so the fixture drops it and keeps the path in UPGRADE_PATHS. The Node row now matches the app.upgrade row: 101, no frame, close 1008 with the shared reason. ws-app-upgrade.json is unchanged: app.upgrade already refused the path before matching, so removing the route does not change its answer. Signed-off-by: Diego Resendez --- test/router-parity/frozen/ws-node-upgrade.json | 11 +++-------- test/router-parity/ws.test.ts | 9 ++++----- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/test/router-parity/frozen/ws-node-upgrade.json b/test/router-parity/frozen/ws-node-upgrade.json index df82268..475e583 100644 --- a/test/router-parity/frozen/ws-node-upgrade.json +++ b/test/router-parity/frozen/ws-node-upgrade.json @@ -134,15 +134,10 @@ { "path": "/__mesh__/control", "status": 101, - "sent": [ - { - "id": "reserved", - "params": {} - } - ], + "sent": [], "close": { - "code": 1005, - "reason": "" + "code": 1008, + "reason": "mesh control channel not enabled: this app exports nothing, or has no mesh.secret" } } ] diff --git a/test/router-parity/ws.test.ts b/test/router-parity/ws.test.ts index f3bb3a1..492ff2c 100644 --- a/test/router-parity/ws.test.ts +++ b/test/router-parity/ws.test.ts @@ -3,7 +3,8 @@ * with no specificity ranking, an HTTP route at the same path never takes the upgrade, and the mesh * control path is checked before WS route matching. Captured through both upgrade entry points — * `app.upgrade` (Deno/Bun/edge) and the Node `server.on('upgrade')` listener — because they are - * separate code paths and do not agree on everything (see the reserved-path rows in the fixture). + * separate code paths. They used to disagree on the reserved mesh path; since CARD-21 (D17) both refuse + * it with the same 1008 close. */ import 'reflect-metadata'; import type { AddressInfo } from 'net'; @@ -40,10 +41,8 @@ class ParityWs { @Stream('/feed') feed() { return announce('feed', {}); } - // A user route on the reserved mesh path, on an app with no mesh: the two adapters disagree here. - @Ws('/__mesh__/control') reserved(@param() p: Record) { - return announce('reserved', p); - } + // No route on the reserved mesh path: since CARD-21 (D17) the boot refuses one. The path stays in + // UPGRADE_PATHS so both adapters' refusal on an app with no mesh is captured; they now agree. } @Module({ mountpoint: '/', controllers: [ParityWs] }) -- 2.54.1