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 <diego.resendez@zero-oneit.com>
This commit is contained in:
10 files changed
+478
-7
No files matched your search
+28
-3
@@ -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<void> => {
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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.',
|
||||
);
|
||||
}
|
||||
@@ -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) {
|
||||
|
||||
+13
-1
@@ -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.
|
||||
*
|
||||
|
||||
Reference in new issue
Block a user