fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s

The 1 MiB inbound cap from #107 applied to every WebSocket, the mesh
control channel included. An RPC carries a whole request body, so a body
inside maxBodyBytes could still overflow the cap once wrapped in an
rpc-req frame, and the teapot then closed the whole channel with 1009:
every request through that link failed 503 until it reconnected.

The test asked for by the card (T1, a 1 MB JSON body at defaults) passes
on Node, Deno and Bun, because a JSON body re-encodes to about its own
size. Two other cases fail on all three before this change:
- T1b: a 999 KB text body of quotes doubles under JSON escaping;
- T4: maxBodyBytes raised to 4 MB, a 3.9 MB JSON body.

The control channel's bound is now derived from the teapot's
limits.maxBodyBytes via controlFrameLimit(): MAX_FRAME_CHARS (4,000,000)
at the 1 MB default, scaled by the same ratio above it, never below
maxWsMessageBytes. No new option. User @Ws routes keep
maxWsMessageBytes: Node gets a second WebSocketServer for the control
path, app.upgrade picks the bound from the path before subscribing, and
Bun's single native maxPayloadLength is raised on a teapot only, leaving
app.upgrade to close user routes 1009 itself.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 00:03:11 -05:00
1 parent e565b1d4c9
commit 99ad996c2e
10 files changed
+525 -19

No files matched your search

+49 -11
View File
@@ -10,6 +10,7 @@ import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web';
import {
boundInbound,
controlLimits,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
@@ -44,7 +45,7 @@ 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, controlFrameLimit, createMeshControl, 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';
@@ -267,6 +268,7 @@ export function createApp(opts: {
orderedProviders,
orderedSteps,
deps: pipelineDeps,
maxBodyBytes: opts.limits?.maxBodyBytes,
});
};
@@ -331,7 +333,13 @@ export function createApp(opts: {
devRoutes,
() => remoteRoutes,
);
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
// Known at construction, unlike the control channel itself, because `app.upgrade` must bound a
// socket before it awaits the boot (#120).
const meshBounds = controlLimits(opts.limits, controlFrameLimit(opts.limits?.maxBodyBytes));
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
limits: opts.limits,
meshBounds,
});
const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps;
@@ -420,7 +428,7 @@ export function createApp(opts: {
};
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
[WS_MAX_MESSAGE_BYTES]: nativeWsBytes(opts.mesh, registry, opts.limits, meshBounds),
});
}
@@ -1225,6 +1233,21 @@ function makeAppBooter(
return once(runBoot);
}
/**
* The one inbound bound Bun applies natively to every socket (`WS_MAX_MESSAGE_BYTES`). A teapot
* raises it to its control channel's (#120); user routes still close at `maxWsMessageBytes`,
* because `app.upgrade` bounds them itself.
*/
function nativeWsBytes(
mesh: MeshConfig | undefined,
registry: Registry,
limits: RequestLimits | undefined,
meshBounds: { maxWsMessageBytes: number },
): number {
const servesControl = mesh?.secret && (registry.exportedSteps.length || registry.exportedRoutes.length);
return servesControl ? meshBounds.maxWsMessageBytes : wsMessageBytes(limits);
}
/**
* Builds the mesh control gateway that exposes this node's declared exports over the control channel.
* Returns undefined when there is nothing to export; throws if exports are declared without a gating secret.
@@ -1232,7 +1255,13 @@ function makeAppBooter(
function buildMeshControl(
mesh: MeshConfig | undefined,
registry: Registry,
deps: { container: Container; orderedProviders: GraphNode[]; orderedSteps: GraphNode[]; deps: PipelineDeps },
deps: {
container: Container;
orderedProviders: GraphNode[];
orderedSteps: GraphNode[];
deps: PipelineDeps;
maxBodyBytes?: number;
},
): MeshControl | undefined {
const { exportedSteps, exportedRoutes, routePlans, runners } = registry;
const hasExports = exportedSteps.length || exportedRoutes.length;
@@ -1303,7 +1332,14 @@ function buildMeshControl(
return result;
};
return createMeshControl({ secret: mesh.secret, manifest, resolveScope, resolveRoute, bus });
return createMeshControl({
secret: mesh.secret,
manifest,
resolveScope,
resolveRoute,
bus,
maxBodyBytes: deps.maxBodyBytes,
});
}
/** Compiles every non-ws route plan into an HTTP route that seeds and runs the pipeline, plus any remote routes. */
@@ -1395,7 +1431,7 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
bounds: { limits?: RequestLimits; meshBounds: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'> },
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
@@ -1404,10 +1440,8 @@ function buildAppUpgrade(
// with no subscriber is dropped, so anything the peer sends while providers are still booting
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
// hang until timeout against a teapot whose providers happened to boot slowly.
const ready = boundInbound(socket, limits);
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
// The path comes first, though, because it decides the bound: the mesh control channel carries
// whole request bodies and is bounded by the body limit, not `maxWsMessageBytes` (#120).
let path: string;
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
@@ -1415,10 +1449,14 @@ function buildAppUpgrade(
try {
path = normalizeRequestPath(request.url.split('?')[0]);
} catch {
ready.close(1008, 'invalid request path');
socket.close(1008, 'invalid request path');
return;
}
const ready = boundInbound(socket, path === MESH_CONTROL_PATH ? bounds.meshBounds : bounds.limits);
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
const meshControl = getMeshControl();
// The reserved mesh path, checked before route matching: this is what lets a teapot export