Commit Graph
218 Commits
Author SHA1 Message Date
chrnx 8f73779a21 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
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>
2026-10-23 01:16:43 -05:00
chrnx e98d5d33eb fix(mesh): size control frames for the worst escaping a body can get (#120)
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>
2026-10-23 01:16:43 -05:00
chrnx cad81223e5 fix(mesh): give the control channel its own inbound queue bound (#148)
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>
2026-10-23 01:16:43 -05:00
chrnx 713122d53a fix(mesh): bound the control channel by maxBodyBytes, not the 1 MiB ws cap (CARD-24, #120)
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>
2026-10-23 01:16:43 -05:00
chrnx 3296189093 feat(http): response compression with gzip and br (CARD-16, #112)
CI / runtimes (edge) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 17s
CI / build (pull_request) Successful in 28s
CI / runtimes (deno) (pull_request) Successful in 23s
Text responses went out uncompressed unless a proxy sat in front of every
runtime. createApp({ compression: true | { threshold, encodings } }), off
by default, implements D13 strategy B as accepted on 2026-10-22.

- One function, compressOutcome, runs after handle() and before either
  adapter writes, so Node and the fetch runtimes cannot diverge.
- Accept-Encoding negotiation with q-values, identity, * and q=0; ties go
  to server preference (br before gzip). Vary: Accept-Encoding is merged
  wherever the request decided the outcome, including every 304. Skips:
  existing Content-Encoding or Content-Range, no or an incompressible
  Content-Type (ndjson is compressible), Cache-Control: no-transform.
  HEAD and bodies under threshold keep Vary; 204 gets none.
- Node, Deno, Bun: node:zlib only, loaded lazily through nodeRequire.
  Buffered bodies use the async API, never the sync one; br at quality 4.
  Content-Length is dropped from an encoded body.
- Streams (SSE, ndjson): a zlib stream flushed after every frame, error
  frame and ping, piped into res on Node and wrapped around the
  ReadableStream on fetch runtimes. Backpressure follows the compressor;
  a client leaving destroys it.
- Edge: core never encodes and sets Vary only. Edge is recognised by
  edgeHandler, which marks the app through an internal symbol, and by
  createApp detecting workerd (navigator.userAgent, or node:zlib failing
  to load), which covers a bare app.fetch export.
- ETags from CARD-15 are taken on the identity body and stay weak, so the
  tag does not change with the coding.

Deno runs zlib's async API on the main thread; that is documented and
pinned by a test, not worked around.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:12:48 -05:00
chrnx d32fc9f8d7 feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 13s
CI / build (pull_request) Successful in 27s
Conditional GETs were never answered: every revalidation re-downloaded
the file or response.

- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
  Last-Modified and Cache-Control from the stat the resolver already did.
  A matching If-None-Match, or If-Modified-Since when If-None-Match is
  absent, answers 304 before the file is read. StaticHit now carries the
  stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
  no-cache so browsers revalidate rather than reuse a file for a lifetime
  guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
  to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
  plus its length, computed before HEAD blanks the body. A handler-set
  etag is kept and only compared. Weak comparison, lists split outside
  quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
  dropped, so NotModified matches the ETag path on every adapter.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:09:54 -05:00
chrnx 7f9a0eef0f feat(http)!: cookie decorators, setCookie, and string | string[] response headers (CARD-14, #113)
CI / runtimes (edge) (pull_request) Successful in 14s
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
Reading a cookie meant parsing the Cookie header by hand, and a response
could not carry more than one Set-Cookie: response header values were
Record<string, string>, and the fetch adapters would have stringified an
array into one broken "a,b" cookie anyway.

- @cookie('name') / @cookies() sit next to @header/@headers as a new
  'cookies' arg source. The header is parsed on first use per request and
  cached on the context, so a route without a cookie argument never parses
  it. RFC 6265: first value wins, %-sequences decoded, malformed pairs
  skipped (never a 400), undecodable values kept raw. Several cookie lines
  are joined with "; ". The map has no prototype. @needs('cookies') reads
  the same map, and 'cookies' joins the seed-key allow-list.
- setCookie(name, value, options) serialises one Set-Cookie value with
  HttpOnly, SameSite=Lax, Path=/ and Secure by default (D10), and throws,
  naming the field, on anything that could inject a header or that browsers
  reject (sameSite none / partitioned without secure).
- Response header values widen to string | string[] (D11) across
  TransformerFn, ErrorResponse, HttpError(Like).headers, ResponseShape and
  the neutral outcome. Node writes a set-cookie array as one line per
  element and joins every other array with ", " before writeHead; the
  fetch adapters build a Headers and append each set-cookie element.
  mergeInjectedHeaders keeps arrays by reference and joins a vary array
  before merging it.
- OpenAPI maps a cookie argument to an in: cookie parameter.

BREAKING CHANGE: code that reads a header value from TransformerFn,
ErrorResponse, HttpError or ResponseShape as a string must handle string[].

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:08:24 -05:00
chrnx 9ea1365b66 test(router-parity): a late teapot is served after it connects for CARD-19 (owner approval required)
CI / runtimes (bun) (pull_request) Successful in 16s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
owner-mesh-lifetime.json froze phase B2 (teapot absent at boot, then up)
at 404 for GET and POST /api/remote/ping. The table was built once at
boot, so a late teapot was never spliced in. CARD-19 (#124, D15) changes
that. B2 now answers GET 200 {"from":"teapot"} and POST 405 with
Allow: GET, HEAD, OPTIONS, the same as A1.

Only those two entries change. A1, A2 and B1 are identical.

The fixture's teacup goes from reconnect: false to reconnect with a fast
backoff (20-60ms). Under D15, reconnect: false makes a dropped teapot
"gone" (404), and an absent one is not retried. The card's phases
describe the reconnecting teacup: A2 stays 503 and B2 becomes 200. B2
now waits for the mesh:routes event before probing. The fixture comment
and the corpus README line describing "built once at boot" are updated.

Owner approval required (CARD-08 rule): this edits a frozen file and the
fixture under test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:40 -05:00
chrnx 6bbd78fc8e feat(mesh): remote routes follow teapot membership (CARD-19, #124)
The teacup built its route table once at boot. A teapot that started
late was never served, and one that was gone for good stayed advertised.
Implement D15 (accepted 2026-10-18):

- A teapot that missed bootTimeoutMs is retried in the background with
  the reconnect backoff (not with reconnect: false). On connect its
  routes join the remote table. Its steps do not, because the graph
  was validated at boot without them.
- While a link is reconnecting, its routes stay and answer 503, now
  with retry-after (seconds until the next attempt).
- A link that gives up for good (dropped with reconnect: false, or a
  permanent refusal while reconnecting) has its routes removed: 404,
  and Allow drops its methods. A refused reconnect no longer retries
  forever.
- A returning manifest replaces the teapot's routes. missingFromManifest
  now checks steps only, so a dropped route is removed instead of
  refusing the reconnect.
- A late route that conflicts with another teapot's is refused and
  logged. The table keeps serving. At boot the same conflict still
  fails boot.
- Each change emits mesh:routes with { url, added, removed }.
- The reserved-path check from CARD-21/CARD-17 (#141, #145) runs in
  the table for every remote route: at boot a route on /__mesh__/control
  (or /__live__ and /__ready__ with health on) fails boot as before. A
  late or returning one is refused and logged, and the teapot's other
  routes are served.

Mechanics: the remote table publishes a new array per change
(copy-on-write). app.fetch and listen() share one table through a
getter, and buildFetch/createHttpServer read it once per request, so a
request sees the old table or the new one, never a mix. The router
reuses local trees when the local entries are identical, so a
membership change rebuilds only the remote trees. Dev routes now sit
before remote ones in the table to keep the local positions stable.

Tests cover T1-T8 on Node (test/mesh/membership.test.ts), plus the
local-tree build counter and late reserved-path routes, and T1/T2 on
Deno and Bun.

The frozen owner-mesh-lifetime.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 01:04:39 -05:00
chrnx ae9e5529e8 test(router-parity): HEAD on a remote GET answers 200 for CARD-20 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / runtimes (deno) (pull_request) Successful in 20s
owner-mesh-allow.json froze HEAD /api/x at 404 on both adapters: the
teacup forwarded HEAD to the teapot, which has no HEAD plan for the
route. CARD-20 (#125, D16) fixes that, so HEAD now answers 200 with the
GET's headers and an empty body, like a local route.

Only those two entries change (fetch and node), status 404 -> 200.
Headers and the empty body are identical. The fixture comment in
owner.test.ts that described the old behaviour is updated to match.

Owner approval required (CARD-08 rule): this edits a frozen file under
test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx 5783212377 fix(mesh): answer HEAD on a remote GET route (CARD-20, #125)
The teacup's router resolves HEAD to a remote buffered GET through the
implicit-HEAD fallback, and OPTIONS advertises HEAD. But the remote
route handler forwarded req.method, so the teapot got a HEAD envelope,
found no HEAD plan in resolveRoute, and answered 404.

Forward a HEAD that matched a remote GET as GET. dispatch already drops
the body for HEAD, so the client gets the GET's status and headers and
no body, the same as a local route. An explicit remote HEAD route is
matched first and is still forwarded as HEAD.

The fix is teacup-side (D16, accepted 2026-10-22): the teapot and the
wire protocol are unchanged, so a new teacup works against an older
teapot during a rolling deploy.

Tests cover app.fetch and the Node listener (200 + GET headers + empty
body, OPTIONS, explicit HEAD precedence, 404/500 kept with no body, the
teapot handler called once as GET) and Deno and Bun.

The frozen owner-mesh-allow.json capture changes in the next commit.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:59:56 -05:00
chrnx f0530b15bb feat(http): liveness and readiness probes with a drain window (CARD-17, #115)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 14s
createApp({ health: true }) serves GET/HEAD /__live__ and /__ready__.
Ready reports booting until boot() resolves, ok or degraded (from
app.degraded()) after that, and draining from the moment close() starts.

Probes are answered by the adapters, ahead of the request gate and of
handle(): Node in serve() (src/http/server.ts), the Fetch path in
app.fetch before it awaits the boot. Otherwise ready could never say
booting. Being ahead of the gate means maxConcurrentRequests never sheds
a probe (D14). Being ahead of handle() means no step, provider, plugin or
onError runs, and no lifecycle event is emitted, so logRequests and
metrics never see a probe. Security headers still apply, plus
cache-control: no-store. Other methods get 405 with Allow: GET, HEAD.

A probe through app.fetch before any boot starts the boot without
awaiting it. On the edge, or under a bare Deno.serve(app.fetch), nothing
else may boot the app, and an orchestrator that waits for ready before
sending traffic would wait forever.

health: { drainDelayMs } (D14) marks the app draining and keeps the
listener open for that long before connections drain. Without it, Node
closes idle keep-alive sockets at once, and a probe sees a reset rather
than the 503. The window is spent out of the close budget. serveDeno and
serveBun start the same window, through a symbol-keyed hook on the app,
before server.shutdown() / server.stop(false). workerd has no close(),
so it never reports draining.

While health is on, /__live__ and /__ready__ join the reserved-path
boot check that CARD-21 introduced, for local and mesh-spliced routes.
Invalid health values throw at createApp.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:57:10 -05:00
chrnx 9977d14605 test(router-parity): reserved mesh path refused on Node for CARD-21 (owner approval required)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
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 <diego.resendez@zero-oneit.com>
2026-10-23 00:53:55 -05:00
chrnx 2c00cc3407 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>
2026-10-23 00:53:55 -05:00
chrnx 56f953f0bb feat(graph)!: fail boot when a token has a second producer (CARD-18, GitHub #35)
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
topoSort, topoLevels and subgraphFor built their token -> node map with
producedBy.set(key, node), so the last node registered for a token won.
Plugin nodes are registered after module nodes, which let a plugin's
scope.add({ name: 'shadow', provides: ['user'] }) silently replace the
app's own @Provider({ provides: 'user' }) for every route that needed
it. setRunner only rejects duplicate names, and scope.add is the one
path where a name and its tokens differ.

D9 settles it graph-wide: topoSort now throws when a token already has
a producer, naming both nodes and their origins (module:..., plugin,
mesh:<url>, builtin). One check on the whole node set covers every
current and future registration path. It also protects the built-ins
(logger, rooms, events) by rule rather than by registration order.
topoSort runs at finalize, after the mesh splice, so remote steps are
checked too. topoLevels and subgraphFor only ever see nodes topoSort
has already validated, so they keep their plain maps.

overrides replace the runner of an existing token and add no node, so
they are unaffected. Steps that provide nothing (plugin observers) are
not producers. The official plugins (jwt, metrics, rate-limit) pass
their suites against this build.

BREAKING CHANGE: an app whose graph has two nodes providing one token,
  e.g. a plugin scope node providing a token a module or built-in
  already provides, now fails createApp instead of letting the later
  node win.
Refs: GitHub #35

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:50:26 -05:00
chrnx 88cbe41f72 feat(edge)!: trust cf-connecting-ip only under trustProxy, for HTTP and WebSocket (CARD-23, #119)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
edgeHandler copied cf-connecting-ip into ctx.ip on every WebSocket
upgrade, so any client that sent the header chose its own address, and
it never read the header for HTTP, so IP-keyed plugins saw '' there.
D21 settles both: the header counts only under trustProxy, on both
paths, with no new option.

The adapter cannot make that call, because trustProxy is an app option.
So edgeHandler records the header against the object it hands the app
(the Request for HTTP, the WsRequest for an upgrade) in an internal
registry next to the Deno/Bun peer one, and app.fetch and app.upgrade
both consult it through one helper, trustedProxyClient(), which returns
'' unless trustProxy is on. Under trustProxy it takes precedence over
x-forwarded-for, since Cloudflare sets it itself and XFF can carry
client-supplied hops.

Nothing else records into the registry, so the Node, Deno and Bun
adapters, and a bare app.fetch or app.upgrade, ignore the header as
before.

BREAKING CHANGE: an edge WebSocket upgrade no longer takes ctx.ip from
  cf-connecting-ip unless the app sets trustProxy: true; without it,
  ctx.ip is ''.
Refs: #119

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:47:58 -05:00
chrnx 8bf54ec168 fix(http): keep every ? after the first in the query string (CARD-25, GitHub #48)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
parseQuery took `url.split('?')[1]`, so a second `?` ended the query
string and `/search?q=what?now` gave `q: 'what'`. RFC 3986 §3.4 allows
`?` inside a query. The query string is now everything after the first
`?` and before `#`, if one is present. The early return for URLs without
a query is kept, and so is its measurement note. The comment that
deferred this behaviour question is removed because the question is now
decided (D23).

Path extraction already split on the first `?` and is unchanged.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-23 00:02:42 -05:00
chrnxandClaude Opus 5.5 69bdc8adec test(bun): expect 1009 for oversized WebSocket frames on Bun 1.4+
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 27s
CI picked up Bun 1.4.4 (`oven-sh/setup-bun@v2`, latest), which now sends a
real `1009` close frame when `maxPayloadLength` refuses a frame. Bun 1.3
dropped the connection instead, so the peer saw `1006` — the difference D1
documented and these two assertions pinned on purpose so a Bun upgrade would
be noticed. It was: `runtimes (bun)` fails on develop.

The assertion now follows `Bun.version` (1006 before 1.4, 1009 from 1.4), so a
further change in either direction still fails. JSDoc, README and the #107
CHANGELOG entry say which Bun versions do what.

Verified with Bun 1.3.14 and 1.4.4 (26/26 each); lint, format, typecheck,
npm test.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-22 23:50:30 -05:00
chrnx 63f60134ea feat(router)!: fail boot on unreachable or ambiguous constrained params
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
Before, when two sibling routes could match the same request, the router
picked one by registration order or precedence, and nothing reported it.
Boot now refuses two cases between routes of the same method that branch at
the same segment under the same prefix:

- ambiguous: both params are constrained, the constraints accept a common
  segment, and the rest of both patterns can match one request. The error
  names both declarations and a witness segment with an example path.
- unreachable: a plain param sits next to a constraint that accepts every
  segment, and the constraint wins every request the plain param could take.

A plain param next to a constraint that leaves some segments over is the
documented fallback pattern and still boots.

The check is exact. assertSafeConstraint admits only a linear, group-free
subset, so every constraint reads back as a sequence of (character set, min,
max) blocks. Atom sets follow u-flag semantics. \p{...} is the one construct
that is not modelled, and for it the engine is asked once per code point. A
product walk over two block sequences finds a common segment, or proves none
exists, in O(|A|*|B|*(|A|+|B|)*K) with K <= 2048. "Accepts every segment" is
a closed-form test on the blocks. Both are measured against what the router
hands a param: a decoded, non-empty segment that is never "." or "..".

The check runs per table under that table's own precedence. HTTP ranks by
specificity. WebSocket takes the first declared match. @Stream routes sit in
both tables. Routes exported by different teapots are checked against each
other. Local against remote keeps the local override and its warning.

The lookup path is unchanged. router.ts only exports the two token regexes,
so the boot check and assertSafeConstraint read atoms the same way.

BREAKING CHANGE: an app that declares two overlapping constrained siblings
  (e.g. /u/:id(\d+) and /u/:n(\d{1,3})), or a plain param beside a constraint
  that accepts every segment, now fails createApp. So do a plain WebSocket param
  declared before a constrained sibling, and such pairs across mesh teapots.
Refs: #127
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 16:07:58 -05:00
chrnx e41d9560ba test(router-parity): make the app fixture's hex route disjoint for CARD-13 (owner approval required)
The frozen app fixture declares GET /n/:num(\d+) and GET /n/:code([0-9a-f]+).
Both constraints accept digits, so CARD-13 (#127) makes this pair a boot error,
and the fixture app could no longer start. That would fail app-fetch.json and
app-node.json, and the Deno, Bun and workerd parity runs that boot the same app.

Narrow nCode to [a-f]+. The two frozen requests on this pair still get the
captured answers: /n/42 goes to nNum and /n/ff goes to nCode, with the same
params. No frozen JSON file changes.

What is lost at app level is the equal-rank registration tie between two
overlapping constraints. CARD-13 now forbids that tie at boot. The tie stays
covered by matcher-hand.json, which calls the matcher without booting an app.

Owner approval required (CARD-08 rule): this edits a file under
test/router-parity/.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 16:07:15 -05:00
chrnx 7a9932f095 test(router): prove misses after index build recompile nothing (CARD-10, #109)
The linear matcher answered every 404, 405 and automatic OPTIONS by compiling
the whole route table. The radix index compiles each pattern once, when the
index for an array is built. Nothing asserted that, so a regression to
per-request compilation or per-request index builds would only show up as a
slower benchmark.

compilePattern is called inside router.ts, where a spy on the module export
cannot see it, so the router gains two internal counters (compilePattern calls,
index builds), exposed as @internal routerSeamCounts() next to walkStackSize.
router.ts is not a package entry. The new test warms the index, then repeats
404, 405 and OPTIONS misses through resolveRoute/allowedMethods, buildFetch and
app.fetch, and asserts both counts stay constant while status and Allow stay
correct.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 15:12:40 -05:00
chrnx fcee6892bf test(router): prove introspection parity after the radix index (CARD-09, #109)
CI / dco (pull_request) Successful in 3s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
The frozen CARD-08 goldens already hold graph(), explain(), openapi() and
the mesh teacup. This adds what they do not cover, with expectations
captured from the pre-radix code at ed47836 in a detached checkout:

- explain()/inspect() on a pattern shared by several methods with a
  non-GET declared first, and a concrete path that is not a declaration;
- /__graph__ and /__openapi__ on app.fetch, a Node listener and a mesh
  teacup, and their agreement with the direct API;
- a structural check that graph/explain/inspect/openapi never call the
  router lookup, return the same output before and after the index is
  built, and keep declaration order where the index ranks differently.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 13:59:56 -05:00
chrnx a2b71e2472 fix(router): drop pending walk frames when a segment fails to decode
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
The walk stack is shared across lookups. A malformed % escape threw out
of decodeSegment with frames still pushed, so repeated direct matcher
calls on such paths retained them. Truncate both arrays back to the
entry length in a finally block, and check it with a test.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-12 13:47:53 -05:00
chrnx 4de9f32e31 test(router-parity): retarget walk mutants to the iterative walk
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 15s
Same four mutants (no-backtrack, catch-all-needs-segment,
prune-bound-off-by-one, zero-catch-all-after-static-dead-end), patched
at their new sites in the stack-based walk. 21/21 still killed.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 22:07:17 -05:00
chrnx 5e0ae94ba2 fix(router): walk the radix index without recursion
The lookup walk recursed once per path segment, so a valid deep route
such as 4,999 static segments followed by /:x threw RangeError where the
linear matcher matched. Walk on an explicit stack instead, visiting
frames in the same order, and cover the case through buildFetch.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 22:06:49 -05:00
chrnx 996fb3f7a5 test(router-parity): retarget mutants to the radix index (owner-approved)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 25s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
The owner approved editing this one file under test/router-parity/ so
the PR ends with a single mutant check. The original search texts
targeted lines of the linear scan that CARD-07 removed, so the script
refused to run against the new router. The parity tests, oracle,
frozen JSON and manifest are untouched.

The twelve original mutants keep their names and the bug each models;
six apply their original edit, six are rewritten against the index.
Nine new mutants cover risks the index introduced: the static-route
map ignoring the method or shadowing an earlier route, an off-by-one
pruning bound, the empty-collection skip pruning a real match, a
local/remote tie going remote, Allow and implicit HEAD from the local
tree only, the stale-index guard removed, and a zero-segment
catch-all skipped where the path ends on a static continuation.

The suite now also runs test/router-index.test.ts, which covers the
local/remote split and index lifetime the corpus cannot reach. Each
edit must match exactly once and must change the file; a failed edit
restores the copy before the run aborts. The script still ends with
git diff --exit-code src.

Removes test/router-index-mutants.ts and parity:mutants:index, which
this replaces.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 21:00:35 -05:00
chrnx 55a4e282ad test(router): cover pruning across a static branch and a param sibling
The walk takes the static branch first, so for `GET /a/:rest*` and
`GET /:x/b` it reaches the catch-all on `/a/b` before the exact param
route that outranks it. The corpus has no such pair, and a pruning
bound off by one went unnoticed there. Checked against the oracle in
both declaration orders.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 21:00:27 -05:00
chrnx 815f76116f perf(router): index HTTP routes in a radix tree
Replace the linear, specificity-sorted scan behind matchRoute,
resolveRoute and allowedMethods with a segment trie per HTTP method,
built once per route array from the compiled segments compilePattern
already produces.

Ranking stays global: every terminal carries its position in the old
sorted bucket (moreSpecific, declaration order on ties), and the walk
keeps the lowest rank it can reach, pruning subtrees that cannot beat
it. The tree decides which routes can match; the rank alone decides
which one does. A static branch that dead-ends deeper backtracks into
its param, constrained and catch-all siblings.

All-static routes are also kept by exact path per method. A hit there
is provably the tree's best match, so a static request is answered
without splitting the path; a miss falls through to the walk.

Mesh-spliced remote routes go in a second tree, per the owner's
design decision. Both trees answer, the more specific match wins and
an equal one goes to the earlier declaration, so local still beats
remote on a tie. Allow, 405 and implicit HEAD run over the union. An
app without remote routes does one lookup.

allowedMethods walks the index instead of recompiling every route on
a miss, and an implicit HEAD no longer builds a fresh index from a
filtered array on every request.

The frozen parity corpus passes unchanged. The frozen mutant script
cannot run against the new layout by design, so
test/router-index-mutants.ts re-targets its twelve bug classes at
the new code and runs the same untouched suite.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-11 12:56:37 -05:00
chrnx fdd762b081 test(router): freeze local/remote Allow and remote implicit HEAD for mesh
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 26s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
CARD-07 will index local and remote mesh routes as two radix trees and keep
today's unified precedence: the most specific route wins across both trees, a
tie goes to the local route, and Allow is the union. This freezes that behaviour
from ed47836, through app.fetch and a Node socket, in a new file
(owner-mesh-allow.json); existing captures are untouched.

- Local GET and remote POST on one path: PUT is 405 and OPTIONS is 204, both
  with Allow GET, HEAD, POST, OPTIONS. HEAD uses the local GET.
- Local static GET /api/v/b with remote POST /api/v/🆔 the same union on
  /api/v/b, and only POST, OPTIONS on /api/v/c.
- A remote GET with no local route: OPTIONS advertises GET, HEAD, OPTIONS, but
  HEAD answers 404. The teacup resolves HEAD to the remote GET implicitly,
  forwards it as HEAD, and the teapot finds no plan for (pattern, HEAD). That
  is the mesh proxy, not the matcher, and is captured as observed.

The mutation check still kills 12 of 12.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 18:16:09 -05:00
chrnx 32caa21308 test(router): add a mutation check for the parity corpus
A frozen corpus is only worth what it catches. npm run parity:mutants applies 12
targeted mutants to a temporary copy of src/, one at a time, and runs the parity
suite against each. Every mutant models a bug a radix rewrite could plausibly
introduce:

  no backtracking to a param branch     static/param precedence swapped
  equal-rank tie to last-registered     constraint ignored
  decode before splitting (%2F)         catch-all needs a segment
  implicit HEAD from a streaming GET    Allow from one pattern only
  Allow in discovery order              trailing slash not normalized
  WS ranked like HTTP                   case-insensitive static match

All 12 are killed (4 to 74 failing tests each), so no corpus case had to be
added. A mutant whose search text is not found exactly once fails the run rather
than silently testing an unmutated copy. The real src/ is never written, and
the run ends with git diff --exit-code src. It is not part of npm test because
it runs the suite once per mutant.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:39:38 -05:00
chrnx 684795a2de test(router): run the parity differential on Deno, Bun and workerd
The matcher comparison does not depend on the runtime, so it should run on every
runtime core supports. Only the Node suite ran it before.

The comparison and the app.fetch fixtures move into differential.ts and
app-fixture.ts, which use neither vitest nor a file API. Each runtime passes in
a loader for the frozen JSON. The vitest files use the same modules, plus a
Node check that the neutral runners report no mismatch, so the two paths cannot
drift.

- Deno and Bun: test/{deno,bun}/router-parity.test.ts run all 1158 frozen
  matcher cases (hand-picked, owner, generated v1 and v2, WS) through the oracle
  and the live router, plus the 55 app.fetch cases.
- workerd: test/edge/parity-worker.ts bundles the frozen JSON and runs the
  same checks; test/edge/run.ts adds the phase after its existing assertions.

The Node-socket, WS-upgrade, boot and mesh captures stay Node-only: they need
http.request, the ws client, or a mesh peer on a port.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:38:36 -05:00
chrnx a47c6564ab test(router): add owner-requested parity cases and a shared-prefix generator
Additions requested in CARD-08 review, captured from ed47836 like the rest of
the corpus and frozen in their own files, so the first capture is untouched.

- Backtracking: a static branch failing one level down, at depth 5 (and a
  param branch at depth 3), and with a constrained param on the fallback.
- Cross-pattern Allow: GET :id plus POST b, with and without DELETE :rest*,
  at matcher level and through app.fetch and Node.
- Encoded slashes in plain and constrained params. A constraint cannot itself
  contain a slash: the pattern splits there and is rejected as malformed.
- Zero-segment catch-alls without an exact sibling, and a root catch-all.
- The mesh HTTP table across a peer's lifetime. It is built once at boot and
  never changes: a peer that leaves keeps its routes (503 on hit, 405 Allow
  unchanged) and a peer that arrives after boot is never spliced in (404).
  CARD-10 can reuse this for its no-rebuild-per-request check.
- router-parity-gen-v2, same seed 10908, forces static, param, constrained
  and catch-all siblings under shared prefixes at depths 1-4. branches.ts
  measures the effect and the result is frozen with the fixture: 71.9% of v2
  requests reach sibling branches and 67.3% backtrack, against 36.5% and
  26.7% for v1. v1 and its fixture are unchanged.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 17:27:11 -05:00
chrnx 5d0e544878 test(router): capture graph, explain and OpenAPI goldens before indexing
graph(), explain() and openapi() read routePlans in declaration order. A
radix index must stay a lookup structure and never become their source, so
their output is frozen from ed47836 for CARD-09 to compare against.

One app fixture covers multiple methods and transports, constraints, explicit
HEAD and OPTIONS, providers and steps, and WS, declared out of specificity
order. The goldens hold graph(), explain() for declared patterns and the
`no route: <pattern>` error (including a concrete request path, which is not a
declaration), and openapi({ title: 'Parity', version: '1' }). A separate mesh
teacup records the pre-ready errors, then post-ready introspection in which
the remote HTTP route is reachable but absent from routePlans.

The comparison holds array order and object key order, and `vitest -u` is
refused rather than allowed to rewrite a golden.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 16:59:46 -05:00
chrnx c30cf7e457 test(router): freeze the differential, application, WS and boot-error corpus
The parity corpus from ROUTER-CORPUS §2, with every expected output captured
from ed47836 rather than written by hand.

Matcher: 24 hand-picked scenarios (precedence, constraint ties, exact versus
catch-all, equal-rank and same-pattern ties with reversed twins, implicit and
explicit HEAD, streaming GETs, canonical Allow, encoding, case, Unicode and
normalization) plus 40 scenarios from a fixed-seed generator
(router-parity-gen-v1, seed 10908). The generated file stores the seed, the
rules and every generated input; the test regenerates and requires a match,
so changing the generator cannot move the baseline. Each scenario runs through
the oracle and the live router and both must equal the capture, compared by
declaration ID, decoded params, implicitHead, ordered Allow, or the
normalization error.

Application level: status, Allow, headers and body through app.fetch and a
Node socket, including HEAD body suppression, 400/404/405 and OPTIONS.

WebSocket, separate from HTTP: first-registered selection, an HTTP route at the
same path not taking the upgrade, and the reserved mesh control path, through
app.upgrade and the Node listener. This freezes one adapter disagreement as
observed: a user @Ws('/__mesh__/control') on an app without mesh is refused by
app.upgrade (1008) and served by the Node listener.

Boot-time rejections: pattern compilation, local ambiguity and mesh splicing
(duplicate exports, same-shape exports, local-over-remote precedence with its
warning, and a remote static outranking a local parameter route).

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 16:59:45 -05:00
chrnx adce82beaa test(router): pin the retained-test manifest and a frozen pre-radix oracle
CARD-07 replaces the linear HTTP matcher with a radix index. Before any of
that code changes, the behaviour it must preserve has to exist somewhere the
new code cannot quietly move it.

manifest.json names the existing tests retained unchanged (ROUTER-CORPUS §1),
pinned to ed47836 instead of 42376c6: #117 and #122 landed after the corpus
was written. Every named file and test was verified to exist and pass there;
none was renamed. Three upgrade-path tests from #117 are listed separately as
proposed additions, pending D5. manifest.test.ts fails if a named test
disappears.

oracle.ts is a verbatim copy of the matcher at ed47836 (matchRoute,
resolveRoute, allowedMethods, normalizeRequestPath, compilePattern,
matchWsRoute), with local route types and its own caches. Its header says it
must not be edited to fit a new implementation, and the manifest test fails if
anything under src/ imports it.

frozen.ts reads the captured baseline. It refuses `vitest -u`, and the capture
switch only fills a missing file, never overwrites one.

Refs #109

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 16:59:31 -05:00
chrnx 77a99e83ce chore(deps): vitest 4
CI / runtimes (bun) (pull_request) Successful in 15s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / dco (pull_request) Successful in 4s
CI / build (pull_request) Successful in 26s
CI / runtimes (edge) (pull_request) Successful in 13s
vitest 3.2.7 carried the last three dev audit advisories: tinypool
(critical, prototype pollution to RCE in worker options), vitest itself
(critical, through tinypool and @vitest/mocker) and @vitest/mocker
(moderate, path traversal through a redirected mock). 4.1.11 is the
first stable release outside every affected range; vitest 4 no longer
depends on tinypool at all. It needs Node 20 or newer, which the Node 22
floor now guarantees. vitest 5 would need Node 22.12, and 4.1.11 is
enough to clear the advisories.

vite stays on ^6.4.3, which vitest 4 accepts.

The one change the bump requires: vitest 4 types `vi.fn()` with no
arguments as a mock of a function *or* a constructor, so
`ReturnType<typeof vi.fn>` is no longer callable as a plain function.
listener-boundary.test.ts now types its spies as
`Mock<(...args: unknown[]) => void>`.

npm 10.9 crashes in arborist's #loadPeerSet resolving this tree, so the
lockfile was produced with npm 11.6.2; `npm ci` on Node 22's bundled
npm 10 installs it cleanly.

npm audit: 3 -> 0. npm audit --omit=dev stays at 0.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 15:03:19 -05:00
chrnx bd478ce09c build!: require Node 22
Node 18 and Node 20 are end-of-life and receive no security patches, so
supporting them before RC.1 would mean promising a runtime nobody can
patch. Node 22 is the oldest line still maintained.

engines.node moves to >=22, @types/node to ^22, the tsup target to
node22, and CI's build job from Node 18 to 22, so every workflow now
runs Node 22 only. The docs, the bug report example and the comments
that stated 18 as the floor follow.

The node:crypto fallback in the HTTP core existed only for Node 18,
which lacked the global crypto; it goes with its regression test, which
said as much. The ws fallback for the WebSocket client stays: Node 22
has the global, but it can still be switched off with a flag.

Moving off Node 18 and 20 also unblocks vitest 4, which the remaining
dev audit advisories need.

BREAKING CHANGE: Node 18 and Node 20 are no longer supported. The
minimum is Node 22.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 12:10:52 -05:00
chrnx 26bacdb304 fix(ws): bound inbound frames synchronously and all-or-nothing
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 30s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s
Two gaps in boundInbound, both from review of #117.

The bound ran in an async pump reading the adapter's channel. `ws` emits a
whole TCP read's worth of frames synchronously, so the unbounded channel
took the burst before the pump saw the first frame: with maxWsQueue 2, a
2,000-frame burst reached the channel in full before close(1013). boundInbound now taps
the channel through an internal, non-exported hook that runs inside push(),
so each frame is bounded before it is queued. Measured on the Node
listen() path, the same burst now closes on the 3rd frame.

accept() also offered a frame to consumers in order and closed 1013 when a
later queue was full, so the rejected frame had already reached earlier
consumers. Capacity is now checked for every consumer before any delivery.

Refs #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:42:38 -05:00
chrnx 7fa02d16be fix(ws): give every inbound consumer its own bounded queue
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 14s
boundInbound returned one shared FIFO to every `inbound` iterator, with a
single waiter slot. Two consumers waiting at once left one hanging forever,
sequential consumers split frames, and one consumer's return() ended the
stream for all. Node used to fan out through `channel`; Deno, Bun and edge
already shared one iterator before #107, so the bug was older there.

Each iterator now gets its own queue, and maxWsQueue bounds each one. Frames
that arrive before anyone reads still go to the first consumer, which keeps
the mesh `hello`.

Refs #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:23:38 -05:00
chrnx f78c9dc6fd fix(runtime): give ctx.ip the socket peer on Deno and Bun
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 32s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 15s
buildFetch had no channel for a peer address, so ctx.ip was '' for
every HTTP request served by serveDeno or serveBun unless trustProxy and
x-forwarded-for supplied one. Everything keyed on the address shared one
value: the rate-limit plugin put every client in a single bucket, and
one client could exhaust the limit for all of them.

The adapters now record the peer in a WeakMap keyed by the Request
object (src/http/peer.ts, not exported) and pass that same object to
app.fetch. A header would be visible to handlers and spoofable; a second
fetch parameter would be public API. buildFetch derives ctx.ip as Node's
deriveIp does: the first x-forwarded-for hop when trustProxy is on and
the header is present, the peer otherwise. trustProxy without the header
therefore falls back to the peer instead of answering ''.

The map hangs off globalThis under Symbol.for('@green-tea/core:peer')
rather than living in the module. tsup's CommonJS build bundles index,
deno and bun as separate files with no shared chunk, so each gets its
own copy of peer.ts; with a module-private map, serveBun from
@green-tea/core/bun recorded peers that app.fetch from @green-tea/core
never saw, and ctx.ip stayed ''. A test loads a second instance of the
module to pin this.

A bare app.fetch from user code, or a Request copied from the adapter's,
has no entry and answers exactly what it did before. Addresses are
passed through unnormalised. WebSocket and the edge adapter are
unchanged; trusting cf-connecting-ip is a separate decision.

Closes #116

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:59 -05:00
chrnx ae60cd68a2 fix(http): enforce maxBodyBytes while reading fetch request bodies
The fetch adapter read every body through request.arrayBuffer() and
compared the length afterwards, so Deno, Bun and the edge buffered an
oversized upload in full before refusing it. readFetchBytes now reads
request.body chunk by chunk, stops at the chunk that crosses the limit
and cancels the reader, so no further chunk is pulled.

A content-length that already declares more than the limit is refused
before anything is read, on both adapters. On Node the request used to
wait for its first chunk, which a client that sends only headers never
delivers. A malformed or absent header is ignored and the running count
enforces the limit. The response is the same 413 through onError, and
the route-over-server precedence for maxBodyBytes and maxParts is
untouched; the new tests pin it.

The over-read is proven with a counting stream rather than a status
code, which is the same 413 either way. The stream uses a high-water
mark of 0: the default of 1 pulls a chunk at construction, before any
reader exists, which would make "nothing was read" unprovable.

Socket-level tests on Deno, Bun and workerd use a 1000-byte route limit
so every refused body fits in the socket buffer. With a multi-megabyte
body the client is still writing when the 413 lands and sometimes sees
ECONNRESET instead, which is the transport racing the answer. The Bun
socket test also disables keep-alive: Bun's own fetch client reuses a
socket after a response that arrived before the body was read, and its
next request on it comes back 400 or 431. Node's fetch against the same
Bun server does not.

Closes #105

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:47 -05:00
chrnx 0540bef07b feat(ws)!: bound inbound WebSocket message size and queue
Inbound WebSocket traffic was unbounded per connection: Node used ws's
100 MiB default payload, the other runtimes had no cap of their own, and
the queue behind `inbound` was an unbounded channel on every runtime, so
one client could exhaust memory with large messages or a slow consumer.

Add `limits.maxWsMessageBytes` (default 1 MiB, close 1009) and
`limits.maxWsQueue` (default 16 unread messages, close 1013), as recorded
in D1. Both are server-wide and validated by createApp, which throws a
TypeError for anything but a positive integer. Enforcement is shared in
`boundInbound`, which subscribes immediately and replaces the
subscribe-before-boot trick in app.upgrade. Node and Bun also get the
native pre-buffer cap; Bun drops the connection without a close frame,
so its peer sees 1006, which is documented and tested. Deno and workerd
expose no such option and check the size after receipt.

BREAKING CHANGE: messages over 1 MiB now close the connection with 1009,
and a connection with 16 unread inbound messages is closed with 1013 on
the next one, including a handler that never reads `inbound`.

Closes #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:35 -05:00
chrnx 59763c9af5 fix(ws): reject malformed upgrades instead of crashing the server
The Node 'upgrade' listener matched the raw request path without the
normalization HTTP runs. A bad percent escape in a param segment threw
URIError synchronously inside the listener, an uncaught exception that
ends the process, and '//' silently matched a route HTTP refuses.

Upgrades now normalize the path first: malformed escapes and repeated
slashes get a 400, an unknown route a written 404 instead of a bare
destroy, and any other throw in the listener a 500. app.upgrade
(Deno/Bun/edge) closes 1008 'invalid request path' rather than 1011.

On Deno the adapter's socket is still CONNECTING when an early 1008 is
sent, and that close was a no-op that left the peer hanging; eventSocket
now defers such a close to 'open'.

Closes #104

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:35 -05:00
chrnx 1069c727c8 fix(http): catch failures at the Node request-listener boundary
The Node request listener was an async function, and http.createServer
ignores the promise a listener returns. Anything that rejected outside
the region where errors convert to a response - a custom static resolver,
a handler header value Node refuses to write (ERR_INVALID_CHAR), a stream
that fails between flushing its headers and its first frame - became an
unhandled rejection, which Node's default mode turns into a process exit.

The listener now hands the request to serve() and catches its rejection
in failSafe(), per refinement decision D2:

- writable: a fixed 500 with connection: close, written through the
  patched writeHead so the security headers still land, without calling
  onError again;
- headers or body already sent, or the client gone: destroy the socket;
- the failure is logged through logger.error first, guarded, with
  String(err) for non-Error values.

No request:end is emitted for these requests: observers do not alter the
response, and the core never completed it. The request gate slot is
already released by the existing finally, which the tests prove.

Deno, Bun and the edge are unaffected: they receive app.fetch's promise
and the runtime answers a rejection itself.

Closes #108

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:32 -05:00
chrnx 53660adcce fix(views): confine static serving to the root's real path
The static resolver's traversal guard compared paths lexically, and the
read that followed it resolved symlinks, so a link inside the root such
as `public/leak -> /etc/hosts` served a file outside it.

Containment now compares real paths. The root's real path is resolved
on the first request and cached (a failed lookup is not, so a root
created after boot still starts serving); the requested file and a
directory's `index.html` are each realpath'd and must lie at or beneath
it, with the `root + sep` rule keeping a sibling such as `root-evil`
out. The lexical guard stays in front, since it rejects `..` without a
syscall.

An escape or a dangling link is a plain miss: 404 through `onError`, or
405/204 where the path has routes. Not 403, so a probe cannot tell a
file outside the root from one that does not exist. Re-pointing a root
symlink at runtime needs a restart. The realpath-to-read race is left
open and marked; closing it needs per-component O_NOFOLLOW, which is
not portable across Node, Deno and Bun.

Closes #106

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-09 13:59:03 -05:00
chrnx 9634ec73e8 feat(runtime)!: serveDeno and serveBun boot before they bind
CI / dco (pull_request) Successful in 6s
CI / build (pull_request) Successful in 30s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / runtimes (deno) (pull_request) Successful in 20s
CI / runtimes (edge) (pull_request) Successful in 13s
Both were synchronous and left the boot to the first request, with the fix
documented as something the caller should remember: `await app.boot()` before
`Deno.serve` / `Bun.serve`. That made the correct use of a core helper depend
on reading a README, in a framework whose whole argument is that order should
not be something you have to get right.

The failure it leaves is the bad kind. `app.fetch` boots lazily and the boot
memo keeps the *rejection*, so a missing signing key does not fail the deploy:
the port binds, every request is answered 500 by the runtime, and none of them
reach `onError`. Anything that health-checks by asking whether the process is
listening sees a healthy server.

`listen()` has always awaited `bootApp()` before binding its socket, with a
comment saying it exists so Node and Deno/Bun serve an identical graph. They
did not. Now the three helpers agree, and the two adapters return promises.

`edgeHandler` is deliberately unchanged: on workerd there is no startup outside
a request, so there is no earlier moment to move the failure to.

Both new tests were confirmed to fail with the gate commented out — without it
`serveBun` resolves instead of rejecting, and serveDeno binds a port that 500s.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-19 12:38:50 -05:00
chrnx a30c2cecb3 chore(release): 26.9.0-beta.2 to staging
The plugins repository builds against Plugin { name, mount } and app.boot(),
which only develop has. Staging the version publishes it to Verdaccio under
stg and nowhere else; the npm and JSR cut stays a separate decision.

The bump also moves the exported VERSION, which was two releases behind and had
no business being. Its comment claimed it was "replaced at publish time" and
nothing ever did that — not tsup, not stage.yml, not release.yml, which only
reads the version out of package.json. VERSION is what a consumer quotes in a
bug report, so a stale one sends someone to the changelog of a release they are
not running.

Pinning it to package.json is what keeps this from being a fix with a shelf
life: the next bump that forgets it now fails the build. smoke.test.ts was
never going to catch it, because it asserts the CalVer shape and a stale
version matches that perfectly.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-17 22:39:49 -05:00
chrnx e0da6cee16 test(runtimes): build plugins as named objects on Deno and Bun
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:25 -05:00
chrnx b3152aac45 test: build plugins as named objects
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:27:15 -05:00
chrnx 3fc761ce16 feat(app): expose boot() so providers can fail before serving
Only listen() booted before accepting traffic. Deno, Bun and edge all boot on the
first request, and the memo keeps the rejection, so a bad key answered 500 for the
life of the process while the app looked healthy.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-16 22:26:28 -05:00