fix(mesh): bound the control channel by maxBodyBytes and its own queue, not the user ws limits (CARD-24, #120, #148) #142

Merged
chrnx merged 4 commits from feature/fprd-001c-ws-mesh-body into develop 2026-10-23 06:20:08 +00:00
Owner

Card CARD-24 (FPRD-001c), decision D22, issue #120. Also fixes #148 (owner decision 2026-10-23: fix it before the freeze, in this PR) in its own commit.

Owner decision 2026-10-23: keep the #120 fix (T4 proves the bug).

Outcome of the test-first step

The card's T1 (remote RPC, ~1,000,000 B JSON body, defaults) passes on Node, Deno and Bun: a JSON body re-encodes to about its own size inside the rpc-req envelope, which stays under 1 MiB.

The issue's concern is still real, though. Two cases fail on all three runtimes before this change, with the teapot closing the whole control channel 1009 and every request through that link answering 503 until it reconnects:

Case Before After
T1 — 1 MB JSON body, defaults 200 (Node/Deno/Bun) 200
T1b — 999 KB text/plain body of " (JSON escaping doubles it to ~2 MB) 503, channel closed (Node/Deno/Bun) 200, channel open
T2 — body > maxBodyBytes 413 413, channel open
T3 — user @Ws route on the same teapot, frame > 1 MiB 1009 1009 (Node/Deno/Bun)
T4 — maxBodyBytes: 4 MB, 3.9 MB JSON body 503, channel closed (Node/Deno/Bun) 200
T1c — 999 KB text/plain body of U+0001 (each escapes to 6 chars, ~6 MB frame) 503 (also with the first version of this PR) 200, channel open

T4 is one of the card's own test cases, so I applied the fix the card describes (step 3). Owner check: T1 as literally written passes, so if you would rather keep #120 test-only, the tests here document T1b/T4 as known failures and the src/ changes can be dropped.

What changed

  • src/mesh/teapot.ts: controlFrameLimit(maxBodyBytes) = 6 × maxBodyBytes + 1 MiB (7,048,576 at the 1 MB default). Six is the worst growth of any body byte inside the JSON envelope: a control character escapes to \u00XX. By comparison, quotes and backslashes double, JSON numbers like 1e20 grow about 5×, multipart Buffers at most 4×, and non-ASCII text is not escaped. The 1 MiB covers headers, params, query, url and the envelope. This replaces the fixed MAX_FRAME_CHARS = 4,000,000, after review P1 #1, in commit "size control frames for the worst escaping". createMeshControl takes an optional maxBodyBytes in its deps and returns maxFrameBytes.
  • src/http/ws-core.ts: controlBounds(limits, maxFrameBytes) returns the control channel's two phases of bounds (see the pre-auth section below).
  • Node (src/http/ws.ts): the control path gets its own WebSocketServer with that maxPayload, so user routes keep maxWsMessageBytes on the pre-buffer check too.
  • app.upgrade (Deno/Bun/edge): the path is normalized before boundInbound, because the path decides the bound. Inbound is still subscribed before the boot is awaited. An invalid path now closes on the raw socket; same code and reason.
  • Bun (src/bun.ts, WS_MAX_MESSAGE_BYTES): Bun has one native maxPayloadLength for every socket, so only on a teapot (secret plus exports) it is raised to the control bound. User routes on that teapot are then held to maxWsMessageBytes by app.upgrade, so they close with a real 1009 on every Bun version, where Bun < 1.4 natively dropped the connection (1006). Non-teapot apps are unchanged (the ws.test.ts / #135 assertions are untouched).
  • No new user option. limits.maxWsMessageBytes still governs every user @Ws route.

#148: the control channel's queue bound (second commit)

The control channel also inherited limits.maxWsQueue (16, close 1013). On Node, ws emits every frame of one socket read synchronously, so 17 or more RPCs leaving a teacup together tripped the teapot's queue: the link dropped and every pending request got 503. A teapot on Deno or Bun didn't trip, even with a 1,000-RPC burst, because those runtimes deliver one frame per task.

  • controlBounds() (authenticated phase) now also sets the control channel's maxWsQueue to 4,096 frames, or maxWsQueue if larger. It is an internal constant (CONTROL_QUEUE in ws-core.ts) with no option.
  • Why 4,096: the teapot's frame loop never awaits between frames, so the queue only ever holds one delivery burst. One Node read is at most 64 KiB, which holds fewer than 4,096 of the smallest control frame ({"type":"ping"}).
  • It stays finite, so a peer flooding a channel nobody is reading (for example during a slow boot) is still cut off.
  • Bursts of 2,000 RPCs pass on Node.
  • New tests on Node, Deno and Bun:
    • 64 RPCs sent in one tick through app.fetch on one link all answer 200. This was red on Node before the fix. Over HTTP sockets the requests trickle in and do not reproduce the burst.
    • A user @Ws route on the same teapot still closes 1013 on its 17th unread frame.

Pre-auth exposure: phased bounds (review P1 #2, last commit)

boundInbound runs before ensureBooted() and before the hello is checked. With 4,096 queued frames × a 7 MB frame cap and nothing reading during a slow boot, an unauthenticated peer could make the process buffer tens of GB.

Chosen: auth-phased bounds, not a total-bytes cap. The only unauthenticated frame with a purpose is the hello, and phasing keeps the trusted path free of a second accounting rule.

  • Until the hello is accepted: frames of at most HELLO_FRAME_BYTES (64 KiB) and the default 16-frame queue, so about 1 MiB per connection. The peer is closed with 1009 or 1013 past that.
  • After: the #120 frame bound and the #148 queue bound.
  • Mechanism: boundInbound(socket, limits, widened?) keeps a switch on the bounded socket under a Symbol.for key, and the teapot calls widenInbound(socket) when the handshake succeeds. The teapot's own parse check is phased the same way, so a standalone createMeshControl is covered too.
  • Residual on Node: the control path's native maxPayload stays at the authenticated bound, because ws can't change it per phase. A pre-auth peer can make ws assemble one frame up to 7 MB before boundInbound closes it with 1009. That frame is transient and never queued.
  • Tests:
    • During a delayed boot via app.upgrade, a 1 MB pre-auth frame closes 1009 at once.
    • During a delayed boot, a flood closes 1013 within 17 frames.
    • After the hello, large frames and a 64-ping burst are accepted.
    • On Node, Deno and Bun, an unauthenticated 1 MB frame over a real socket closes 1009.
    • The #148 64-RPC test stays green.

Unsure / owner questions

  1. Public surface (for CARD-22's API report): createMeshControl deps gain optional maxBodyBytes, and its return gains maxFrameBytes. The internal MeshControl type gains optional maxFrameBytes. All additive. boundInbound, widenInbound, controlBounds and HELLO_FRAME_BYTES live in internal ws-core and are not exported from the package index.
  2. The bound comes from the teapot's own limits.maxBodyBytes. Per-route maxBodyBytes overrides on exported routes are not included: the teacup enforces its own server limit for remote routes, since the manifest carries no per-route limit. Teacup and teapot need matching limits, as in T4.
  3. The frame bound now covers the worst escaping (6×), so every body within maxBodyBytes fits. Headers count against the 1 MiB headroom: Node caps them at 16 KiB, and escaping can at most multiply that by 6.
  4. Side observation: on Deno, a @Ws route that yields before the socket opens saw a 1005 close. This is a pre-existing pump bug, explained and fixed in #147 (CARD-26). The T3 test here uses a reading route.

Test evidence (after rebase on develop @ e565b1d)

  • npm run lint: 0 errors (51 warnings, all no-explicit-any. The +1 over develop is meshWss: any, which mirrors the existing wss: any.)
  • npm run format:check: clean
  • npm run typecheck: clean
  • npm test: 94 files, 927 tests passed
  • npm run build: ok
  • npm run complexity:check: every function ≤ 25
  • npm run test:deno: 45 passed, 0 failed (includes mesh-large-body.test.ts)
  • npm run test:bun: 35 pass, 0 fail
  • npm run test:edge: PASS (HTTP/WS limits, router parity)
  • npm audit --audit-level=moderate: 0 vulnerabilities

New tests: test/mesh/large-body.test.ts (Node), test/deno/mesh-large-body.test.ts, test/bun/mesh-large-body.test.ts. The Bun T2 posts the over-limit body through app.fetch to avoid the known socket race on early 413s (see body-limits.test.ts).

Docs follow-up (CARD-12)

  • guides/mesh.md: the control channel is bounded by the teapot's limits.maxBodyBytes (6 × the limit + 1 MiB, so 7,048,576 B at the default) after authentication, and by 64 KiB / 16 frames before it, not limits.maxWsMessageBytes. Teacup and teapot should agree on maxBodyBytes.
  • WebSocket limits page: on a Bun teapot, an oversized user-route frame closes 1009 (framework check), not Bun's native refusal.

The CHANGELOG has ### Fixed entries for #120 and #148.

Card **CARD-24** (FPRD-001c), decision **D22**, issue #120. Also fixes **#148** (owner decision 2026-10-23: fix it before the freeze, in this PR) in its own commit. **Owner decision 2026-10-23:** keep the #120 fix (T4 proves the bug). ## Outcome of the test-first step The card's T1 (remote RPC, ~1,000,000 B **JSON** body, defaults) **passes** on Node, Deno and Bun: a JSON body re-encodes to about its own size inside the `rpc-req` envelope, which stays under 1 MiB. The issue's concern is still real, though. Two cases **fail on all three runtimes** before this change, with the teapot closing the whole control channel `1009` and every request through that link answering `503` until it reconnects: | Case | Before | After | |---|---|---| | T1 — 1 MB JSON body, defaults | 200 (Node/Deno/Bun) | 200 | | T1b — 999 KB `text/plain` body of `"` (JSON escaping doubles it to ~2 MB) | **503**, channel closed (Node/Deno/Bun) | 200, channel open | | T2 — body > `maxBodyBytes` | 413 | 413, channel open | | T3 — user `@Ws` route on the same teapot, frame > 1 MiB | 1009 | 1009 (Node/Deno/Bun) | | T4 — `maxBodyBytes: 4 MB`, 3.9 MB JSON body | **503**, channel closed (Node/Deno/Bun) | 200 | | T1c — 999 KB `text/plain` body of U+0001 (each escapes to 6 chars, ~6 MB frame) | **503** (also with the first version of this PR) | 200, channel open | T4 is one of the card's own test cases, so I applied the fix the card describes (step 3). **Owner check:** T1 as literally written passes, so if you would rather keep #120 test-only, the tests here document T1b/T4 as known failures and the `src/` changes can be dropped. ## What changed - `src/mesh/teapot.ts`: `controlFrameLimit(maxBodyBytes)` = **6 × `maxBodyBytes` + 1 MiB** (7,048,576 at the 1 MB default). Six is the worst growth of any body byte inside the JSON envelope: a control character escapes to `\u00XX`. By comparison, quotes and backslashes double, JSON numbers like `1e20` grow about 5×, multipart `Buffer`s at most 4×, and non-ASCII text is not escaped. The 1 MiB covers headers, params, query, url and the envelope. This replaces the fixed `MAX_FRAME_CHARS = 4,000,000`, after review P1 #1, in commit "size control frames for the worst escaping". `createMeshControl` takes an optional `maxBodyBytes` in its deps and returns `maxFrameBytes`. - `src/http/ws-core.ts`: `controlBounds(limits, maxFrameBytes)` returns the control channel's two phases of bounds (see the pre-auth section below). - Node (`src/http/ws.ts`): the control path gets its own `WebSocketServer` with that `maxPayload`, so user routes keep `maxWsMessageBytes` on the pre-buffer check too. - `app.upgrade` (Deno/Bun/edge): the path is normalized **before** `boundInbound`, because the path decides the bound. Inbound is still subscribed before the boot is awaited. An invalid path now closes on the raw socket; same code and reason. - Bun (`src/bun.ts`, `WS_MAX_MESSAGE_BYTES`): Bun has one native `maxPayloadLength` for every socket, so **only on a teapot** (secret plus exports) it is raised to the control bound. User routes on that teapot are then held to `maxWsMessageBytes` by `app.upgrade`, so they close with a real `1009` on every Bun version, where Bun < 1.4 natively dropped the connection (`1006`). Non-teapot apps are unchanged (the `ws.test.ts` / #135 assertions are untouched). - No new user option. `limits.maxWsMessageBytes` still governs every user `@Ws` route. ## #148: the control channel's queue bound (second commit) The control channel also inherited `limits.maxWsQueue` (16, close `1013`). On Node, `ws` emits every frame of one socket read synchronously, so 17 or more RPCs leaving a teacup together tripped the teapot's queue: the link dropped and every pending request got 503. A teapot on Deno or Bun didn't trip, even with a 1,000-RPC burst, because those runtimes deliver one frame per task. - `controlBounds()` (authenticated phase) now also sets the control channel's `maxWsQueue` to **4,096 frames, or `maxWsQueue` if larger**. It is an internal constant (`CONTROL_QUEUE` in `ws-core.ts`) with no option. - Why 4,096: the teapot's frame loop never awaits between frames, so the queue only ever holds one delivery burst. One Node read is at most 64 KiB, which holds fewer than 4,096 of the smallest control frame (`{"type":"ping"}`). - It stays finite, so a peer flooding a channel nobody is reading (for example during a slow boot) is still cut off. - Bursts of 2,000 RPCs pass on Node. - New tests on Node, Deno and Bun: - 64 RPCs sent in one tick through `app.fetch` on one link all answer 200. This was red on Node before the fix. Over HTTP sockets the requests trickle in and do not reproduce the burst. - A user `@Ws` route on the same teapot still closes `1013` on its 17th unread frame. ## Pre-auth exposure: phased bounds (review P1 #2, last commit) `boundInbound` runs before `ensureBooted()` and before the `hello` is checked. With 4,096 queued frames × a 7 MB frame cap and nothing reading during a slow boot, an unauthenticated peer could make the process buffer tens of GB. **Chosen: auth-phased bounds, not a total-bytes cap.** The only unauthenticated frame with a purpose is the hello, and phasing keeps the trusted path free of a second accounting rule. - **Until the hello is accepted:** frames of at most `HELLO_FRAME_BYTES` (64 KiB) and the default 16-frame queue, so about 1 MiB per connection. The peer is closed with `1009` or `1013` past that. - **After:** the #120 frame bound and the #148 queue bound. - **Mechanism:** `boundInbound(socket, limits, widened?)` keeps a switch on the bounded socket under a `Symbol.for` key, and the teapot calls `widenInbound(socket)` when the handshake succeeds. The teapot's own parse check is phased the same way, so a standalone `createMeshControl` is covered too. - **Residual on Node:** the control path's native `maxPayload` stays at the authenticated bound, because `ws` can't change it per phase. A pre-auth peer can make `ws` assemble one frame up to 7 MB before `boundInbound` closes it with 1009. That frame is transient and never queued. - **Tests:** - During a delayed boot via `app.upgrade`, a 1 MB pre-auth frame closes 1009 at once. - During a delayed boot, a flood closes 1013 within 17 frames. - After the hello, large frames and a 64-ping burst are accepted. - On Node, Deno and Bun, an unauthenticated 1 MB frame over a real socket closes 1009. - The #148 64-RPC test stays green. ## Unsure / owner questions 1. **Public surface (for CARD-22's API report):** `createMeshControl` deps gain optional `maxBodyBytes`, and its return gains `maxFrameBytes`. The internal `MeshControl` type gains optional `maxFrameBytes`. All additive. `boundInbound`, `widenInbound`, `controlBounds` and `HELLO_FRAME_BYTES` live in internal `ws-core` and are not exported from the package index. 2. The bound comes from the **teapot's own** `limits.maxBodyBytes`. Per-route `maxBodyBytes` overrides on exported routes are not included: the teacup enforces its own server limit for remote routes, since the manifest carries no per-route limit. Teacup and teapot need matching limits, as in T4. 3. The frame bound now covers the worst escaping (6×), so every body within `maxBodyBytes` fits. Headers count against the 1 MiB headroom: Node caps them at 16 KiB, and escaping can at most multiply that by 6. 4. Side observation: on Deno, a `@Ws` route that yields before the socket opens saw a `1005` close. This is a pre-existing pump bug, explained and fixed in #147 (CARD-26). The T3 test here uses a reading route. ## Test evidence (after rebase on develop @ e565b1d) - `npm run lint`: 0 errors (51 warnings, all `no-explicit-any`. The +1 over develop is `meshWss: any`, which mirrors the existing `wss: any`.) - `npm run format:check`: clean - `npm run typecheck`: clean - `npm test`: 94 files, 927 tests passed - `npm run build`: ok - `npm run complexity:check`: every function ≤ 25 - `npm run test:deno`: 45 passed, 0 failed (includes `mesh-large-body.test.ts`) - `npm run test:bun`: 35 pass, 0 fail - `npm run test:edge`: PASS (HTTP/WS limits, router parity) - `npm audit --audit-level=moderate`: 0 vulnerabilities New tests: `test/mesh/large-body.test.ts` (Node), `test/deno/mesh-large-body.test.ts`, `test/bun/mesh-large-body.test.ts`. The Bun T2 posts the over-limit body through `app.fetch` to avoid the known socket race on early 413s (see `body-limits.test.ts`). ## Docs follow-up (CARD-12) - `guides/mesh.md`: the control channel is bounded by the teapot's `limits.maxBodyBytes` (6 × the limit + 1 MiB, so 7,048,576 B at the default) after authentication, and by 64 KiB / 16 frames before it, not `limits.maxWsMessageBytes`. Teacup and teapot should agree on `maxBodyBytes`. - WebSocket limits page: on a Bun teapot, an oversized user-route frame closes `1009` (framework check), not Bun's native refusal. The CHANGELOG has `### Fixed` entries for #120 and #148.
chrnx force-pushed feature/fprd-001c-ws-mesh-body from c40e6ebf1b to 99ad996c2e 2026-10-23 05:03:15 +00:00 Compare
chrnx changed title from fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120) to fix(mesh): bound the control channel by maxBodyBytes and its own queue, not the user ws limits (CARD-24, #120, #148) 2026-10-23 05:30:45 +00:00
Author
Owner

Implementation review done on 2026-10-23: a Codex review of all 12 sprint PRs, with each finding verified. The P1s in #142 and the P3 in #149 are fixed. The owner (Chrnx) authorized merging in order, each one rebased on develop with CI green. This supersedes the earlier "not merging yet" note.

Implementation review done on 2026-10-23: a Codex review of all 12 sprint PRs, with each finding verified. The P1s in #142 and the P3 in #149 are fixed. The owner (Chrnx) authorized merging in order, each one rebased on develop with CI green. This supersedes the earlier "not merging yet" note.
chrnx force-pushed feature/fprd-001c-ws-mesh-body from bd85bf67bc to f62a791afc 2026-10-23 06:11:33 +00:00 Compare
chrnx force-pushed feature/fprd-001c-ws-mesh-body from f62a791afc to dcbfafd47b 2026-10-23 06:14:29 +00:00 Compare
chrnx added 4 commits 2026-10-23 06:17:41 +00:00
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>
The control channel also inherited limits.maxWsQueue (16 undelivered
frames, close 1013) from #107. On Node, ws emits every frame of one
socket read synchronously, so a teacup with more than 16 RPCs in flight
sent a burst the teapot's queue refused: the link dropped and every
pending request failed 503. Deno and Bun deliver one frame per task and
did not trip.

controlLimits() now also raises maxWsQueue for the control channel, to
an internal 4,096 frames or maxWsQueue if larger, alongside the size
bound from #120. The teapot's frame loop never awaits between frames, so
the queue only holds one delivery burst, and one read (at most 64 KiB)
holds fewer than 4,096 of the smallest control frame. The bound stays
finite, so a peer flooding a channel nobody is reading is still cut off.
No new option. User @Ws routes keep closing 1013 at maxWsQueue.

Tests: 64 RPCs in one tick through app.fetch on one link all answer 200
(red on Node before), and a user route on the same teapot still closes
1013, on Node, Deno and Bun.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
A 999,000-byte text/plain body of U+0001, within maxBodyBytes, still
failed 503: the envelope carries a text body as a JSON string, each
control character escapes to six characters, and the ~6 MB frame was
over the 4,000,000 the channel was sized to.

controlFrameLimit() is now 6 x maxBodyBytes plus 1 MiB for headers,
params, query and the envelope: 7,048,576 at the 1 MB default. Six is
the worst growth of any body byte; quotes and backslashes double, JSON
numbers like 1e20 grow about fivefold, multipart Buffers at most
fourfold, and non-ASCII text is not escaped. The fixed MAX_FRAME_CHARS
goes away with it.

Test (T1c) on Node, Deno and Bun: the control-character body now
answers 200 and the channel stays open.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
fix(mesh): hold the control channel to hello size until the peer authenticates
CI / runtimes (bun) (pull_request) Successful in 18s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 24s
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
8f73779a21
boundInbound(socket, meshBounds) runs before ensureBooted() and before
the hello is checked, and meshBounds allowed 4,096 queued frames of up
to 7 MB each. During a slow boot nothing reads that queue, so an
unauthenticated peer could make the process buffer tens of GB.

The control channel's bounds are now phased (controlBounds() replaces
controlLimits()):
- until the hello is accepted: frames of at most HELLO_FRAME_BYTES
  (64 KiB) and the default 16-frame queue, so about 1 MiB per
  connection;
- after: the frame bound from #120 and the queue bound from #148.

boundInbound takes the second set as an optional `widened` argument and
keeps the switch on the bounded socket under a Symbol.for key. The
teapot calls widenInbound() when the handshake succeeds. The teapot's
own parse check follows the same phases, so a standalone
createMeshControl also refuses a pre-auth frame over hello size.

This is an auth-phased bound rather than a total-bytes cap: the only
unauthenticated frame with a purpose is the hello, and phasing keeps
the trusted path free of a second accounting rule. No new option.

On Node the control path's native maxPayload stays at the authed bound,
because ws cannot change it per phase. A pre-auth peer can still make
ws assemble one frame of up to that size before boundInbound closes
the connection with 1009. That frame is transient and never queued.

Tests: during a delayed boot, a 1 MB pre-auth frame closes 1009 at once
and a flood closes 1013 within 17 frames; after the hello, large frames
and a 64-ping burst are accepted. On Node, Deno and Bun, an
unauthenticated 1 MB frame over a real socket closes 1009. The #148
64-RPC test stays green.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
chrnx force-pushed feature/fprd-001c-ws-mesh-body from dcbfafd47b to 8f73779a21 2026-10-23 06:17:41 +00:00 Compare
chrnx merged commit 567b5e134f into develop 2026-10-23 06:20:08 +00:00
chrnx deleted branch feature/fprd-001c-ws-mesh-body 2026-10-23 06:20:10 +00:00
Sign in to join this conversation.