Author SHA1 Message Date
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 4c3b4d29c4 chore(deps): move the benchmark's fastify to 5.12.5
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 29s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 13s
fastify <= 5.12.4 carries seven advisories (high), and it reaches us
twice, both benchmark-only: as a direct devDependency and through
@nestjs/platform-fastify 11.2.7, which pins fastify 5.11.3 exactly.
`npm audit fix --force` would move to @nestjs/platform-fastify 12,
which is ESM-only and needs @nestjs/core and @nestjs/common 12 as
well: a migration of the Nest benchmark servers, not a dependency fix.

Raise the direct range to ^5.12.5, a patch inside the major we already
use, and point nest's copy at it with `"fastify": "$fastify"` so the
tree holds a single, patched fastify.

Checked with `BENCH_SMOKE=1 npm run bench`: fastify, nestjs-fastify
and nestjs-express all boot and serve every scenario with 0% errors.

npm audit: 5 (2 critical, 1 high, 2 moderate) -> 3 (2 critical,
1 moderate), all of them vitest. `npm audit --omit=dev` stays at 0.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 12:00:06 -05:00
chrnx 445738e830 chore(deps): override miniflare's undici and sharp to patched releases
miniflare 4.20260730.0 is still the newest stable release, and it pins
undici 7.28.0 and sharp 0.35.2. The existing undici 7.29.0 override is
now inside a new advisory range (7.0.0 - 7.29.0, high), and sharp is
under two libheif/librsvg advisories (<= 0.35.5-rc.1, high).
`npm audit fix --force` would install miniflare 5.20261006.1-alpha:
a major and a prerelease, for a test-only dependency.

Move the undici override to 7.29.1 and add sharp 0.35.5, both patch
releases and the exact versions the next miniflare ships with. Same
approach already used for find-my-way, hyperid's uuid and undici.

`test:edge` is the suite that drives workerd through miniflare and it
passes unchanged.

npm audit: 8 (2 critical, 4 high, 2 moderate) -> 5 (2 critical,
1 high, 2 moderate). `npm audit --omit=dev` stays at 0.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:59:59 -05:00
chrnx 352ba477b4 chore(deps): apply non-breaking dev-dependency audit fixes
`npm audit fix` without --force: every bump stays inside the ranges
package.json already declares, so only the lockfile changes.

Clears proxy-addr (critical), multer and @nestjs/platform-express,
qs, brace-expansion, fast-uri, js-yaml and source-map-js. All of them
are dev or benchmark dependencies; `npm audit --omit=dev` was and
stays at 0.

npm audit: 16 (3 critical, 11 high, 2 moderate) -> 8 (2 critical,
4 high, 2 moderate).

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-10-10 11:57:23 -05:00
chrnx 4d1639f7c5 Merge pull request 'FPRD-001a: core safety and adapter correctness (#104 #105 #106 #107 #108 #116)' (#117) from feature/fprd-001a into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 15s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 21s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
2026-10-10 16:49:33 +00: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 42376c6693 Merge pull request 'docs(agents): stop publishing the address of the private forge' (#102) from docs/scrub-forge-host into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 14s
CI / build (push) Successful in 30s
CI / runtimes (deno) (push) Successful in 18s
Promote → GitHub / push-github (push) Successful in 6s
CI / runtimes (edge) (push) Successful in 14s
2026-09-23 17:04:26 +00:00
chrnx 9761b40eb5 docs(agents): stop publishing the address of the private forge
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 14s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
The promotion example I added in #101 carried the development forge's full
hostname, and this file is mirrored to GitHub — `develop` reaches the public
`contrib` branch on every merge, so it has been readable by anyone since it
landed.

That host resolves from the public internet, unlike the internal registry named
elsewhere in this repository, so it is a reachable endpoint rather than an
internal naming detail. Replaced with `$GITEA_URL` and `$REPO`, which costs a
reader nothing: `fast-forward-only` was always the part worth documenting, and
it is the part the CLI does not offer.

Not a rewrite of history — the commit stays where it is. Anyone who wanted the
address can still read it there, so this is tidiness going forward rather than a
recall.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 11:51:53 -05:00
chrnx 7255b8ec30 Merge pull request 'docs(agents): say how the promotion is actually merged' (#101) from docs/promotion-via-api into develop
CI / dco (push) Has been skipped
CI / runtimes (bun) (push) Successful in 17s
CI / build (push) Successful in 29s
CI / runtimes (deno) (push) Successful in 19s
CI / runtimes (edge) (push) Successful in 12s
Promote → GitHub / push-github (push) Successful in 8s
2026-09-23 14:36:12 +00:00
chrnx ca78f0a8e5 docs(agents): say how the promotion is actually merged
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 15s
CI / build (pull_request) Successful in 31s
CI / runtimes (deno) (pull_request) Successful in 18s
CI / runtimes (edge) (pull_request) Successful in 14s
The section tells you promotions are fast-forward-only and never says which
tool does that. `tea pr merge` does not: it offers merge, rebase, squash and
rebase-merge, and each one births a commit on main — the exact drift the rule
exists to prevent. Reaching for the obvious command therefore produces the
thing the paragraph above it forbids.

Gitea's API takes the style the CLI omits, so the promotion for 26.9.0-beta.2
went through curl. Recording the call, and the 405 that precedes it: main is
protected and a promotion PR runs its own checks rather than inheriting the
ones develop already passed, so the first attempt is refused for checks that
simply have not finished yet.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
2026-09-23 09:34:57 -05:00
54 changed files with 3075 additions and 674 deletions

No files matched your search

+1 -1
View File
@@ -19,7 +19,7 @@ The smallest module and route that shows it:
## Environment ## Environment
- green-tea version: - green-tea version:
- Runtime and version: <!-- Node 20.11 / Deno 2.1 / Bun 1.1 / Cloudflare Workers --> - Runtime and version: <!-- Node 22.12 / Deno 2.1 / Bun 1.1 / Cloudflare Workers -->
- OS: - OS:
<!-- <!--
+1 -1
View File
@@ -41,7 +41,7 @@ jobs:
- uses: actions/checkout@v4 - uses: actions/checkout@v4
- uses: actions/setup-node@v4 - uses: actions/setup-node@v4
with: with:
node-version: '18' node-version: '22'
- run: npm ci - run: npm ci
- run: npm run lint - run: npm run lint
- run: npm run format:check - run: npm run format:check
+14
View File
@@ -55,6 +55,20 @@ feature/* → develop → main → [promote.yml] → GitHub main
**Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does. **Only `hotfix/*` can still cause real drift**, since it branches from and returns to `main`. That case genuinely needs a back-merge; nothing else does.
**`tea pr merge` cannot do the promotion.** The CLI offers `merge`, `rebase`, `squash` and `rebase-merge`, and every one of them births a commit on `main` — the drift this section exists to prevent. Gitea's API has the style the CLI lacks, so promote through it:
```bash
curl -X POST -H "Authorization: token $TOKEN" -H 'Content-Type: application/json' \
-d '{"Do":"fast-forward-only"}' \
"$GITEA_URL/api/v1/repos/$REPO/pulls/<n>/merge"
```
`$GITEA_URL` and `$REPO` are yours to fill in — this file is mirrored to a public repository, and
the address of a private forge is not something to publish. `fast-forward-only` is the part that
matters and is the part the CLI does not offer.
A `405 Not all required status checks successful` means the pull request's own CI has not finished — `main` is protected, and a promotion runs its own checks rather than inheriting `develop`'s. Wait for them; the call is the same afterwards.
**Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later: **Delete the branch when the work lands.** Both sides, as the last step of merging rather than a chore left for later:
```bash ```bash
+98
View File
@@ -6,6 +6,104 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since green-tea uses calendar versioning: `YY.M.PATCH` — the month is not zero-padded, since
npm treats versions as semver and semver forbids leading zeros. npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
### Breaking
- **Node 18 and Node 20 are no longer supported; the minimum is Node 22.** Both are end-of-life
and receive no security patches, so `engines.node` is now `>=22`, CI runs Node 22 only, and the
build targets `node22`. Node 22 is the oldest line still maintained. The `node:crypto` fallback
for Node 18's missing global `crypto` is removed with it.
- **Inbound WebSocket messages are capped at 1 MiB by default** (#107). Node used `ws`'s own
default of 100 MiB, and Deno, Bun and the edge applied no cap of their own, so one client could
make the server hold a message of any size the runtime would accept. A larger message now closes
the connection with `1009` (`message too large`). Raise it with `limits.maxWsMessageBytes`.
- **A connection with 16 unread inbound messages is closed on the 17th** (#107), with `1013`
(`inbound queue full`). The queue behind `inbound` was unbounded on every runtime, so a handler
that read slowly — or never — let a client grow it without limit. This also reaches a `@Ws`
handler that never reads `inbound` at all: on Node those frames used to be discarded, and they
now count. Raise the bound with `limits.maxWsQueue`.
### Added
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
WebSocket messages, in bytes and in unread messages, server-wide on every runtime. `createApp`
throws a `TypeError` for anything but a positive integer. Node and Bun refuse an oversized message
before buffering it; Bun does so by dropping the connection, so its peer sees `1006` rather than
`1009`. Deno and workerd expose no such option, so there the message is received in full and then
refused, and its memory is bounded by the platform's own cap. Worst-case buffered inbound memory is
about `maxConnections × maxWsQueue × maxWsMessageBytes`, ≈ 15.6 GiB at the Node defaults; Deno and
Bun have no connection cap, so set one at the platform or proxy there.
### Fixed
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
compared paths lexically, and the file read then followed symlinks, so `public/leak -> /etc/hosts`
was served. Containment now compares real paths: the requested file, and a directory's
`index.html`, must resolve beneath the root's real path. Links that stay inside the root, and a
root that is itself a symlink, keep working.
A link that resolves outside the root, or a dangling link, is a **404** — the same miss as a file
that does not exist, rendered through `onError` like any other, and `405`/`204` where the path has
routes. It is deliberately not a `403`, so a probe cannot tell "exists outside the root" from
"does not exist". The content-type still follows the requested name, not the link target.
The root's real path is resolved on the first request and cached, so **re-pointing a root symlink
while the app runs needs a restart** to take effect. A link swapped inside the root between the
check and the read can still escape; exploiting that needs write access to the served directory.
- **A request that fails past the error renderer no longer takes the Node process down** (#108). The Node
request listener was an `async` function, and `http.createServer` ignores the promise it returns,
so anything that rejected outside the region where errors convert to a response — a custom static
resolver, a handler header value Node refuses to write, a stream that fails before its first frame
— became an unhandled rejection, which Node's default mode turns into an exit. The listener now
catches it. While the response is still writable the client gets a fixed 500 with
`connection: close`, written without calling `onError` again; once output has started the socket
is destroyed instead. Either way the failure is logged through `logger.error`. No `request:end` is
emitted for these requests. Deno, Bun and the edge were not affected: they receive `app.fetch`'s
promise, and the runtime answers a rejection with a 500 itself.
- **A malformed WebSocket upgrade no longer takes a Node server down** (#104). The upgrade path never
ran the request-path normalization HTTP runs, so a bad percent escape in a param segment
(`/room/%E0%A4%A`) threw out of the `'upgrade'` listener as an uncaught exception, and one request
was enough to end the process. Upgrades now go through the same normalization: a malformed escape
or a repeated slash gets a `400`, an unknown route a written `404` instead of a silent disconnect,
and anything else that throws in the listener a `500`. `//rt//echo` used to match `/rt/echo` on
upgrade while HTTP refused it; both refuse it now. On Deno, Bun and the edge the same paths close
with `1008 invalid request path` rather than `1011 internal error`, and on Deno a `1008` sent before
the socket finished opening now reaches the client instead of leaving it hanging.
- **Deno, Bun and the edge enforce `maxBodyBytes` while reading the body, not after** (#105). The
fetch adapter read every request through `request.arrayBuffer()` and compared the length once the
whole body was in memory, so a 10 GB upload was buffered in full before it was refused. It now
reads `request.body` chunk by chunk, stops at the chunk that crosses the limit and cancels the
stream, so nothing further is pulled. A `content-length` that already declares more than the limit
is refused before any of the body is read, on Node too, where the request used to wait for its
first chunk. A malformed or absent `content-length` proves nothing and is ignored; the running
count enforces the limit either way. The response is unchanged: the same `413 Payload Too Large`,
through `onError`, with the same route-over-server precedence for `maxBodyBytes` and `maxParts`.
workerd may drop `content-length` from a chunked upload, so there an oversized body is refused by
the count rather than up front. The status is the same; only how early it comes differs.
- **`serveDeno()` and `serveBun()` populate `ctx.ip` with the client's address** (#116). The fetch
path had no way to learn the socket peer, so every HTTP request on Deno and Bun saw `ctx.ip` as
`''`, and anything keyed on it put every client in one bucket — the rate-limit plugin, where one
client could exhaust the limit for everyone, above all. Both adapters now hand the peer to
`app.fetch`, and `ctx.ip` follows the same rule as Node's `listen()`: the first
`x-forwarded-for` hop when `trustProxy` is on and the header is present, the socket peer
otherwise. That includes `trustProxy` with no `x-forwarded-for`, which used to answer `''` on
the fetch path and now falls back to the peer, as Node always has.
Addresses are passed through as each runtime reports them, so the IPv6 loopback is `::1` on all
three but Node may report an IPv4 client as `::ffff:127.0.0.1`. A bare `app.fetch(request)` from
your own code has no socket to report and still answers `''` (or the forwarded hop), and so does
a `Request` copied from the one the adapter received. No signature changed. The edge adapter is
unchanged: trusting `cf-connecting-ip` is only correct behind Cloudflare, and needs its own
decision.
## [26.9.0-beta.2] - 2026-09-22 ## [26.9.0-beta.2] - 2026-09-22
### Breaking ### Breaking
+1 -1
View File
@@ -101,7 +101,7 @@ Follow [Conventional Commits](https://www.conventionalcommits.org/): `feat:`, `f
## Local setup ## Local setup
Node 18 or newer, which is what `engines` requires and what CI runs. Node 22 or newer, which is what `engines` requires and what CI runs. Node 18 and 20 are end-of-life and no longer supported.
```bash ```bash
npm install npm install
+2 -2
View File
@@ -141,7 +141,7 @@ without growing the runtime dependency tree past `reflect-metadata`:
- **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS. - **Real body parsing.** JSON and urlencoded out of the box; `multipart/form-data` file uploads (`@body()` → `{ fields, files }`) via the optional [`busboy`](https://github.com/mscdex/busboy) peer dependency (`npm i busboy`) — a multipart request without it returns a clear `501`. All size-capped (`413`) against DoS.
- **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response. - **Errors, your way.** Throw typed errors (`Unauthorized`, `NotFound`, `HttpError(status, msg, body?)`) anywhere; they convert centrally to `4xx`/`5xx`. Render them however you like — HTML, RFC 7807, content-negotiated — with a single `createApp({ onError })` hook that covers every error response.
- **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency. - **HTML without a view layer.** `@Html` returns a string, serves a file, or renders one with the built-in `{{ }}` template engine — swap in EJS or handlebars with `createApp({ viewEngine })`. `createApp({ static: true })` serves `./public` with path-traversal guards and no mime dependency.
- **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. - **Resource ceilings, with safe defaults.** `limits` caps body size (`413`), multipart parts, concurrent Node connections (default `1000`; `<= 0` leaves connections unlimited), and the request / headers / keep-alive timeouts — defaulting to `30s` / `10s` / `5s`, tighter than Node's own two-minute default. `maxConcurrentRequests` is opt-in and applies per server or Fetch adapter instance; when set, excess in-flight requests receive `503` and `Retry-After: 1`. It bounds concurrently executing handlers, so a handler that never returns continues to hold its slot; on Node, a client disconnect releases that slot. Long-lived streams and WebSocket upgrades do not hold that request budget. When Node's connection cap is reached, excess sockets are destroyed without an HTTP response. Deno and Bun expose no equivalent active-socket cap, so enforce one at the deployment platform or reverse proxy there. WebSocket connections are bounded too: `maxWsMessageBytes` (default 1 MiB) closes a connection whose message is larger with `1009`, and `maxWsQueue` (default `16`) closes one that has that many unread inbound messages and receives another with `1013`, rather than dropping anything. Both are server-wide and must be positive integers. Node and Bun refuse an oversized message before buffering it (Bun drops the connection, so its peer sees `1006`); Deno and the edge check it after the runtime has received it. Worst case, a server buffers about `maxConnections × maxWsQueue × maxWsMessageBytes` of inbound messages — ≈ 15.6 GiB at the Node defaults.
- **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core. - **Observability without an integration.** Every request carries an id and a trace id through every lifecycle event, each step reports its own duration, and `createApp({ logger })` accepts any logger — the default writes structured JSON. Nothing in core writes to `console`. Metrics and tracing exporters read the same stream from outside core.
- **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`. - **Graceful shutdown, with a deadline.** `app.close()` drains in-flight requests and closes live streams and mesh links, then warns and force-closes whatever is still open after 10 seconds — so a stuck handler cannot hold a deploy open forever. Change the number per call with `close({ timeoutMs })` or for the whole app with `createApp({ shutdownTimeoutMs })`. Connection *draining* is Node-only; on Deno and Bun the server `serveDeno()`/`serveBun()` returns carries the same `close({ timeoutMs })`.
- **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook. - **Shutdown is an extension point.** A provider that opened a pool closes it in `dispose()`; a plugin registers `onShutdown(...)`; an application that wants neither passes `createApp({ hooks: [{ onShutdown }] })`. All three land in one registry, run in reverse boot order — a `cache` that needs `db` closes first — and are *awaited*, unlike a `bus.on` listener. A failure is logged and the rest still run, because one broken teardown must not leave the process up. Everything happens inside `close()`'s deadline; `createApp({ teardownTimeoutMs })` reserves a slice of it when a connection must get its chance. *Not available on the edge* — workerd has no shutdown to hook.
@@ -284,7 +284,7 @@ green-tea is **beta**, on the road to a release candidate. Express and Fastify h
**What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists. **What is not here:** no metrics registry, and **no OpenTelemetry exporter in core** — that is a separate package, because core has one runtime dependency and intends to keep it. A `traceparent` header is carried through untouched for an exporter to interpret; core implements no propagation spec. If your definition of production-ready includes shipping traces on day one, you are writing the exporter, and the stream it needs is the part that now exists.
**Runtimes differ in what they can offer.** Node ≥ 18, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag. **Runtimes differ in what they can offer.** Node ≥ 22, Deno, and Bun run everything. On the edge (Cloudflare Workers) there is no `app.listen()`, no filesystem — so `@Html` file/template modes and `static` serving are unavailable — and mesh does not run there at all (the teapot's secret comparison needs `node:crypto`'s `timingSafeEqual`, which `nodejs_compat` doesn't provide). Workers also require the `nodejs_compat` flag.
**mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet. **mesh is alpha.** Distributed DI works, but discovery, load-balancing, and failover are not built, and its API and wire protocol may change between releases. It is gated behind an explicit opt-in — `createApp({ mesh, experimental: true })` — and `createApp` throws if you configure `mesh` without it. Don't ship mesh to production yet.
Generated
+6 -4
View File
@@ -27,7 +27,7 @@
"npm:@types/autocannon@^7.12.7", "npm:@types/autocannon@^7.12.7",
"npm:@types/busboy@^1.5.4", "npm:@types/busboy@^1.5.4",
"npm:@types/express@^5.0.6", "npm:@types/express@^5.0.6",
"npm:@types/node@^18.19.0", "npm:@types/node@^22.20.5",
"npm:@types/ws@^8.18.1", "npm:@types/ws@^8.18.1",
"npm:autocannon@8", "npm:autocannon@8",
"npm:busboy@^1.6.0", "npm:busboy@^1.6.0",
@@ -35,7 +35,7 @@
"npm:esbuild@0.27.2", "npm:esbuild@0.27.2",
"npm:eslint@^9.39.5", "npm:eslint@^9.39.5",
"npm:express@^5.2.1", "npm:express@^5.2.1",
"npm:fastify@^5.11.0", "npm:fastify@^5.12.5",
"npm:graphql@^16.9.0", "npm:graphql@^16.9.0",
"npm:miniflare@^4.20260730.0", "npm:miniflare@^4.20260730.0",
"npm:prettier@^3.9.6", "npm:prettier@^3.9.6",
@@ -46,7 +46,7 @@
"npm:typescript-eslint@^8.65.0", "npm:typescript-eslint@^8.65.0",
"npm:typescript@^5.5.0", "npm:typescript@^5.5.0",
"npm:vite@^6.4.3", "npm:vite@^6.4.3",
"npm:vitest@^3.2.7", "npm:vitest@^4.1.11",
"npm:ws@^8.21.1" "npm:ws@^8.21.1"
], ],
"overrides": { "overrides": {
@@ -56,7 +56,9 @@
"uuid": "11.1.1" "uuid": "11.1.1"
} }
}, },
"undici": "7.29.0" "undici": "7.29.1",
"sharp": "0.35.5",
"fastify": "$fastify"
} }
} }
} }
+389 -527
View File
File diff suppressed because it is too large. Load diff
+7 -5
View File
@@ -26,7 +26,7 @@
"node" "node"
], ],
"engines": { "engines": {
"node": ">=18" "node": ">=22"
}, },
"publishConfig": { "publishConfig": {
"access": "public" "access": "public"
@@ -128,7 +128,9 @@
"uuid": "11.1.1" "uuid": "11.1.1"
} }
}, },
"undici": "7.29.0" "undici": "7.29.1",
"sharp": "0.35.5",
"fastify": "$fastify"
}, },
"devDependencies": { "devDependencies": {
"@eslint/js": "^9.39.5", "@eslint/js": "^9.39.5",
@@ -140,7 +142,7 @@
"@types/autocannon": "^7.12.7", "@types/autocannon": "^7.12.7",
"@types/busboy": "^1.5.4", "@types/busboy": "^1.5.4",
"@types/express": "^5.0.6", "@types/express": "^5.0.6",
"@types/node": "^18.19.0", "@types/node": "^22.20.5",
"@types/ws": "^8.18.1", "@types/ws": "^8.18.1",
"autocannon": "^8.0.0", "autocannon": "^8.0.0",
"busboy": "^1.6.0", "busboy": "^1.6.0",
@@ -148,7 +150,7 @@
"eslint": "^9.39.5", "eslint": "^9.39.5",
"esbuild": "0.27.2", "esbuild": "0.27.2",
"express": "^5.2.1", "express": "^5.2.1",
"fastify": "^5.11.0", "fastify": "^5.12.5",
"graphql": "^16.9.0", "graphql": "^16.9.0",
"miniflare": "^4.20260730.0", "miniflare": "^4.20260730.0",
"prettier": "^3.9.6", "prettier": "^3.9.6",
@@ -158,7 +160,7 @@
"typescript": "^5.5.0", "typescript": "^5.5.0",
"typescript-eslint": "^8.65.0", "typescript-eslint": "^8.65.0",
"vite": "^6.4.3", "vite": "^6.4.3",
"vitest": "^3.2.7", "vitest": "^4.1.11",
"ws": "^8.21.1" "ws": "^8.21.1"
} }
} }
+39 -15
View File
@@ -8,7 +8,17 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http'; import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http'; import type { HttpOptions } from '../http';
import { buildFetch } from '../http/web'; import { buildFetch } from '../http/web';
import { matchWsRoute, runWsConnection, trackUntil, type WsRequest, type WsSocket } from '../http/ws-core'; import {
boundInbound,
validateWsLimits,
WS_MAX_MESSAGE_BYTES,
wsMessageBytes,
matchWsRoute,
runWsConnection,
trackUntil,
type WsRequest,
type WsSocket,
} from '../http/ws-core';
import { isAsyncIterable } from '../channel'; import { isAsyncIterable } from '../channel';
import { JsonTransformer, type ErrorRenderer } from '../transformers'; import { JsonTransformer, type ErrorRenderer } from '../transformers';
import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin'; import { mountPlugin, Plugin, ScopeApi, ScopeNode } from '../plugin';
@@ -39,7 +49,7 @@ import type { MeshControl } from '../http';
import type { RequestEnvelope, RouteEntry } from '../mesh/protocol'; import type { RequestEnvelope, RouteEntry } from '../mesh/protocol';
import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types'; import type { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
import { inspectRoute, buildGraphView, explainRoute } from './introspect'; import { inspectRoute, buildGraphView, explainRoute } from './introspect';
import { compilePattern } from '../http/router'; import { compilePattern, normalizeRequestPath } from '../http/router';
export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types'; export type { App, InspectLine, ExplainNode, Explain, MeshConfig, Hooks } from './types';
@@ -195,6 +205,8 @@ export function createApp(opts: {
); );
} }
validateWsLimits(opts.limits);
const bus = new Bus(); const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger(); const logger = opts.logger ?? createDefaultLogger();
if (opts.logRequests) logRequests(bus, logger); if (opts.logRequests) logRequests(bus, logger);
@@ -318,7 +330,7 @@ export function createApp(opts: {
devRoutes, devRoutes,
() => remoteRoutes, () => remoteRoutes,
); );
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl); const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
const listen = async (port: number): Promise<http.Server> => { const listen = async (port: number): Promise<http.Server> => {
const deps = pipelineDeps; const deps = pipelineDeps;
@@ -387,7 +399,7 @@ export function createApp(opts: {
return wrapped; return wrapped;
}; };
return { const app: App = {
listen, listen,
close, close,
handleSignals, handleSignals,
@@ -405,6 +417,10 @@ export function createApp(opts: {
bus, bus,
logger, logger,
}; };
return Object.assign(app, {
[WS_MAX_MESSAGE_BYTES]: wsMessageBytes(opts.limits),
});
} }
/** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */ /** Creates an empty {@link Registry} whose `setRunner` enforces globally-unique provider/step names. */
@@ -1275,22 +1291,30 @@ function buildAppUpgrade(
streams: Set<() => void>, streams: Set<() => void>,
ensureBooted: () => Promise<void>, ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined, getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
): (request: WsRequest, socket: WsSocket) => Promise<void> { ): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined; let wsRoutes: WsRouteDef[] | undefined;
return async (request: WsRequest, socket: WsSocket): Promise<void> => { return async (request: WsRequest, socket: WsSocket): Promise<void> => {
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no // Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
// subscriber is dropped, so anything the peer sends while providers are still booting would be // with no subscriber is dropped, so anything the peer sends while providers are still booting
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang // would be lost. For the mesh control channel that is the `hello` itself — the handshake would
// until timeout against a teapot whose providers happened to boot slowly. // hang until timeout against a teapot whose providers happened to boot slowly.
const frames = socket.inbound[Symbol.asyncIterator](); const ready = boundInbound(socket, limits);
const ready: WsSocket = Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
}) as WsSocket;
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
const path = request.url.split('?')[0]; let path: string;
// The same normalization HTTP and the Node upgrade listener run. A malformed escape would
// otherwise reject out of the matcher and close with 1011, a server-error code for a client error.
try {
path = normalizeRequestPath(request.url.split('?')[0]);
} catch {
ready.close(1008, 'invalid request path');
return;
}
const meshControl = getMeshControl(); const meshControl = getMeshControl();
// The reserved mesh path, checked before route matching: this is what lets a teapot export // The reserved mesh path, checked before route matching: this is what lets a teapot export
@@ -1489,8 +1513,8 @@ function closeApp(
timeoutMs, timeoutMs,
}); });
// closeAllConnections() requires Node >=18.2, same floor as closeIdleConnections() // closeAllConnections() and closeIdleConnections() below both arrived in Node 18.2;
// below — `engines` in package.json only guarantees >=18, so this matters. // `engines` guarantees >=22, so both are always present.
server.closeAllConnections(); server.closeAllConnections();
finish(); finish();
}, drainBudget); }, drainBudget);
+11 -1
View File
@@ -1,9 +1,10 @@
import { channel } from './channel'; import { channel } from './channel';
import type { Channel } from './channel'; import type { Channel } from './channel';
import type { App } from './app/types'; import type { App } from './app/types';
import type { WsSocket, WsRequest } from './http/ws-core'; import { WS_MAX_MESSAGE_BYTES, DEFAULT_MAX_WS_MESSAGE_BYTES, type WsSocket, type WsRequest } from './http/ws-core';
import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter'; import { decodeMessage, neutralSocket, toWsRequest, upgradeSafely } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown'; import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep. // Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call. // Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
@@ -15,6 +16,7 @@ interface BunServerWebSocket {
terminate?(): void; terminate?(): void;
} }
interface BunWebSocketHandler { interface BunWebSocketHandler {
maxPayloadLength?: number;
open?(ws: BunServerWebSocket): void; open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): void; message(ws: BunServerWebSocket, message: string | Uint8Array): void;
close?(ws: BunServerWebSocket, code: number, reason: string): void; close?(ws: BunServerWebSocket, code: number, reason: string): void;
@@ -100,9 +102,17 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
return new Response('WebSocket upgrade failed', { status: 400 }); return new Response('WebSocket upgrade failed', { status: 400 });
} }
// The same object goes to `app.fetch`, which is what lets it find the peer again.
setPeer(request, server.requestIP(request)?.address ?? '');
return app.fetch(request); return app.fetch(request);
}, },
websocket: { websocket: {
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
// assembling it. It drops the connection without a close frame, so the peer sees 1006 rather
// than 1009 — verified on Bun 1.3, and the price of not buffering the message at all.
// `app.upgrade` checks the same bound again on the decoded text.
maxPayloadLength:
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
open(ws) { open(ws) {
const { wsReq } = ws.data as BunConnData; const { wsReq } = ws.data as BunConnData;
+31 -2
View File
@@ -14,6 +14,26 @@ export function isAsyncIterable(x: unknown): x is AsyncIterable<unknown> {
return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function'; return x != null && typeof (x as { [Symbol.asyncIterator]?: unknown })[Symbol.asyncIterator] === 'function';
} }
/**
* Internal: reads a channel synchronously, inside `push`, rather than through an async iterator
* that only drains once the event loop yields. `boundInbound` needs it to bound a WebSocket burst
* frame by frame, before anything is queued (#107). Not exported from the package; `Symbol.for`
* because each tsup entry carries its own copy of this module.
*/
export const CHANNEL_TAP: unique symbol = Symbol.for('green-tea.channel-tap');
/** What {@link CHANNEL_TAP} calls, synchronously, for every push, close and fail. */
export interface ChannelSink<T> {
push(value: T): void;
end(): void;
fail(err: unknown): void;
}
/** A channel that can be tapped; every channel built by {@link channel} is one. */
export interface TappableChannel<T> extends Channel<T> {
[CHANNEL_TAP](sink: ChannelSink<T>): () => void;
}
interface Sub<T> { interface Sub<T> {
iterator: AsyncIterator<T>; iterator: AsyncIterator<T>;
push(value: T, cap: number): void; push(value: T, cap: number): void;
@@ -84,9 +104,9 @@ function newSub<T>(onReturn: () => void): Sub<T> {
* Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber. * Creates a fan-out {@link Channel}. Values pushed are delivered to every active subscriber.
* @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded). * @param opts.buffer Per-subscriber queue cap; drops oldest when exceeded (default: unbounded).
*/ */
export function channel<T>(opts: { buffer?: number } = {}): Channel<T> { export function channel<T>(opts: { buffer?: number } = {}): TappableChannel<T> {
const cap = opts.buffer ?? Infinity; const cap = opts.buffer ?? Infinity;
const subs = new Set<Sub<T>>(); const subs = new Set<Omit<Sub<T>, 'iterator'>>();
let done = false; let done = false;
let closedFlag = false; let closedFlag = false;
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
subs.add(sub); subs.add(sub);
return sub.iterator; return sub.iterator;
}, },
[CHANNEL_TAP](sink) {
if (done) {
sink.end();
return () => {};
}
subs.add(sink);
return () => subs.delete(sink);
},
}; };
} }
+6 -2
View File
@@ -1,9 +1,10 @@
import type { App } from './app/types'; import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter'; import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
import { closeWithDeadline } from './http/shutdown'; import { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x) // The project tsconfig's `lib` doesn't include `DOM`, so we ambient-declare just the shape of
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use. // Deno's `WebSocket` we use rather than rely on whichever global `@types/node` happens to declare.
interface WebSocket extends EventfulSocket { interface WebSocket extends EventfulSocket {
binaryType: string; binaryType: string;
} }
@@ -82,6 +83,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
return response; return response;
} }
// The same object goes to `app.fetch`, which is what lets it find the peer again. A unix socket
// has no `hostname`, and records nothing.
setPeer(request, info.remoteAddr.hostname);
return app.fetch(request); return app.fetch(request);
}); });
+14 -6
View File
@@ -22,12 +22,11 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
/** /**
* Reads the raw request body, enforcing `limit`. * Reads the raw request body, enforcing `limit`.
* *
* The adapter owns this and nothing else about the body, because enforcement is the one place the * The adapter owns this and nothing else about the body, because getting the bytes is the one place
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a * the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check * Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer * limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer * possible — measuring afterwards would force the reader to buffer without bound first.
* without bound first.
* *
* The failure branch is opaque on purpose: Node answers an over-limit request with * The failure branch is opaque on purpose: Node answers an over-limit request with
* `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket. * `connection: close`, so the rest of the upload does not keep arriving on a kept-alive socket.
@@ -41,6 +40,15 @@ function isPromise<T>(value: MaybePromise<T>): value is Promise<T> {
*/ */
export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>; export type BodyReader = (source: unknown, limit: number) => MaybePromise<{ bytes: Buffer | undefined } | BodyFailure>;
/**
* True when a `content-length` header declares more than `limit` bytes — the one case a reader can
* refuse before consuming anything. A malformed or absent header answers false: it proves nothing,
* and the running total still enforces the limit on whatever actually arrives.
*/
export function declaresOverLimit(contentLength: string | null | undefined, limit: number): boolean {
return contentLength != null && /^\d+$/.test(contentLength) && Number(contentLength) > limit;
}
/** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */ /** Parse outcome: the decoded body, or an error message plus the status to send (400 unless set). */
type ParseResult = { body: unknown } | { error: string; status?: number }; type ParseResult = { body: unknown } | { error: string; status?: number };
+5 -21
View File
@@ -9,31 +9,15 @@ import { acquireBody, type BodyReader } from './body';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders'; import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { nodeRequire } from '../node-require';
/** /**
* `randomUUID`, from wherever this runtime keeps it. Resolved once, at import. * `randomUUID` from the web-standard global, which every supported runtime exposes without a flag:
* Node (the `engines` floor is 22; the global arrived unflagged in 19), Deno, Bun and workerd.
* *
* The web-standard global stays the primary path, and that is deliberate rather than stylistic: * Node 18 lacked it, and this used to fall back to `node:crypto` there. That fallback went with the
* this file is the runtime-neutral core, and Deno, Bun and workerd all expose `crypto` without a * Node 18 floor.
* compatibility flag, while `node:crypto` is unavailable to at least one of them.
*
* Node is the exception. The global arrived **unflagged in 19**, and `engines` promises `>=18`,
* where it does not exist at all — so the previous `declare const crypto` compiled cleanly and then
* threw `ReferenceError: crypto is not defined` on the first request of every Node 18 process. Only
* CI's Node 18 job caught it; every newer Node and every other runtime hides it, which is exactly
* why that job is pinned to the floor rather than to the current release.
*
* The fallback is reached only by a runtime that lacks the global, so workerd never evaluates it.
* It goes through {@link nodeRequire} rather than a bare `require`, which is what makes it work on
* every distribution of this package and not just the bundled ones.
*/ */
const randomUUID: () => string = (() => { const randomUUID = (): string => crypto.randomUUID();
const webCrypto = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;
if (typeof webCrypto?.randomUUID === 'function') return () => webCrypto.randomUUID!();
return nodeRequire<{ randomUUID: () => string }>('node:crypto').randomUUID;
})();
/** /**
* A runtime-neutral inbound request. * A runtime-neutral inbound request.
+27
View File
@@ -0,0 +1,27 @@
// src/http/peer.ts — the socket peer address, handed from the Deno and Bun adapters to `buildFetch`.
// Internal: not exported from the package.
//
// Keyed by the `Request` object rather than carried on it. A header would be visible to handlers and
// spoofable by any client that sent one with the same name; a second `fetch` parameter would be
// public API. The adapters call `app.fetch` with the very object they record, so identity holds, and
// the entry goes when the request does. A `Request` copied from it carries nothing, which is what a
// bare `app.fetch` from user code has always seen.
//
// The map lives on `globalThis` under a registered symbol, not in this module, because this module
// is not always one instance. The CommonJS build bundles `index`, `deno` and `bun` as separate files
// with no shared chunk, so each carries its own copy of this one: a module-private map in
// `@green-tea/core/bun` would record peers that `app.fetch` from `@green-tea/core` never sees. An app
// that loads core both as ESM and as CommonJS has the same split.
const KEY = Symbol.for('@green-tea/core:peer');
const registry = globalThis as { [KEY]?: WeakMap<Request, string> };
const peers = (registry[KEY] ??= new WeakMap<Request, string>());
/** Records `ip` as the peer of `request`. An empty address — a unix socket has none — is not recorded. */
export function setPeer(request: Request, ip: string): void {
if (ip) peers.set(request, ip);
}
/** The peer an adapter recorded for `request`, or `''` when none did. */
export function peerOf(request: Request): string {
return peers.get(request) ?? '';
}
+5
View File
@@ -1,8 +1,13 @@
import type http from 'http'; import type http from 'http';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { declaresOverLimit } from './body';
/** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */ /** Reads the full request body, enforcing the max-bytes ceiling (throws 413 if exceeded). */
export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> { export async function readBody(req: http.IncomingMessage, maxBodyBytes: number): Promise<Buffer | undefined> {
// A declared length over the limit is refused without waiting for the first chunk, which could
// otherwise sit until the request timeout. The fetch adapter makes the same check.
if (declaresOverLimit(req.headers['content-length'], maxBodyBytes)) throw new HttpError(413, 'Payload Too Large');
const chunks: Buffer[] = []; const chunks: Buffer[] = [];
let total = 0; let total = 0;
+43 -3
View File
@@ -18,6 +18,7 @@ import {
} from './core'; } from './core';
import type { BodyFailure, BodyReader } from './body'; import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types'; import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
interface HandlerConfig { interface HandlerConfig {
@@ -78,7 +79,7 @@ export function createHttpServer(
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000; server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000; server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_000;
server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000; server.keepAliveTimeout = opts?.limits?.keepAliveTimeoutMs ?? 5_000;
attachWs(server, wsRoutes, bus, meshControl, opts?.streams); attachWs(server, wsRoutes, bus, meshControl, opts?.streams, opts?.limits);
return server; return server;
} }
@@ -96,7 +97,14 @@ function createRequestHandler(cfg: HandlerConfig) {
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts); const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
const gate = createRequestGate(opts?.limits?.maxConcurrentRequests); const gate = createRequestGate(opts?.limits?.maxConcurrentRequests);
return async (req: http.IncomingMessage, res: http.ServerResponse): Promise<void> => { // `http.createServer` ignores the promise a listener returns, so a rejection that escapes `serve`
// would be an `unhandledRejection` — and under Node's default mode, the end of the process.
// Caught here, at the one place every request passes through (#108).
return (req: http.IncomingMessage, res: http.ServerResponse): void => {
serve(req, res).catch((err: unknown) => failSafe(res, err, opts?.logger));
};
async function serve(req: http.IncomingMessage, res: http.ServerResponse): Promise<void> {
// Install the security-header patch BEFORE any routing/response so every path // Install the security-header patch BEFORE any routing/response so every path
// (200, 404, error, stream) writes headers through the same patched writeHead. // (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy); const secure = deriveSecure(req, trustProxy);
@@ -192,7 +200,39 @@ function createRequestHandler(cfg: HandlerConfig) {
res.writeHead(result.outcome.status, result.outcome.headers); res.writeHead(result.outcome.status, result.outcome.headers);
res.end(result.outcome.body); res.end(result.outcome.body);
}; }
}
/**
* The last resort for a request whose handling rejected. Deliberately does not call `onError`: this
* runs because something already failed past the point where errors convert to a response, and user
* code that may be the thing failing is the wrong place to send it. Must never throw — nothing
* catches it.
*
* Writable: a fixed 500 with `connection: close`, still through the patched `writeHead`, so the
* security headers land. Output already started, or the client gone: there is no honest response
* left to send, so the socket is destroyed and the client sees a truncated reply rather than a
* complete-looking one. No `request:end` is emitted — observers do not alter the response, and the
* core never completed this request.
*/
function failSafe(res: http.ServerResponse, err: unknown, logger: Logger | undefined): void {
try {
logger?.error('request listener failed', { err: err instanceof Error ? err.message : String(err) });
} catch {
/* a broken logger must not stop the response below */
}
if (res.headersSent || res.destroyed || !res.writable) {
res.destroy();
return;
}
try {
res.writeHead(500, { 'content-type': 'application/json', connection: 'close' });
res.end('{"error":"Internal Server Error"}');
} catch {
res.destroy();
}
} }
/** /**
+25
View File
@@ -16,6 +16,31 @@ export interface RequestLimits {
headersTimeoutMs?: number; // default 10_000 headersTimeoutMs?: number; // default 10_000
keepAliveTimeoutMs?: number; // default 5_000 keepAliveTimeoutMs?: number; // default 5_000
maxParts?: number; // default 1000 maxParts?: number; // default 1000
/**
* Largest inbound WebSocket message, in bytes (UTF-8 bytes for text), per connection. Default
* `1_048_576` (1 MiB). A larger message closes the connection with `1009` (`message too large`);
* a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws.
*
* Node and Bun refuse an oversized frame before buffering it (`ws`'s `maxPayload`, Bun's
* `maxPayloadLength`). Bun then drops the connection without a close frame, so on Bun the peer
* sees `1006` instead of `1009`. Deno and the edge offer no such option: there the runtime
* receives the whole message first, so its memory is bounded by the platform's own cap, and this
* limit is checked after receipt — the connection still closes `1009`.
*
* Server-level only; there is no per-route override.
*/
maxWsMessageBytes?: number;
/**
* Inbound WebSocket messages a connection may hold that the handler has not read yet. Default
* `16`. One more closes the connection with `1013` (`inbound queue full`) rather than dropping
* anything, so a handler that never reads `inbound` is closed once its peer sends 17 messages.
* Must be a positive integer, or `createApp` throws. Applies on every runtime.
*
* Worst-case buffered inbound memory is about `maxConnections × maxWsQueue × maxWsMessageBytes`:
* ≈ 15.6 GiB at the defaults on Node. Deno and Bun have no connection cap, so cap connections at
* the platform or proxy there. Server-level only; there is no per-route override.
*/
maxWsQueue?: number;
} }
/** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */ /** Options controlling server construction: limits, TLS, proxy trust, security headers, CORS, and body parsing. */
+66 -18
View File
@@ -11,7 +11,8 @@ import {
type Preflight, type Preflight,
} from './core'; } from './core';
import { mergeInjectedHeaders } from './headers'; import { mergeInjectedHeaders } from './headers';
import type { BodyFailure, BodyReader, MaybePromise } from './body'; import { peerOf } from './peer';
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
import { HttpError } from '../signals'; import { HttpError } from '../signals';
import { renderError, type ErrorRequest } from '../transformers'; import { renderError, type ErrorRequest } from '../transformers';
import type { RouteDef, HttpOptions } from './types'; import type { RouteDef, HttpOptions } from './types';
@@ -97,9 +98,9 @@ function headersToRecord(headers: Headers): Record<string, string> {
/** /**
* The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer. * The fetch half of body acquisition: bytes out of the `Request`, and the over-limit answer.
* *
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body * Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
* or not at all, so the limit can only be checked once the bytes are already in memory. That * the whole body or not at all and so could only check the limit once every byte was in memory.
* difference is exactly why the limit is passed in rather than applied by the shared core. * Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
*/ */
function readFetchBytes( function readFetchBytes(
source: unknown, source: unknown,
@@ -110,8 +111,54 @@ function readFetchBytes(
// Not `async`: a bodiless request answers without allocating a promise at all. // Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined }; if (!request.body) return { bytes: undefined };
return request.arrayBuffer().then((arrayBuffer) => { // A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
if (arrayBuffer.byteLength > limit) { // effort: it tells the runtime to stop the upload, and a refusal changes nothing about the answer.
if (declaresOverLimit(request.headers.get('content-length'), limit)) {
request.body.cancel().catch(() => {});
return tooLarge(request, opts);
}
// ponytail: one reader loop; a TransformStream byte-counter only if another consumer needs it
return readBounded(request.body.getReader(), limit).then((bytes) =>
bytes === null ? tooLarge(request, opts) : { bytes },
);
}
/**
* Reads until the stream ends, or until the running total crosses `limit` — then cancels the reader,
* so no further chunk is pulled, and answers null. A rejected `read()` (the client went away)
* propagates exactly as a rejected `arrayBuffer()` used to.
*
* workerd may strip `content-length` from a chunked upload, so there this count is the only check.
* The answer is the same 413 either way; only how early it comes differs.
*/
async function readBounded(
reader: ReadableStreamDefaultReader<Uint8Array>,
limit: number,
): Promise<Buffer | undefined | null> {
const chunks: Uint8Array[] = [];
let total = 0;
for (;;) {
const { done, value } = await reader.read();
if (done) break;
total += value.byteLength;
if (total > limit) {
reader.cancel().catch(() => {});
return null;
}
chunks.push(value);
}
return total === 0 ? undefined : Buffer.concat(chunks, total);
}
/** The over-limit answer, shared by the declared-length check and the stream count. */
function tooLarge(request: Request, opts: HttpOptions | undefined): BodyFailure {
// Rebuilt here rather than captured per request: only an over-limit body ever needs it, and // Rebuilt here rather than captured per request: only an over-limit body ever needs it, and
// a `url`/`headers` pair captured up-front cost more than the work it saved. // a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url); const url = new URL(request.url);
@@ -121,10 +168,6 @@ function readFetchBytes(
headers: headersToRecord(request.headers), headers: headersToRecord(request.headers),
}; };
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) }; return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
} }
/** /**
@@ -176,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
return new Response(body, { status: result.outcome.status, headers }); return new Response(body, { status: result.outcome.status, headers });
} }
/** The first `x-forwarded-for` hop when the proxy is trusted, else `''`. */
function forwardedFor(headers: Record<string, string>, opts: HttpOptions | undefined): string {
if (!opts?.trustProxy) return '';
return String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim();
}
/** /**
* Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses: * Builds a Web-Standards `fetch(request)` handler over the same route table the Node adapter uses:
* describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it * describes the request for the runtime-neutral {@link handle}, supplies the {@link BodyReader} it
@@ -244,14 +296,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
source: request, source: request,
secure, secure,
// Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the // Mirrors Node's `deriveIp` (src/http/request.ts): only trust `x-forwarded-for` when the
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable, and // proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
// there's no socket peer address to fall back to on the fetch path, so the untrusted case // Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
// is simply ''. // `app.fetch` has none, so there the answer is still ''.
ip: opts?.trustProxy ip: forwardedFor(headers, opts) || peerOf(request),
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
}, },
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to // Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request. // one call per request.
+19 -5
View File
@@ -1,4 +1,4 @@
import { channel } from '../channel'; import { channel, type Channel } from '../channel';
import type { App } from '../app/types'; import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core'; import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
*/ */
const decoder = new TextDecoder(); const decoder = new TextDecoder();
const CONNECTING = 0; // WebSocket.CONNECTING
const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient const OPEN = 1; // WebSocket.OPEN — same constant in every runtime; avoids a per-runtime ambient
/** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */ /** Decodes a host `message` payload to the string the core expects (parity with Node's Buffer.toString()). */
@@ -69,7 +70,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
ac.abort(); ac.abort();
}); });
return neutralSocket(host, inbound, ac); const socket = neutralSocket(host, inbound, ac);
const closeNow = socket.close;
// Deno hands the socket over still CONNECTING: its 101 has not gone out yet, and a close in
// that state is a no-op, so a route that refuses straight away (1008) left the peer hanging.
// Deferring to 'open' is what lets that close reach the client at all.
return Object.assign(socket, {
close: (code?: number, reason?: string) => {
if (host.readyState === CONNECTING) host.addEventListener('open', () => closeNow(code, reason));
else closeNow(code, reason);
},
});
} }
/** /**
@@ -79,7 +91,7 @@ export function eventSocket(host: EventfulSocket): WsSocket {
*/ */
export function neutralSocket( export function neutralSocket(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void }, host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>, inbound: Channel<unknown>,
ac: AbortController, ac: AbortController,
): WsSocket { ): WsSocket {
return { return {
@@ -112,8 +124,10 @@ export function neutralSocket(
export type SocketCtor = new (url: string) => EventfulSocket; export type SocketCtor = new (url: string) => EventfulSocket;
/** /**
* The WebSocket client implementation: the platform global where it exists (Deno, Bun, and * The WebSocket client implementation: the platform global where it exists, else the `ws`
* Node >= 22), else the `ws` optional peer — Node 18-21, our declared floor, has no global. * optional peer. Every supported runtime has the global — Deno, Bun, and Node from 22, the
* declared floor — so the fallback is reached only when Node runs with the global switched off
* (`--no-experimental-websocket`). `ws` is installed anyway for the server side.
* *
* Both expose the same `addEventListener` API and deliver text frames as `event.data` strings, * Both expose the same `addEventListener` API and deliver text frames as `event.data` strings,
* so one bridge covers both. That is verified rather than assumed: `ws` implements the * so one bridge covers both. That is verified rather than assumed: `ws` implements the
+215 -1
View File
@@ -1,8 +1,9 @@
import { isHttpError } from '../signals'; import { isHttpError } from '../signals';
import { CHANNEL_TAP, type TappableChannel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { correlateRequest } from './core'; import { correlateRequest } from './core';
import { matchPattern } from './router'; import { matchPattern } from './router';
import type { WsRouteDef } from './types'; import type { WsRouteDef, RequestLimits } from './types';
/** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */ /** Neutral, runtime-free WebSocket request context (replaces the raw Node req). */
export interface WsRequest { export interface WsRequest {
@@ -22,6 +23,219 @@ export interface WsSocket {
terminate(): void; terminate(): void;
} }
/** Default for `limits.maxWsMessageBytes`: 1 MiB. */
export const DEFAULT_MAX_WS_MESSAGE_BYTES = 1_048_576;
/** Default for `limits.maxWsQueue`, in undelivered inbound messages per connection (D1). */
export const DEFAULT_MAX_WS_QUEUE = 16;
/**
* Where `createApp` leaves the resolved `maxWsMessageBytes` for `serveBun`, which needs it as
* Bun's native `maxPayloadLength` and has no other path to the app's options. Internal, not part
* of the public `App` type; `Symbol.for` because each tsup entry carries its own copy of this
* module, and only the global registry resolves to one symbol across them.
*/
export const WS_MAX_MESSAGE_BYTES: unique symbol = Symbol.for('green-tea.ws-max-message-bytes');
/** The effective `limits.maxWsMessageBytes`. */
export function wsMessageBytes(limits: Pick<RequestLimits, 'maxWsMessageBytes'> | undefined): number {
return limits?.maxWsMessageBytes ?? DEFAULT_MAX_WS_MESSAGE_BYTES;
}
/** Throws when a WebSocket limit is present but not a positive safe integer (#107). */
export function validateWsLimits(limits: RequestLimits | undefined): void {
for (const key of ['maxWsMessageBytes', 'maxWsQueue'] as const) {
const value: unknown = limits?.[key];
if (value === undefined || (Number.isSafeInteger(value) && (value as number) > 0)) continue;
const shown = typeof value === 'string' ? `'${value}'` : String(value);
throw new TypeError(`limits.${key} must be a positive integer, got ${shown}`);
}
}
const encoder = new TextEncoder();
/** True when `msg`'s UTF-8 encoding is longer than `max` bytes. */
function exceedsBytes(msg: unknown, max: number): boolean {
if (typeof msg !== 'string') return false; // every adapter delivers strings; nothing else to measure
// A UTF-16 unit encodes to 1–3 UTF-8 bytes, so both bounds below are exact. Only a string in
// between pays for the encode — which is never one of the short messages that dominate.
if (msg.length * 3 <= max) return false;
if (msg.length > max) return true;
return encoder.encode(msg).byteLength > max;
}
/**
* Bounds a socket's inbound side (#107): a frame over `maxWsMessageBytes` closes `1009`, and a
* frame that arrives while `maxWsQueue` frames are still undelivered closes `1013`. Nothing is
* dropped silently — the peer learns which bound it hit from the close code.
*
* Subscribes to `socket.inbound` immediately. `channel` is fan-out, so a frame pushed with no
* subscriber is lost; subscribing here, before any boot or step runs, is what keeps the first
* frames — for the mesh control channel, the `hello` itself. Those early frames go to the first
* consumer. After that the returned `inbound` fans out like `channel`: each iterator gets every
* frame from the moment it subscribes, through its own queue, and the bound applies to each queue.
* Every other capability is the original socket's.
*/
export function boundInbound(
socket: WsSocket,
limits?: Pick<RequestLimits, 'maxWsMessageBytes' | 'maxWsQueue'>,
): WsSocket {
const fanout = new InboundFanout(socket, wsMessageBytes(limits), limits?.maxWsQueue ?? DEFAULT_MAX_WS_QUEUE);
const tap = (socket.inbound as Partial<TappableChannel<unknown>>)[CHANNEL_TAP];
if (tap) fanout.tap(tap);
else void fanout.pump();
return Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => fanout.subscribe() } },
}) as WsSocket;
}
/** The fan-out behind {@link boundInbound}: one bounded queue per consumer. */
class InboundFanout {
private readonly subs = new Set<InboundSub>();
/** Holds the frames that arrive before anyone reads; handed to the first consumer. */
private first: InboundSub | null;
private ended = false;
private failure: { err: unknown } | null = null;
constructor(
private readonly socket: WsSocket,
private readonly maxBytes: number,
private readonly maxQueue: number,
) {
this.first = this.add();
}
/**
* Reads the adapter's channel inside its `push`. Runtimes emit a whole read's worth of frames
* synchronously — `ws` does — so a bound checked after the event loop yields is checked after an
* unbounded queue has already taken the burst. Here each frame is bounded before it is queued.
*/
tap(tap: TappableChannel<unknown>[typeof CHANNEL_TAP]): void {
const untap = tap({
push: (msg) => {
if (this.ended || this.accept(msg)) return;
untap();
this.settle();
},
end: () => this.settle(),
fail: (err) => this.settle({ err }),
});
}
// ponytail: only for an inbound that is not a channel (no adapter builds one); bounds late.
async pump(): Promise<void> {
try {
for await (const msg of this.socket.inbound) {
if (this.ended || !this.accept(msg)) break;
}
this.settle();
} catch (err) {
this.settle({ err });
}
}
subscribe(): AsyncIterator<unknown> {
const sub = this.first ?? this.add();
this.first = null;
return sub;
}
private add(): InboundSub {
const sub = new InboundSub(() => this.subs.delete(sub));
if (this.ended) sub.settle(this.failure ?? undefined);
else this.subs.add(sub);
return sub;
}
/** Delivers or queues one frame for every consumer; returns false once it has closed the socket. */
private accept(msg: unknown): boolean {
if (exceedsBytes(msg, this.maxBytes)) {
this.socket.close(1009, 'message too large');
return false;
}
// Capacity first, for every consumer: a frame that overflows one queue reaches none, so a
// rejected frame cannot run some handlers' side effects and not others'.
for (const sub of this.subs) {
if (sub.full(this.maxQueue)) {
this.socket.close(1013, 'inbound queue full');
return false;
}
}
for (const sub of this.subs) sub.offer(msg);
return true;
}
/** Ends every consumer once, cleanly or with a failure; whatever is still queued is delivered first. */
private settle(failure?: { err: unknown }): void {
if (this.ended) return;
this.ended = true;
this.failure = failure ?? null;
for (const sub of this.subs) sub.settle(failure);
this.subs.clear();
}
}
/** One consumer's queue; it is its own async iterator. */
class InboundSub implements AsyncIterator<unknown> {
private readonly queue: unknown[] = [];
private waiter: { resolve: (r: IteratorResult<unknown>) => void; reject: (e: unknown) => void } | null = null;
private ended = false;
private failure: { err: unknown } | null = null;
constructor(private readonly onReturn: () => void) {}
/** True when `max` frames are already waiting and no `next()` is there to take another. */
full(max: number): boolean {
return !this.waiter && this.queue.length >= max;
}
/** Hands `msg` to a waiting `next()` or queues it; callers check {@link full} first. */
offer(msg: unknown): void {
const waiter = this.waiter;
if (waiter) {
this.waiter = null;
waiter.resolve({ value: msg, done: false });
return;
}
this.queue.push(msg);
}
next(): Promise<IteratorResult<unknown>> {
if (this.queue.length) return Promise.resolve({ value: this.queue.shift(), done: false });
if (this.failure) return Promise.reject(this.failure.err);
if (this.ended) return Promise.resolve({ value: undefined, done: true });
return new Promise((resolve, reject) => {
this.waiter = { resolve, reject };
});
}
// A consumer that stops reading has said it wants no more; queueing for it would only close
// the connection for a bound it no longer cares about. Other consumers keep receiving.
return(): Promise<IteratorResult<unknown>> {
this.queue.length = 0;
this.onReturn();
this.settle();
return Promise.resolve({ value: undefined, done: true });
}
settle(failure?: { err: unknown }): void {
if (this.ended) return;
this.ended = true;
this.failure = failure ?? null;
const waiter = this.waiter;
this.waiter = null;
if (!waiter) return;
if (failure) waiter.reject(failure.err);
else waiter.resolve({ value: undefined, done: true });
}
}
/** Finds the first ws route whose pattern matches `path`, capturing its params. */ /** Finds the first ws route whose pattern matches `path`, capturing its params. */
export function matchWsRoute( export function matchWsRoute(
wsRoutes: WsRouteDef[], wsRoutes: WsRouteDef[],
+64 -14
View File
@@ -1,8 +1,17 @@
import type http from 'http'; import type http from 'http';
import { channel } from '../channel'; import { channel } from '../channel';
import type { Bus } from '../bus'; import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core'; import {
import type { WsRouteDef, MeshControl } from './types'; runWsConnection,
matchWsRoute,
trackUntil,
boundInbound,
wsMessageBytes,
type WsSocket,
type WsRequest,
} from './ws-core';
import type { WsRouteDef, MeshControl, RequestLimits } from './types';
import { normalizeRequestPath } from './router';
import { nodeRequire } from '../node-require'; import { nodeRequire } from '../node-require';
/** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */ /** Lazily loads the optional `ws` peer dependency's `WebSocketServer`, or null when it is not installed. */
@@ -16,9 +25,9 @@ function loadWss(): any | null {
} }
} }
/** Writes a 501 Not Implemented status to the raw socket and destroys it. */ /** Writes a bodyless HTTP status to the raw socket and destroys it. */
function reject501(socket: any): void { function rejectUpgrade(socket: any, status: number, text: string): void {
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n'); socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
socket.destroy(); socket.destroy();
} }
@@ -31,11 +40,12 @@ function handleMeshUpgrade(
socket: any, socket: any,
head: Buffer, head: Buffer,
streams?: Set<() => void>, streams?: Set<() => void>,
limits?: RequestLimits,
): boolean { ): boolean {
if (path !== meshControl.path) return false; if (path !== meshControl.path) return false;
if (!wss) { if (!wss) {
reject501(socket); rejectUpgrade(socket, 501, 'Not Implemented');
return true; return true;
} }
@@ -45,7 +55,7 @@ function handleMeshUpgrade(
// an untracked control channel leaves the teapot's server.close() waiting on it forever. // an untracked control channel leaves the teapot's server.close() waiting on it forever.
// serveFrames swallows its own failures, so the floating promise cannot reject. // serveFrames swallows its own failures, so the floating promise cannot reject.
wss.handleUpgrade(req, socket, head, (ws: any) => { wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = nodeSocket(ws); const neutral = boundInbound(nodeSocket(ws), limits);
void trackUntil(neutral, meshControl.handle(neutral), streams); void trackUntil(neutral, meshControl.handle(neutral), streams);
}); });
@@ -97,29 +107,69 @@ export function attachWs(
bus?: Bus, bus?: Bus,
meshControl?: MeshControl, meshControl?: MeshControl,
streams?: Set<() => void>, streams?: Set<() => void>,
limits?: RequestLimits,
): void { ): void {
if (wsRoutes.length === 0 && !meshControl) return; if (wsRoutes.length === 0 && !meshControl) return;
const WebSocketServer = loadWss(); const WebSocketServer = loadWss();
const wss = WebSocketServer ? new WebSocketServer({ noServer: true }) : null; // `maxPayload` is the pre-buffer half of `maxWsMessageBytes`: `ws` refuses an oversized frame,
// fragmented or not, before it is assembled, and closes 1009 itself. `boundInbound` repeats the
// check on the decoded text, which is the only half Deno and the edge have.
const wss = WebSocketServer ? new WebSocketServer({ noServer: true, maxPayload: wsMessageBytes(limits) }) : null;
server.on('upgrade', (req, socket, head) => { server.on('upgrade', (req, socket, head) => {
const path = (req.url ?? '/').split('?')[0]; // A peer that resets mid-rejection must not raise an unhandled 'error' on a socket nobody
// else is listening to yet: that is as fatal as a throw.
socket.on('error', () => {});
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams)) return; // Nothing thrown in here may escape. This is a raw EventEmitter listener, so a throw is an
// uncaught exception that takes the whole process down, not a 500 for one client.
try {
routeUpgrade({ wss, wsRoutes, bus, meshControl, streams, limits }, req, socket, head);
} catch {
if (socket.writable) rejectUpgrade(socket, 500, 'Internal Server Error');
else socket.destroy();
}
});
}
/** What every upgrade on one server shares. */
interface UpgradeEnv {
wss: any;
wsRoutes: WsRouteDef[];
bus?: Bus;
meshControl?: MeshControl;
streams?: Set<() => void>;
limits?: RequestLimits;
}
/** Routes one upgrade: validates the path the way HTTP does, then mesh control, then the ws route table. */
function routeUpgrade(env: UpgradeEnv, req: http.IncomingMessage, socket: any, head: Buffer): void {
const { wss, wsRoutes, bus, meshControl, streams, limits } = env;
let path: string;
// The same normalization the HTTP path runs (`dispatch` in core.ts). Without it a malformed
// escape reaches `decodeURIComponent` in the matcher and throws, and `//` silently matches.
try {
path = normalizeRequestPath((req.url ?? '/').split('?')[0]);
} catch {
rejectUpgrade(socket, 400, 'Bad Request');
return;
}
if (meshControl && handleMeshUpgrade(wss, meshControl, path, req, socket, head, streams, limits)) return;
const route = matchWsRoute(wsRoutes, path); const route = matchWsRoute(wsRoutes, path);
if (!route) { if (!route) {
socket.destroy(); rejectUpgrade(socket, 404, 'Not Found');
return; return;
} }
if (!wss) { if (!wss) {
reject501(socket); rejectUpgrade(socket, 501, 'Not Implemented');
return; return;
} }
wss.handleUpgrade(req, socket, head, (ws: any) => { wss.handleUpgrade(req, socket, head, (ws: any) => {
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams); void runWsConnection(boundInbound(nodeSocket(ws), limits), nodeWsRequest(req), route, bus, streams);
});
}); });
} }
+49 -6
View File
@@ -86,9 +86,40 @@ export interface StaticHit {
/** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */ /** Resolves a URL path to a static file under a fixed root, or `undefined` for a miss. */
export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>; export type StaticResolver = (urlPath: string) => Promise<StaticHit | undefined>;
/** The real path of `path` when it is `root` or lies beneath it, else `undefined`. Rejects on ENOENT.
* The separator suffix keeps a sibling such as `root-evil` out of `root`. */
async function confine(fs: typeof import('node:fs'), sep: string, root: string, path: string) {
const real = await fs.promises.realpath(path);
return real === root || real.startsWith(root + sep) ? real : undefined;
}
/** Reads `full` (or its `index.html` when a directory) if its real path stays inside the real `root`. */
async function readConfined(
fs: typeof import('node:fs'),
nodePath: typeof import('node:path'),
root: string,
full: string,
): Promise<StaticHit | undefined> {
let real = await confine(fs, nodePath.sep, root, full);
if (!real) return undefined;
const isDir = (await fs.promises.stat(real)).isDirectory();
// `index.html` is a second resolution and can itself be a link, so it is confined on its own.
if (isDir) real = await confine(fs, nodePath.sep, root, nodePath.join(real, 'index.html'));
if (!real) return undefined;
// ponytail: a link swapped between `realpath` and `readFile` can still escape. Exploiting it needs
// write access inside the served root, which already owns the app; closing it needs `O_NOFOLLOW`
// on every path component, which Node, Deno and Bun do not offer portably.
const body = await fs.promises.readFile(real);
// The content-type follows the requested name, not the link target (`app.js -> app.3f2a.js`).
const target = isDir ? nodePath.join(full, 'index.html') : full;
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
}
/** /**
* Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at * Builds a static-file resolver rooted at `root` (`true` → `./public`). Requires a filesystem: throws at
* boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss. * boot on a runtime without one (edge). Path-traversal-safe — a resolved path outside the root is a miss,
* and so is a symlink whose real target lies outside the root's real path (#106). Escapes are misses
* (404), not 403, so a probe cannot tell "exists outside the root" from "does not exist".
*/ */
export function buildStaticResolver(root: string | true): StaticResolver { export function buildStaticResolver(root: string | true): StaticResolver {
let fs: typeof import('node:fs'); let fs: typeof import('node:fs');
@@ -105,6 +136,18 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root); const abs = nodePath.resolve(process.cwd(), root === true ? 'public' : root);
// The root's real path, resolved once on the first request rather than at build time, so a missing
// `public/` at boot is still not fatal — it just makes every request a miss, as before. Containment
// compares real paths, so the root must be real too: a symlinked `public/` would otherwise fail every
// check. Cached for the life of the app: re-pointing a root symlink at runtime needs a restart. A failed
// lookup is not cached, so a root created after boot starts serving, as it did before.
let realRoot: Promise<string | undefined> | undefined;
const resolveRoot = () =>
(realRoot ??= fs.promises.realpath(abs).catch(() => {
realRoot = undefined;
return undefined;
}));
return async (urlPath) => { return async (urlPath) => {
let rel: string; let rel: string;
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel)); const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
const rootReal = await resolveRoot();
if (!rootReal) return undefined;
try { try {
const stat = await fs.promises.stat(full); return await readConfined(fs, nodePath, rootReal, full);
const target = stat.isDirectory() ? nodePath.join(full, 'index.html') : full;
const body = await fs.promises.readFile(target);
return { body, contentType: contentTypeFor(nodePath.extname(target)) };
} catch { } catch {
return undefined; return undefined; // includes ENOENT from `realpath` on a dangling link: a miss, never a rejection
} }
}; };
} }
+24 -1
View File
@@ -12,7 +12,16 @@ class Rt {
})(); })();
} }
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Route('/room')
class Room {
@Ws('/:name')
join(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt, Room] })
class M {} class M {}
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
@@ -96,4 +105,18 @@ describe('app.upgrade', () => {
await app.upgrade(req, socket); await app.upgrade(req, socket);
expect(closedCode).toBe(1008); expect(closedCode).toBe(1008);
}); });
it.each(['/rt/%E0%A4%A', '/room/%E0%A4%A', '//rt//echo'])(
'closes 1008 on the malformed path %s instead of rejecting (#104)',
async (url) => {
const { socket } = fakeSocket();
let closed: [number | undefined, string | undefined] | undefined;
socket.close = (c, r) => {
closed = [c, r];
};
const req: WsRequest = { url, headers: {}, protocol: 'http', ip: '' };
await app.upgrade(req, socket);
expect(closed).toEqual([1008, 'invalid request path']);
},
);
}); });
+87
View File
@@ -0,0 +1,87 @@
// #105 on the real Bun runtime: the request-body limit is enforced while the body is read, both on
// `app.fetch` directly and through `serveBun`. The counting stream is what proves the read stopped —
// a 413 looks the same whether the body was buffered first or not.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
import { countingStream } from '../helpers/counting-stream.ts';
const LIMIT = 1_000_000; // the server default
const SMALL = 1000;
@Route('/')
class Ctl {
@Post('/echo') echo(@body() b: unknown) {
return { length: String(b).length };
}
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
// writing a large body when the 413 lands can see a reset instead — the transport racing the
// answer, not a different answer.
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
expect(res.status).toBe(413);
expect(source.pulled).toBe(0);
expect(source.cancelled).toBe(true);
await app.close();
});
test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream));
expect(res.status).toBe(413);
expect(source.pulled).toBeLessThanOrEqual(5);
expect(source.cancelled).toBe(true);
await app.close();
});
test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
const app = createApp({ modules: [M] });
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
expect(at.status).toBe(200);
expect(await at.json()).toEqual({ length: LIMIT });
expect(over.status).toBe(413);
await app.close();
});
test('T11 serveBun: the same statuses over a real socket', async () => {
const server = await serveBun(createApp({ modules: [M] }), { port: 0 });
const base = `http://127.0.0.1:${server.port}`;
// A fresh connection per request. Bun's *client* reuses a kept-alive socket after a response that
// arrived before the server read the request body, and its next request on that socket comes back
// 400 or 431. Node's fetch against the same Bun server does not (Bun 1.3.14), so it is the client
// that misbehaves, not `serveBun`.
const send = (body: BodyInit, headers?: Record<string, string>) =>
fetch(post(`${base}/small`, body, headers), { keepalive: false } as RequestInit);
try {
expect((await send(new Uint8Array(2 * SMALL))).status).toBe(413);
expect((await send(countingStream(10, 300).stream)).status).toBe(413);
expect((await send('x'.repeat(SMALL), { 'content-type': 'text/plain' })).status).toBe(200);
expect((await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' })).status).toBe(413);
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+63
View File
@@ -0,0 +1,63 @@
// #116 on the real Bun runtime: `serveBun` hands the socket's peer address to `ctx.ip`, the way
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
// address — the rate-limit plugin above all — put the whole internet in one bucket.
//
// Run with: npm run test:bun (or: bun test test/bun/)
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { createServer } from 'node:net';
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
import { serveBun } from '../../src/bun.ts';
@Route('/')
class Ctl {
@Get('/ip') ip(@ctx() c: { ip: string }) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function ipVia(
hostname: string,
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
): Promise<string> {
const server = await serveBun(createApp({ modules: [M], trustProxy: opts.trustProxy }), { hostname, port: 0 });
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
try {
const res = await fetch(`http://${host}:${server.port}/ip`, { headers: opts.headers });
return ((await res.json()) as { ip: string }).ip;
} finally {
await server.close({ timeoutMs: 1000 });
}
}
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
const ipv6Available = await new Promise<boolean>((resolve) => {
const probe = createServer();
probe.once('error', () => resolve(false));
probe.listen(0, '::1', () => probe.close(() => resolve(true)));
});
test('T2 serveBun: ctx.ip is the socket peer address', async () => {
expect(await ipVia('127.0.0.1')).toBe('127.0.0.1');
});
// Skipped, not failed: the host has no IPv6 loopback to connect over.
test.skipIf(!ipv6Available)('T3 serveBun: an IPv6 peer is passed through as Bun reports it', async () => {
expect(await ipVia('::1')).toBe('::1');
});
test('T4 serveBun: trustProxy takes the first x-forwarded-for hop', async () => {
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
expect(ip).toBe('203.0.113.7');
});
test('T5 serveBun: trustProxy without x-forwarded-for falls back to the peer', async () => {
expect(await ipVia('127.0.0.1', { trustProxy: true })).toBe('127.0.0.1');
});
test('T6 serveBun: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
expect(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } })).toBe('127.0.0.1');
});
+51
View File
@@ -0,0 +1,51 @@
// Static-file confinement (#106) under the real Bun runtime, which reaches `realpath` through its
// `node:fs` compat — a third implementation of symlink resolution, so not something to assume from
// the Node suite.
//
// Run with: npm run test:bun
import 'reflect-metadata';
import { test, expect } from 'bun:test';
import { mkdirSync, mkdtempSync, symlinkSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createApp } from '../../src/index.ts';
const base = mkdtempSync(join(tmpdir(), 'gt-static-bun-'));
const root = join(base, 'root');
mkdirSync(join(root, 'sub'), { recursive: true });
writeFileSync(join(root, 'a.txt'), 'in root');
writeFileSync(join(root, 'sub', 'index.html'), '<h1>Sub</h1>');
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
symlinkSync('a.txt', join(root, 'in-link'));
symlinkSync('../secret.txt', join(root, 'out-link'));
symlinkSync('../nope.txt', join(root, 'dangling'));
symlinkSync('root', join(base, 'root-alias'));
const app = createApp({ modules: [], static: root });
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
test('static on Bun: a link to a file outside the root is a miss', async () => {
const res = await get('/out-link');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
test('static on Bun: a link to a file inside the root is served', async () => {
const res = await get('/in-link');
expect(res.status).toBe(200);
expect(await res.text()).toBe('in root');
});
test('static on Bun: a dangling link is a 404, not a rejection', async () => {
expect((await get('/dangling')).status).toBe(404);
});
test('static on Bun: a root that is itself a symlink still serves its files', async () => {
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
const a = await aliased.fetch(new Request('http://x/a.txt'));
expect(a.status).toBe(200);
expect(await a.text()).toBe('in root');
const sub = await aliased.fetch(new Request('http://x/sub/'));
expect(sub.status).toBe(200);
expect(await sub.text()).toBe('<h1>Sub</h1>');
});
+90
View File
@@ -20,6 +20,22 @@ class Rt {
for await (const msg of inbound) yield `echo:${msg}`; for await (const msg of inbound) yield `echo:${msg}`;
})(); })();
} }
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Module({ mountpoint: '/', controllers: [Rt] })
class M {} class M {}
@@ -47,3 +63,77 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
server.stop(true); server.stop(true);
} }
}); });
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
test('serveBun: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
});
expect(closed).toEqual({ code: 1008, reason: 'invalid request path' });
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
expect(httpRes.status).toBe(200);
} finally {
server.stop(true);
}
});
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
function exchange(port: number, path: string, frames: string[], until = 2000) {
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
const replies: string[] = [];
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, until);
ws.onopen = () => frames.forEach((f) => ws.send(f));
ws.onmessage = (e) => replies.push(String(e.data));
ws.onclose = (e) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
};
});
}
// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Its
// uWebSockets core drops the TCP connection without a close frame, so the peer sees `1006`, not
// the `1009` Node, Deno and the edge send. Asserted rather than papered over: it is the documented
// Bun difference, and a Bun upgrade that starts sending 1009 should fail here and be noticed.
test('serveBun: ws message size and inbound queue limits', async () => {
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
expect(over.close?.code).toBe(1006);
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' });
} finally {
server.stop(true);
}
});
test('serveBun: ws message size default is 1 MiB', async () => {
const app = createApp({ modules: [M] });
const server = await serveBun(app, { port: 0 });
const port = server.port;
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
expect(atLimit.replies.length).toBe(1);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
expect(over.close?.code).toBe(1006);
} finally {
server.stop(true);
}
});
+95
View File
@@ -0,0 +1,95 @@
// #105 on the real Deno runtime: the request-body limit is enforced while the body is read, both on
// `app.fetch` directly and through `serveDeno`. The counting stream is what proves the read stopped —
// a 413 looks the same whether the body was buffered first or not.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Post, Module, body } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
import { countingStream } from '../helpers/counting-stream.ts';
const LIMIT = 1_000_000; // the server default
const SMALL = 1000;
@Route('/')
class Ctl {
@Post('/echo') echo(@body() b: unknown) {
return { length: String(b).length };
}
// Small for the socket tests, so every refused body fits in the socket buffer. A client still
// writing a large body when the 413 lands can see a reset instead — the transport racing the
// answer, not a different answer.
@Post('/small', { maxBodyBytes: SMALL }) small(@body() b: unknown) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
const post = (url: string, body: BodyInit, headers: Record<string, string> = {}) =>
new Request(url, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
Deno.test('T1 app.fetch: a declared content-length over the limit is refused unread', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream, { 'content-length': '2000000' }));
assertEquals(res.status, 413);
assertEquals(source.pulled, 0);
assertEquals(source.cancelled, true);
await app.close();
});
Deno.test('T3 app.fetch: a streamed body stops at the chunk that crosses the limit', async () => {
const app = createApp({ modules: [M] });
const source = countingStream(10, 300_000);
const res = await app.fetch(post('http://x/echo', source.stream));
assertEquals(res.status, 413);
if (source.pulled > 5) throw new Error(`pulled ${source.pulled} chunks — the read did not stop at the limit`);
assertEquals(source.cancelled, true);
await app.close();
});
Deno.test('T5 app.fetch: exactly the limit is accepted, one byte over is refused', async () => {
const app = createApp({ modules: [M] });
const at = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT), { 'content-type': 'text/plain' }));
const over = await app.fetch(post('http://x/echo', 'x'.repeat(LIMIT + 1), { 'content-type': 'text/plain' }));
assertEquals(at.status, 200);
assertEquals(await at.json(), { length: LIMIT });
assertEquals(over.status, 413);
await over.body?.cancel();
await app.close();
});
Deno.test('T11 serveDeno: the same statuses over a real socket', async () => {
const server = await serveDeno(createApp({ modules: [M] }), { port: 0, onListen: () => {} });
const base = `http://127.0.0.1:${(server as unknown as { addr: { port: number } }).addr.port}`;
try {
const send = (body: BodyInit, headers?: Record<string, string>) => fetch(post(`${base}/small`, body, headers));
const declared = await send(new Uint8Array(2 * SMALL));
assertEquals(declared.status, 413);
await declared.body?.cancel();
const streamed = await send(countingStream(10, 300).stream);
assertEquals(streamed.status, 413);
await streamed.body?.cancel();
const at = await send('x'.repeat(SMALL), { 'content-type': 'text/plain' });
assertEquals(at.status, 200);
await at.body?.cancel();
const over = await send('x'.repeat(SMALL + 1), { 'content-type': 'text/plain' });
assertEquals(over.status, 413);
await over.body?.cancel();
} finally {
await server.close({ timeoutMs: 1000 });
}
});
+73
View File
@@ -0,0 +1,73 @@
// #116 on the real Deno runtime: `serveDeno` hands the socket's peer address to `ctx.ip`, the way
// Node's `listen()` always has. Without it every client shared `''`, so anything keyed on the
// address — the rate-limit plugin above all — put the whole internet in one bucket.
//
// Run with: npm run test:deno
import 'reflect-metadata';
import { assertEquals } from 'jsr:@std/assert';
import { createApp, Route, Get, Module, ctx } from '../../src/index.ts';
import { serveDeno } from '../../src/deno.ts';
@Route('/')
class Ctl {
@Get('/ip') ip(@ctx() c: { ip: string }) {
return { ip: c.ip };
}
}
@Module({ mountpoint: '/', controllers: [Ctl] })
class M {}
async function ipVia(
hostname: string,
opts: { trustProxy?: boolean; headers?: Record<string, string> } = {},
): Promise<string> {
const server = await serveDeno(createApp({ modules: [M], trustProxy: opts.trustProxy }), {
hostname,
port: 0,
onListen: () => {},
});
const port = (server as unknown as { addr: { port: number } }).addr.port;
const host = hostname.includes(':') ? `[${hostname}]` : hostname;
try {
const res = await fetch(`http://${host}:${port}/ip`, { headers: opts.headers });
return ((await res.json()) as { ip: string }).ip;
} finally {
await server.close({ timeoutMs: 1000 });
}
}
/** Whether this host can bind the IPv6 loopback at all; CI containers often cannot. */
function ipv6Available(): boolean {
try {
Deno.listen({ hostname: '::1', port: 0 }).close();
return true;
} catch {
return false;
}
}
Deno.test('T1 serveDeno: ctx.ip is the socket peer address', async () => {
assertEquals(await ipVia('127.0.0.1'), '127.0.0.1');
});
Deno.test({
name: 'T3 serveDeno: an IPv6 peer is passed through as Deno reports it',
ignore: !ipv6Available(), // skipped, not failed: the host has no IPv6 loopback to connect over
fn: async () => {
assertEquals(await ipVia('::1'), '::1');
},
});
Deno.test('T4 serveDeno: trustProxy takes the first x-forwarded-for hop', async () => {
const ip = await ipVia('127.0.0.1', { trustProxy: true, headers: { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' } });
assertEquals(ip, '203.0.113.7');
});
Deno.test('T5 serveDeno: trustProxy without x-forwarded-for falls back to the peer', async () => {
assertEquals(await ipVia('127.0.0.1', { trustProxy: true }), '127.0.0.1');
});
Deno.test('T6 serveDeno: without trustProxy a spoofed x-forwarded-for is ignored', async () => {
assertEquals(await ipVia('127.0.0.1', { headers: { 'x-forwarded-for': '1.2.3.4' } }), '127.0.0.1');
});
+37
View File
@@ -74,3 +74,40 @@ Deno.test('multipart resolves the busboy peer dependency instead of reporting it
assertEquals(await res.json(), { name: 'joe', filename: 'p.png' }); assertEquals(await res.json(), { name: 'joe', filename: 'p.png' });
await app.close(); await app.close();
}); });
// #106 on Deno, which reaches `realpath` through its `node:fs` compat. Committed symlinks rather than
// a temp tree, for the same `--allow-write` reason as above; `secret.txt` sits beside the root.
const linked = 'test/fixtures/static';
Deno.test('static: a link to a file outside the root is a miss', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/out-link'));
assertEquals(res.status, 404);
assertEquals((await res.text()).includes('TOP SECRET'), false);
await app.close();
});
Deno.test('static: a link to a file inside the root is served', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
const res = await app.fetch(new Request('http://x/in-link'));
assertEquals(res.status, 200);
assertEquals(await res.text(), 'in root');
await app.close();
});
Deno.test('static: a dangling link is a 404, not a rejection', async () => {
const app = createApp({ modules: [], static: `${linked}/root` });
assertEquals((await app.fetch(new Request('http://x/dangling'))).status, 404);
await app.close();
});
Deno.test('static: a root that is itself a symlink still serves its files', async () => {
const app = createApp({ modules: [], static: `${linked}/root-alias` });
const a = await app.fetch(new Request('http://x/a.txt'));
assertEquals(a.status, 200);
assertEquals(await a.text(), 'in root');
const sub = await app.fetch(new Request('http://x/sub/'));
assertEquals(sub.status, 200);
assertEquals(await sub.text(), '<h1>Sub</h1>');
await app.close();
});
+112
View File
@@ -28,6 +28,22 @@ class Rt {
for await (const msg of inbound) yield `echo:${msg}`; for await (const msg of inbound) yield `echo:${msg}`;
})(); })();
} }
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Module({ mountpoint: '/', controllers: [Rt] })
@@ -69,3 +85,99 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
await server.shutdown(); await server.shutdown();
} }
}); });
// #104: a malformed escape in a param segment used to reject out of the matcher and close 1011.
Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps serving', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const ws = new WebSocket(`ws://127.0.0.1:${port}/rt/room/%E0%A4%A`);
const closed = await new Promise<{ code: number; reason: string }>((resolve) => {
ws.onclose = (e) => resolve({ code: e.code, reason: e.reason });
});
assertEquals(closed, { code: 1008, reason: 'invalid request path' });
const httpRes = await fetch(`http://127.0.0.1:${port}/rt/hello`);
assertEquals(httpRes.status, 200);
await httpRes.body?.cancel();
} finally {
await server.shutdown();
}
});
/** Opens `path`, sends `frames` once open, and resolves with every reply and the close. */
function exchange(port: number, path: string, frames: string[], until = 2000) {
const ws = new WebSocket(`ws://127.0.0.1:${port}${path}`);
const replies: string[] = [];
return new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, until);
ws.onopen = () => frames.forEach((f) => ws.send(f));
ws.onmessage = (e) => replies.push(String(e.data));
ws.onclose = (e) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
};
});
}
// #107: on Deno the runtime receives the whole message before user code sees it, so the size
// bound is checked after receipt — the close code is the same as on Node and Bun.
Deno.test('serveDeno: ws message size and inbound queue limits', async () => {
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1024)], 300);
assertEquals(atLimit.replies, [`echo:${'a'.repeat(1024)}`]);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
assertEquals(over.close, { code: 1009, reason: 'message too large' });
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
assertEquals(full.close, { code: 1013, reason: 'inbound queue full' });
} finally {
await server.shutdown();
}
});
Deno.test('serveDeno: ws message size default is 1 MiB', async () => {
const app = createApp({ modules: [M] });
let port = 0;
const server = await serveDeno(app, {
port: 0,
onListen: (addr) => {
port = addr.port;
},
});
await new Promise((resolve) => setTimeout(resolve, 50));
try {
const atLimit = await exchange(port, '/rt/echo', ['a'.repeat(1_048_576)], 500);
assertEquals(atLimit.replies.length, 1);
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
assertEquals(over.close?.code, 1009);
} finally {
await server.shutdown();
}
});
+75 -1
View File
@@ -66,6 +66,33 @@ async function main() {
assert.equal(httpRes.status, 200); assert.equal(httpRes.status, 200);
assert.deepEqual(await httpRes.json(), { ok: true }); assert.deepEqual(await httpRes.json(), { ok: true });
// Body limits (#105): the same statuses as app.fetch, Deno and Bun. workerd may drop a
// chunked upload's content-length, so the streamed case is enforced by the read count alone.
const LIMIT = 1000; // the route's maxBodyBytes, see worker.ts
const post = async (body: Uint8Array | string | ReadableStream<Uint8Array>): Promise<number> => {
const res = await mf.dispatchFetch('http://localhost/rt/body', {
method: 'POST',
headers: { 'content-type': 'text/plain' },
body,
duplex: 'half',
} as Parameters<typeof mf.dispatchFetch>[1]);
await res.arrayBuffer();
return res.status;
};
const chunks = (count: number, size: number): ReadableStream<Uint8Array> => {
let sent = 0;
return new ReadableStream({
pull(controller) {
if (sent++ === count) controller.close();
else controller.enqueue(new Uint8Array(size).fill(0x61));
},
});
};
assert.equal(await post(new Uint8Array(2 * LIMIT)), 413, 'declared content-length over the limit');
assert.equal(await post(chunks(10, 300)), 413, 'streamed body over the limit');
assert.equal(await post('x'.repeat(LIMIT)), 200, 'exactly the limit');
assert.equal(await post('x'.repeat(LIMIT + 1)), 413, 'one byte over the limit');
// WebSocket // WebSocket
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', { const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
headers: { Upgrade: 'websocket' }, headers: { Upgrade: 'websocket' },
@@ -84,12 +111,59 @@ async function main() {
}); });
assert.equal(got, 'echo:hi'); assert.equal(got, 'echo:hi');
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS'); // #104: a malformed escape in a param segment closes 1008 instead of 1011, and HTTP still serves.
const badRes = await mf.dispatchFetch('http://localhost/rt/room/%E0%A4%A', {
headers: { Upgrade: 'websocket' },
});
const bad = badRes.webSocket;
assert.ok(bad, 'expected a client webSocket on the 101 response');
const closed = new Promise<{ code: number; reason: string }>((resolve) =>
bad.addEventListener('close', (e: { code: number; reason: string }) => resolve({ code: e.code, reason: e.reason })),
);
bad.accept();
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
// #107: workerd delivers the whole message before user code sees it, so the size bound is
// checked after receipt; the close codes match Node and Deno.
const limitedEcho = async (frames: string[]) => exchange(mf, 'http://limited/rt/echo', frames);
assert.deepEqual((await limitedEcho(['a'.repeat(1024)])).replies, [`echo:${'a'.repeat(1024)}`]);
assert.deepEqual((await limitedEcho(['a'.repeat(1025)])).close, { code: 1009, reason: 'message too large' });
assert.deepEqual((await exchange(mf, 'http://limited/rt/stall', ['1', '2', '3', '4', '5'])).close, {
code: 1013,
reason: 'inbound queue full',
});
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_576)])).replies.length, 1);
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
console.log('edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits — PASS');
} finally { } finally {
await mf.dispose(); await mf.dispose();
} }
} }
/** Opens a ws on `url`, sends `frames`, and resolves with the replies and the close (or none within `ms`). */
async function exchange(mf: Miniflare, url: string, frames: string[], ms = 1000) {
const res = await mf.dispatchFetch(url, { headers: { Upgrade: 'websocket' } });
const ws = res.webSocket;
assert.ok(ws, `expected a client webSocket on the 101 response for ${url}`);
const replies: string[] = [];
const result = new Promise<{ replies: string[]; close?: { code: number; reason: string } }>((resolve) => {
const timer = setTimeout(() => {
ws.close();
resolve({ replies });
}, ms);
ws.addEventListener('message', (e: { data: unknown }) => replies.push(String(e.data)));
ws.addEventListener('close', (e: { code: number; reason: string }) => {
clearTimeout(timer);
resolve({ replies, close: { code: e.code, reason: e.reason } });
});
});
ws.accept();
for (const frame of frames) ws.send(frame);
return result;
}
main().catch((err) => { main().catch((err) => {
console.error(err); console.error(err);
process.exit(1); process.exit(1);
+32 -2
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test. // Worker entry for the real workerd (Miniflare) integration test.
// Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven // Mirrors test/deno/ws.test.ts's graph so HTTP + WebSocket behavior is proven
// identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts). // identically across runtimes. Run via `npm run test:edge` (see test/edge/run.ts).
import { createApp, Route, Get, Ws, ctx, Module } from '../../src/index'; import { createApp, Route, Get, Post, Ws, body, ctx, Module } from '../../src/index';
import { edgeHandler } from '../../src/edge'; import { edgeHandler } from '../../src/edge';
@Route('/rt') @Route('/rt')
@@ -11,17 +11,47 @@ class Rt {
return { ok: true }; return { ok: true };
} }
// #105: the body limit, read from workerd's own request stream. Small, so every refused body still
// fits in the socket buffer: a client that is mid-upload when the 413 lands can see ECONNRESET
// instead, which is the transport racing the answer rather than a different answer.
@Post('/body', { maxBodyBytes: 1000 })
body(@body() b: unknown) {
return { length: String(b).length };
}
@Ws('/echo') @Ws('/echo')
echo(@ctx() { inbound }: any) { echo(@ctx() { inbound }: any) {
return (async function* () { return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`; for await (const msg of inbound) yield `echo:${msg}`;
})(); })();
} }
// Never reads `inbound`, so every frame the client sends stays queued (#107).
@Ws('/stall')
stall() {
return (async function* () {
await new Promise<never>(() => {});
yield '';
})();
}
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
} }
@Module({ mountpoint: '/', controllers: [Rt] }) @Module({ mountpoint: '/', controllers: [Rt] })
class M {} class M {}
const app = createApp({ modules: [M] }); const app = createApp({ modules: [M] });
// #107: the same graph with tight ws limits, reached through the `limited` host.
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
export default { fetch: edgeHandler(app) }; export default {
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
};
+155 -1
View File
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect, vi } from 'vitest';
import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index'; import { createApp, Provider, Route, Get, Post, Module, needs, body, ctx } from '../src/index';
import { countingStream } from './helpers/counting-stream';
import { setPeer } from '../src/http/peer';
@Provider({ provides: 'store' }) @Provider({ provides: 'store' })
class Store { class Store {
@@ -108,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
); );
expect(await res.json()).toEqual({ ip: '' }); expect(await res.json()).toEqual({ ip: '' });
}); });
// #116: the Deno and Bun adapters now hand `buildFetch` the socket peer. A bare `app.fetch` from
// user code has none to hand, so it must keep answering exactly what it did before.
it('T7: bare app.fetch without peer metadata is unchanged', async () => {
const untrusting = createApp({ modules: [IpModule] });
const trusting = createApp({ modules: [IpModule], trustProxy: true });
expect(await (await untrusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
expect(await (await trusting.fetch(new Request('http://x/ip/whoami'))).json()).toEqual({ ip: '' });
expect(
await (
await trusting.fetch(new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '9.9.9.9' } }))
).json(),
).toEqual({ ip: '9.9.9.9' });
});
it('the peer an adapter recorded reaches ctx.ip, and trustProxy without XFF falls back to it', async () => {
const untrusting = createApp({ modules: [IpModule] });
const trusting = createApp({ modules: [IpModule], trustProxy: true });
const spoofed = new Request('http://x/ip/whoami', { headers: { 'x-forwarded-for': '1.2.3.4' } });
const plain = new Request('http://x/ip/whoami');
setPeer(spoofed, '127.0.0.1');
setPeer(plain, '::1');
expect(await (await untrusting.fetch(spoofed)).json()).toEqual({ ip: '127.0.0.1' });
expect(await (await trusting.fetch(plain)).json()).toEqual({ ip: '::1' });
});
// The published CommonJS build bundles `index`, `deno` and `bun` as separate files, each with its
// own copy of every module they share, so `serveBun` from `@green-tea/core/bun` and `app.fetch`
// from `@green-tea/core` do not run the same `peer.ts`. A store private to the module would be two
// stores, and the peer recorded by one would never be found by the other.
it('a second copy of the peer module sees the peer the first one recorded', async () => {
const request = new Request('http://x/');
setPeer(request, '192.0.2.1'); // through the copy this file imported
vi.resetModules();
const copy = await import('../src/http/peer');
expect(copy.setPeer).not.toBe(setPeer); // really a second instance of the module
expect(copy.peerOf(request)).toBe('192.0.2.1');
});
it('T8: only the adapter\'s own Request carries the peer — a copy of it does not', async () => {
const original = new Request('http://x/ip/whoami');
setPeer(original, '127.0.0.1');
const res = await createApp({ modules: [IpModule] }).fetch(new Request(original));
expect(await res.json()).toEqual({ ip: '' });
});
}); });
describe('app.fetch on a mesh app', () => { describe('app.fetch on a mesh app', () => {
@@ -145,3 +198,104 @@ describe('app.fetch on a mesh app', () => {
} }
}); });
}); });
// #105: the limit is enforced while the body is read, not after it has been buffered. A status code
// cannot tell the two apart — both answer 413 — so the counting stream is what these assert on.
@Route('/limits')
class LimitsCtl {
@Post('/echo') echo(@body() b: any) {
return { got: b };
}
@Post('/small', { maxBodyBytes: 10 }) small(@body() b: any) {
return { got: b };
}
@Post('/large', { maxBodyBytes: 2_000_000 }) large(@body() b: any) {
return { length: String(b).length };
}
}
@Module({ mountpoint: '/', controllers: [LimitsCtl] })
class LimitsModule {}
const post = (path: string, body: RequestInit['body'], headers: Record<string, string> = {}) =>
new Request(`http://x${path}`, { method: 'POST', body, headers, duplex: 'half' } as RequestInit);
describe('app.fetch bounded body reads (#105)', () => {
const limitsApp = createApp({ modules: [LimitsModule] }); // server limit: the 1 MB default
it('T1: a declared content-length over the limit is refused without reading the body', async () => {
const body = countingStream(10, 300_000);
const res = await limitsApp.fetch(post('/limits/echo', body.stream, { 'content-length': '2000000' }));
expect(res.status).toBe(413);
expect(body.pulled).toBe(0);
expect(body.cancelled).toBe(true);
});
it('T3: a streamed body stops at the chunk that crosses the limit, and the reader is cancelled', async () => {
const body = countingStream(10, 300_000); // 3 MB, no content-length
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
expect(res.status).toBe(413);
// 4 read, the 4th crossing 1 MB, plus at most one the stream queued ahead of the reader.
expect(body.pulled).toBeLessThanOrEqual(5);
expect(body.cancelled).toBe(true);
});
it('T4: a body of exactly the limit is accepted', async () => {
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 8) });
expect(Buffer.byteLength(json)).toBe(1_000_000);
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
expect(res.status).toBe(200);
expect(((await res.json()) as any).got.s).toHaveLength(1_000_000 - 8);
});
it('T5: one byte over the limit is refused', async () => {
const json = JSON.stringify({ s: 'x'.repeat(1_000_000 - 7) });
const res = await limitsApp.fetch(post('/limits/echo', json, { 'content-type': 'application/json' }));
expect(res.status).toBe(413);
});
it('T5: one byte over the limit is refused when streamed without a content-length', async () => {
const body = countingStream(1, 1_000_001);
const res = await limitsApp.fetch(post('/limits/echo', body.stream));
expect(res.status).toBe(413);
});
it('T8: a route limit below the server limit wins', async () => {
const res = await limitsApp.fetch(post('/limits/small', 'x'.repeat(11), { 'content-type': 'text/plain' }));
expect(res.status).toBe(413);
});
it('T9: a route limit above the server limit wins', async () => {
const res = await limitsApp.fetch(
post('/limits/large', 'x'.repeat(1_500_000), { 'content-type': 'text/plain' }),
);
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ length: 1_500_000 });
});
it('a malformed content-length is ignored, and the stream count enforces the limit', async () => {
const body = countingStream(1, 20);
const res = await limitsApp.fetch(post('/limits/small', body.stream, { 'content-length': 'nope' }));
expect(res.status).toBe(413);
});
it('T10: a bodiless request is answered without reading anything', async () => {
const res = await limitsApp.fetch(new Request('http://x/limits/echo', { method: 'POST' }));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({});
});
});
+1
View File
@@ -0,0 +1 @@
root
+1
View File
@@ -0,0 +1 @@
in root
+1
View File
@@ -0,0 +1 @@
../nope.txt
+1
View File
@@ -0,0 +1 @@
a.txt
+1
View File
@@ -0,0 +1 @@
../secret.txt
+1
View File
@@ -0,0 +1 @@
<h1>Sub</h1>
+1
View File
@@ -0,0 +1 @@
TOP SECRET
+44
View File
@@ -0,0 +1,44 @@
// A request body that records how much of it was consumed. Web APIs only, so the Node, Deno and Bun
// suites share it: the regression it guards (#105) is "read the whole body before checking the
// limit", which no status code can show on its own — a 413 looks the same either way.
export interface CountingStream {
stream: ReadableStream<Uint8Array>;
/** Chunks the consumer has pulled so far. */
readonly pulled: number;
/** Whether the consumer cancelled the stream. */
readonly cancelled: boolean;
}
/** `count` chunks of `size` bytes each, handed out one per pull. */
export function countingStream(count: number, size: number): CountingStream {
let pulled = 0;
let cancelled = false;
const stream = new ReadableStream<Uint8Array>({
// Pull-based, and only on demand: with a high-water mark of 0 the stream does not pre-fill its
// queue, so `pulled` counts what the consumer asked for. The default of 1 pulls a chunk at
// construction, before anyone reads, and would make "nothing was read" unprovable.
pull(controller) {
if (pulled === count) {
controller.close();
return;
}
pulled++;
controller.enqueue(new Uint8Array(size).fill(0x61));
},
cancel() {
cancelled = true;
},
}, { highWaterMark: 0 });
return {
stream,
get pulled() {
return pulled;
},
get cancelled() {
return cancelled;
},
};
}
+26
View File
@@ -123,6 +123,32 @@ describe('request hardening', () => {
server.close(); server.close();
}); });
// #105: a declared length over the limit is answered before any of the body is sent. Without the
// header check, the reader waits for a first chunk that this client never sends — and times out.
it('T2: rejects a declared content-length over the limit before reading any body', async () => {
let ran = false;
const server = createHttpServer(
[{ method: 'POST', pattern: '/echo', transport: 'buffer',
handler: async () => { ran = true; return { status: 200, headers: {}, body: 'ok' }; } }],
[], undefined, undefined, { limits: { maxBodyBytes: 16 } },
);
await new Promise<void>((r) => server.listen(0, r));
const socket = net.connect((server.address() as any).port, '127.0.0.1');
await once(socket, 'connect');
socket.write('POST /echo HTTP/1.1\r\nHost: x\r\nContent-Length: 2000000\r\n\r\n'); // headers only
let raw = '';
socket.setEncoding('utf8');
socket.on('data', (chunk: string) => (raw += chunk));
await once(socket, 'end');
expect(raw).toMatch(/^HTTP\/1\.1 413 /);
expect(raw.toLowerCase()).toContain('connection: close');
expect(ran).toBe(false);
socket.destroy();
server.close();
}, 2000);
it('sets the configured server timeouts and connection limit', async () => { it('sets the configured server timeouts and connection limit', async () => {
const server = createHttpServer([], [], undefined, undefined, const server = createHttpServer([], [], undefined, undefined,
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } }); { limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
+285
View File
@@ -0,0 +1,285 @@
import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
import http from 'node:http';
import net from 'node:net';
import { once } from 'node:events';
import { Bus } from '../src/bus';
import { createHttpServer } from '../src/http';
import type { HttpOptions, RouteDef } from '../src/http/types';
import type { Logger } from '../src/logger';
// #108: `http.createServer` ignores the promise its listener returns, so a rejection inside the
// request listener used to be an `unhandledRejection` — fatal under Node's default mode. Every test
// here goes through a real socket, because the boundary under test is the Node listener itself.
interface Reply {
status?: number;
headers?: http.IncomingHttpHeaders;
body?: string;
/** Set when the connection ended without a complete response. */
error?: string;
}
/** A GET on a fresh connection (`agent: false`), bounded so a hung listener fails fast instead of at the 30 s request timeout. */
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<Reply> {
return new Promise((resolve) => {
const reply: Reply = {};
const req = http.request({ host: '127.0.0.1', port, path, headers, agent: false }, (res) => {
reply.status = res.statusCode;
reply.headers = res.headers;
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk: string) => (body += chunk));
res.on('end', () => resolve({ ...reply, body }));
res.on('error', (err) => resolve({ ...reply, body, error: err.message }));
res.on('aborted', () => resolve({ ...reply, body, error: 'aborted' }));
});
req.setTimeout(1_000, () => req.destroy(new Error('client timeout')));
req.on('error', (err) => resolve({ ...reply, error: err.message }));
req.end();
});
}
function spyLogger(): Logger & { error: Mock<(...args: unknown[]) => void> } {
return { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() };
}
const ok: RouteDef = {
method: 'GET',
pattern: '/ok',
transport: 'buffer',
handler: async () => ({ status: 200, headers: { 'content-type': 'text/plain' }, body: 'ok' }),
};
const servers: http.Server[] = [];
async function start(routes: RouteDef[], opts: HttpOptions = {}, bus?: Bus): Promise<number> {
const server = createHttpServer([ok, ...routes], [], bus, undefined, opts);
servers.push(server);
server.listen(0, '127.0.0.1');
await once(server, 'listening');
return (server.address() as net.AddressInfo).port;
}
/** T10: after every injected failure, a normal request on a fresh connection still succeeds. */
async function expectServerStillServes(port: number): Promise<void> {
const next = await get(port, '/ok');
expect(next.status).toBe(200);
expect(next.body).toBe('ok');
}
const settle = () => new Promise((r) => setTimeout(r, 20));
let unhandled: Mock<(...args: unknown[]) => void>;
let uncaught: Mock<(...args: unknown[]) => void>;
beforeEach(() => {
unhandled = vi.fn();
uncaught = vi.fn();
process.on('unhandledRejection', unhandled);
process.on('uncaughtException', uncaught);
});
afterEach(async () => {
await settle();
process.off('unhandledRejection', unhandled);
process.off('uncaughtException', uncaught);
for (const server of servers.splice(0)) {
server.closeAllConnections();
server.close();
}
expect(unhandled).not.toHaveBeenCalled();
expect(uncaught).not.toHaveBeenCalled();
});
const rejectingStatic = (reason: unknown) => async () => {
throw reason;
};
describe('Node request-listener boundary (#108)', () => {
it('T1: a rejected request operation while writable answers a minimal 500 and closes', async () => {
const logger = spyLogger();
const port = await start([], { static: rejectingStatic(new Error('boom')), logger });
const res = await get(port, '/missing');
expect(res.status).toBe(500);
expect(res.headers?.connection).toBe('close');
expect(res.headers?.['content-type']).toBe('application/json');
expect(JSON.parse(res.body!)).toEqual({ error: 'Internal Server Error' });
// The security headers still land: the minimal path writes through the patched writeHead.
expect(res.headers?.['x-content-type-options']).toBe('nosniff');
expect(logger.error).toHaveBeenCalledTimes(1);
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'boom' });
await expectServerStillServes(port);
});
it.each([['boom'], [undefined]])('T2: a non-Error rejection (%s) answers 500 and logs String(err)', async (reason) => {
const logger = spyLogger();
const port = await start([], { static: rejectingStatic(reason), logger });
const res = await get(port, '/missing');
expect(res.status).toBe(500);
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: String(reason) });
await expectServerStillServes(port);
});
// Deviation from the card: `originAllowed` already guards a throwing predicate and denies the origin
// (src/security.ts), so this never reaches the listener boundary. Kept as a regression test.
it('T3: a throwing cors.origins predicate denies the origin and serves the request', async () => {
const logger = spyLogger();
const port = await start([], {
logger,
cors: {
origins: () => {
throw new Error('allowlist down');
},
},
});
const res = await get(port, '/ok', { origin: 'https://a.example' });
expect(res.status).toBe(200);
expect(res.headers?.['access-control-allow-origin']).toBeUndefined();
await expectServerStillServes(port);
});
it('T4: an invalid handler header value answers 500 through the minimal path', async () => {
const logger = spyLogger();
const port = await start(
[
{
method: 'GET',
pattern: '/bad-header',
transport: 'buffer',
handler: async () => ({ status: 200, headers: { 'x-bad': 'a\nb' }, body: 'nope' }),
},
],
{ logger },
);
const res = await get(port, '/bad-header');
expect(res.status).toBe(500);
expect(res.headers?.connection).toBe('close');
expect(res.headers?.['x-bad']).toBeUndefined();
expect(logger.error).toHaveBeenCalledTimes(1);
await expectServerStillServes(port);
});
// The card's BigInt injection is caught inside `pipeStream`'s loop and becomes an error frame, so it
// never reaches the boundary; kept as a regression test. The second case fails after the 200 headers
// are flushed but before that loop, which is the "output already started" path.
it('T5a: a stream encoder failure on the first frame ends the stream with an error frame', async () => {
const port = await start([
{
method: 'GET',
pattern: '/big',
transport: 'ndjson',
handler: async () => ({
stream: (async function* () {
yield { n: BigInt(1) };
})(),
}),
},
]);
const res = await get(port, '/big');
expect(res.status).toBe(200);
expect(res.body).toContain('"error"');
await expectServerStillServes(port);
});
it('T5b: a failure after the 200 headers were sent destroys the connection and is logged', async () => {
const logger = spyLogger();
const port = await start(
[
{
method: 'GET',
pattern: '/broken-stream',
transport: 'ndjson',
handler: async () => ({
stream: {
[Symbol.asyncIterator]() {
throw new Error('iterator failed');
},
},
}),
},
],
{ logger },
);
const res = await get(port, '/broken-stream');
expect(res.status).toBe(200);
expect(res.error).toBeDefined();
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'iterator failed' });
await expectServerStillServes(port);
});
it('T6: a throwing onError still sends the built-in 404', async () => {
const logger = spyLogger();
const port = await start([], {
logger,
onError: () => {
throw new Error('renderer broke');
},
});
const res = await get(port, '/missing');
expect(res.status).toBe(404);
await expectServerStillServes(port);
});
it('T7: a throwing request:start observer does not alter the response', async () => {
const bus = new Bus();
bus.on('request:start', () => {
throw new Error('observer broke');
});
const port = await start([], { bus }, bus);
await expectServerStillServes(port);
await expectServerStillServes(port);
});
it('T8: a client abort racing a rejection leaves no unhandled rejection and no write after close', async () => {
const logger = spyLogger();
let rejected!: () => void;
const done = new Promise<void>((r) => (rejected = r));
const port = await start([], {
logger,
static: async () => {
await new Promise((r) => setTimeout(r, 50));
rejected();
throw new Error('late');
},
});
const socket = net.connect(port, '127.0.0.1');
await once(socket, 'connect');
socket.write('GET /missing HTTP/1.1\r\nHost: x\r\n\r\n');
await new Promise((r) => setTimeout(r, 10));
socket.destroy();
await done;
await settle();
expect(logger.error).toHaveBeenCalledWith('request listener failed', { err: 'late' });
await expectServerStillServes(port);
});
it('T9: a rejection releases its maxConcurrentRequests slot', async () => {
const port = await start(
[],
{ static: rejectingStatic(new Error('boom')), limits: { maxConcurrentRequests: 1 }, logger: spyLogger() },
);
expect((await get(port, '/missing')).status).toBe(500);
await expectServerStillServes(port);
await expectServerStillServes(port);
});
});
+3 -3
View File
@@ -56,11 +56,11 @@ function startSkewedTeapot() {
/** /**
* Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the * Both client implementations, exercised on whatever Node runs the suite. `ws` is always in the
* list: it is the Node 18-21 path, and on a modern CI the platform global would otherwise be the * list: it is the fallback for a Node run with the global WebSocket switched off, and every
* only one ever covered — the fallback would rot unnoticed until someone ran the declared floor. * supported Node has the global, so it would otherwise never be covered and rot unnoticed.
*/ */
const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket; const platform = (globalThis as { WebSocket?: SocketCtor }).WebSocket;
const CTORS: [string, SocketCtor][] = [['the ws package (Node < 22 path)', WS as unknown as SocketCtor]]; const CTORS: [string, SocketCtor][] = [['the ws package (fallback path)', WS as unknown as SocketCtor]];
if (platform) CTORS.push(['the platform global WebSocket', platform]); if (platform) CTORS.push(['the platform global WebSocket', platform]);
describe('WebSocket client implementations', () => { describe('WebSocket client implementations', () => {
+75 -1
View File
@@ -1,6 +1,20 @@
import { describe, it, expect, afterEach } from 'vitest'; import { describe, it, expect, afterEach, vi } from 'vitest';
import { createApp, Route, Post, Module, body } from '../src'; import { createApp, Route, Post, Module, body } from '../src';
// Counts calls into the multipart parser while still running the real one, so a test can prove
// busboy was never reached rather than inferring it from the status code.
const parsed = vi.hoisted(() => ({ calls: 0 }));
vi.mock('../src/multipart', async (importOriginal) => {
const real = await importOriginal<typeof import('../src/multipart')>();
return {
...real,
parseMultipart: (...args: Parameters<typeof real.parseMultipart>) => {
parsed.calls++;
return real.parseMultipart(...args);
},
};
});
let app: any; let app: any;
afterEach(async () => { await app?.close(); }); afterEach(async () => { await app?.close(); });
@@ -88,3 +102,63 @@ describe('bodyDuplicates', () => {
expect(await post('/b')).toEqual({ x: ['1', '2'] }); expect(await post('/b')).toEqual({ x: ['1', '2'] });
}); });
}); });
// #105: multipart is parsed from the bytes the bounded reader returns, so the byte limit has to stop
// a request before busboy ever sees it, and `maxParts` has to keep working on what gets through.
describe('multipart limits on app.fetch (#105)', () => {
const form = (fields: number, size = 1) => {
const fd = new FormData();
for (let i = 0; i < fields; i++) fd.set(`f${i}`, 'x'.repeat(size));
return fd;
};
it('T6: a multipart body over maxBodyBytes is 413 and never reaches the parser', async () => {
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
parsed.calls = 0;
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1, 5000) }));
expect(r.status).toBe(413);
expect(parsed.calls).toBe(0);
});
it('T6: the same holds when the multipart body arrives without a content-length', async () => {
@Route('/') class C { @Post('/u', { maxBodyBytes: 1000 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
parsed.calls = 0;
const encoded = new Request('http://x', { method: 'POST', body: form(1, 5000) });
const r = await app.fetch(new Request('http://x/u', {
method: 'POST',
headers: { 'content-type': encoded.headers.get('content-type')! },
body: encoded.body,
duplex: 'half',
} as RequestInit));
expect(r.status).toBe(413);
expect(parsed.calls).toBe(0);
});
it('T7: under the byte limit but over maxParts is 400 Invalid multipart body', async () => {
@Route('/') class C { @Post('/u', { maxParts: 2 }) u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod] });
const r = await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }));
expect(r.status).toBe(400);
expect(await r.text()).toContain('Invalid multipart body');
});
it('T7: the server-level maxParts applies when the route sets none', async () => {
@Route('/') class C { @Post('/u') u(@body() b: any) { return b; } }
@Module({ mountpoint: '/', controllers: [C] }) class CMod {}
app = createApp({ modules: [CMod], limits: { maxParts: 2 } });
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(1) }))).status).toBe(200);
expect((await app.fetch(new Request('http://x/u', { method: 'POST', body: form(3) }))).status).toBe(400);
});
});
-27
View File
@@ -1,27 +0,0 @@
import { describe, expect, it, vi } from 'vitest';
// The `engines` floor is `>=18`, and the global `crypto` only arrived unflagged in Node 19. That gap
// shipped once: `correlateRequest` compiled cleanly against an ambient declaration and then threw
// `ReferenceError: crypto is not defined` on the first request of every Node 18 process.
//
// CI's Node 18 job is what caught it, and this test is what makes it catchable without one — every
// developer machine and every other runtime has the global, so the bug is invisible where it is
// written. Stubbing the global away reproduces the floor's condition on any Node.
//
// If the floor ever moves above 18, this test and the fallback it guards can both go.
describe('correlateRequest without a global crypto (Node 18)', () => {
it('falls back to node:crypto instead of throwing ReferenceError', async () => {
vi.stubGlobal('crypto', undefined);
vi.resetModules();
const { correlateRequest } = await import('../src/http/core');
const a = correlateRequest({});
const b = correlateRequest({});
expect(a.requestId).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
expect(a.requestId).not.toBe(b.requestId);
expect(correlateRequest({ 'x-request-id': 'from-gateway' }).requestId).toBe('from-gateway');
vi.unstubAllGlobals();
});
});
+1 -1
View File
@@ -46,7 +46,7 @@ function runHarness(signal: NodeJS.Signals, env: NodeJS.ProcessEnv = {}, sendTwi
// `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further // `process.execPath -r tsx/cjs`, not `npx tsx`: a wrapper puts the app one process further
// down, and on Linux the signal then lands on the wrapper while the app never hears it — which // down, and on Linux the signal then lands on the wrapper while the app never hears it — which
// is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader` // is exactly how this passed locally and failed in CI. `-r` rather than `--import`/`--loader`
// because it is the one form that works on both the Node 18 floor CI builds against and the // because it is the one form that works on both the Node 22 floor CI builds against and the
// current release. // current release.
const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], { const proc = spawn(process.execPath, ['-r', 'tsx/cjs', 'test/interop/_signal-app.ts'], {
env: { ...process.env, ...env }, env: { ...process.env, ...env },
+108 -1
View File
@@ -1,9 +1,11 @@
import { describe, expect, it } from 'vitest'; import { describe, expect, it } from 'vitest';
import { writeFileSync, mkdirSync } from 'node:fs'; import { writeFileSync, mkdirSync, mkdtempSync, symlinkSync } from 'node:fs';
import { join } from 'node:path'; import { join } from 'node:path';
import { tmpdir } from 'node:os'; import { tmpdir } from 'node:os';
import { createApp, Route, Get, Module } from '../src/index'; import { createApp, Route, Get, Module } from '../src/index';
import { buildStaticResolver } from '../src/views'; import { buildStaticResolver } from '../src/views';
import { isHttpError } from '../src/signals';
import type { ErrorRenderer } from '../src/transformers';
const root = join(tmpdir(), 'gt-static-test'); const root = join(tmpdir(), 'gt-static-test');
mkdirSync(root, { recursive: true }); mkdirSync(root, { recursive: true });
@@ -67,3 +69,108 @@ describe('static serving', () => {
expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined(); expect(await resolve('/%2e%2e/gt-secret.txt')).toBeUndefined();
}); });
}); });
// #106: the traversal guard above is lexical, and `stat`/`readFile` follow symlinks, so a link
// inside the root could serve a file outside it. Confinement has to compare real paths. On macOS
// `tmpdir()` is itself behind a symlink (`/var` → `/private/var`), so every case below also
// exercises a root whose lexical and real paths differ.
describe('static serving confined to the real root (#106)', () => {
const base = mkdtempSync(join(tmpdir(), 'gt-static-real-'));
const sroot = join(base, 'root');
mkdirSync(join(sroot, 'sub'), { recursive: true });
mkdirSync(join(sroot, 'idx'));
mkdirSync(join(base, 'root-evil'));
mkdirSync(join(base, 'outside'));
writeFileSync(join(sroot, 'a.txt'), 'in root');
writeFileSync(join(sroot, 'sub', 'index.html'), '<h1>Sub</h1>');
writeFileSync(join(base, 'root-evil', 'x.txt'), 'SIBLING');
writeFileSync(join(base, 'secret.txt'), 'TOP SECRET');
writeFileSync(join(base, 'outside', 's.txt'), 'OUTSIDE');
// Windows without the symlink privilege refuses to create links; the cases that need them skip
// there rather than pass vacuously.
let symlinks = true;
try {
symlinkSync('a.txt', join(sroot, 'in-link'));
symlinkSync('../secret.txt', join(sroot, 'out-link'));
symlinkSync('../outside', join(sroot, 'dir-link'));
symlinkSync('../nope.txt', join(sroot, 'dangling'));
symlinkSync('../root-evil/x.txt', join(sroot, 'evil-link'));
symlinkSync('../../secret.txt', join(sroot, 'idx', 'index.html'));
symlinkSync('root', join(base, 'root-alias'));
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== 'EPERM') throw err;
symlinks = false;
}
const withLinks = it.skipIf(!symlinks);
const app = createApp({ modules: [], static: sroot });
const get = (path: string) => app.fetch(new Request(`http://x${path}`));
withLinks('T1: does not serve a link to a file outside the root', async () => {
const res = await get('/out-link');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
withLinks('T2: serves a link to a file inside the root', async () => {
const res = await get('/in-link');
expect(res.status).toBe(200);
expect(await res.text()).toBe('in root');
});
withLinks('T3: a symlinked directory cannot expose an out-of-root file', async () => {
expect((await get('/dir-link/s.txt')).status).toBe(404);
});
it('T4: a sibling-prefix directory is not reachable by traversal', async () => {
expect((await get('/../root-evil/x.txt')).status).toBe(404);
expect((await get('/%2e%2e/root-evil/x.txt')).status).toBe(404);
});
withLinks('T5: a real path in a sibling-prefix directory is outside the root', async () => {
const resolve = buildStaticResolver(sroot);
expect(await resolve('/../root-evil/x.txt')).toBeUndefined();
// Passes the lexical guard, then really lands in `root-evil` — only the `root + sep` rule on the
// real path stops it.
expect(await resolve('/evil-link')).toBeUndefined();
});
withLinks('T6: a dangling link is a miss, not a rejection', async () => {
await expect(buildStaticResolver(sroot)('/dangling')).resolves.toBeUndefined();
expect((await get('/dangling')).status).toBe(404);
});
withLinks('T7: a directory index that links outside the root is a miss', async () => {
const res = await get('/idx/');
expect(res.status).toBe(404);
expect(await res.text()).not.toContain('TOP SECRET');
});
withLinks('T8: a root that is itself a symlink still serves its files', async () => {
const aliased = createApp({ modules: [], static: join(base, 'root-alias') });
const a = await aliased.fetch(new Request('http://x/a.txt'));
expect(a.status).toBe(200);
expect(await a.text()).toBe('in root');
const sub = await aliased.fetch(new Request('http://x/sub/'));
expect(sub.status).toBe(200);
expect(await sub.text()).toBe('<h1>Sub</h1>');
});
withLinks('T10: an escape renders through onError exactly like a plain miss', async () => {
const onError: ErrorRenderer = (error) => ({
status: isHttpError(error) ? error.status : 500,
headers: { 'content-type': 'text/html' },
body: `<h1>${isHttpError(error) ? error.status : 500}</h1>`,
});
const custom = createApp({ modules: [], static: sroot, onError });
const escape = await custom.fetch(new Request('http://x/out-link'));
const miss = await custom.fetch(new Request('http://x/nope.txt'));
expect(escape.status).toBe(404);
expect(escape.headers.get('content-type')).toBe('text/html');
expect(await escape.text()).toBe(await miss.text());
});
});
it('a root created after the first request starts serving without a restart', async () => {
const late = join(mkdtempSync(join(tmpdir(), 'gt-static-late-')), 'public');
const resolve = buildStaticResolver(late);
expect(await resolve('/a.txt')).toBeUndefined();
mkdirSync(late);
writeFileSync(join(late, 'a.txt'), 'late');
expect((await resolve('/a.txt'))?.body.toString()).toBe('late');
});
+379
View File
@@ -0,0 +1,379 @@
import { describe, it, expect, afterEach } from 'vitest';
import type http from 'http';
import WebSocket from 'ws';
import { createApp, Route, Ws, Module, ctx } from '../src/index';
import type { RequestLimits } from '../src/index';
import { channel } from '../src/channel';
import { boundInbound, type WsSocket } from '../src/http/ws-core';
// #107 / D1: per-connection bounds on inbound WebSocket messages. Node runs the real `ws` server
// behind `listen(0)`; the other runtimes are covered in test/deno, test/bun and test/edge.
const never = new Promise<never>(() => {});
@Route('/rt')
class Rt {
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${(msg as string).length}`;
})();
}
// Never reads `inbound`: every frame the client sends stays queued.
@Ws('/stall')
stall() {
return (async function* () {
await never;
yield '';
})();
}
// Reads exactly one frame, acknowledges it, then stalls.
@Ws('/one')
one(@ctx() { inbound }: any) {
return (async function* () {
const it = (inbound as AsyncIterable<unknown>)[Symbol.asyncIterator]();
await it.next();
yield 'took-one';
await never;
})();
}
}
@Module({ mountpoint: '/', controllers: [Rt] })
class M {}
const servers: http.Server[] = [];
const clients: WebSocket[] = [];
afterEach(async () => {
clients.splice(0).forEach((c) => c.terminate());
await Promise.all(servers.splice(0).map((s) => new Promise((r) => s.close(r))));
});
async function serve(limits?: RequestLimits): Promise<number> {
const server = await createApp({ modules: [M], limits }).listen(0);
servers.push(server);
return (server.address() as { port: number }).port;
}
async function connect(port: number, path: string) {
const client = new WebSocket(`ws://127.0.0.1:${port}${path}`);
clients.push(client);
const messages: string[] = [];
client.on('message', (d) => messages.push(d.toString()));
const closed = new Promise<{ code: number; reason: string }>((r) =>
client.on('close', (code, reason) => r({ code, reason: reason.toString() })),
);
await new Promise((r) => client.on('open', r));
return { client, messages, closed };
}
/** Resolves with the close if it happens within `ms`, else 'open'. */
const closedWithin = (closed: Promise<{ code: number; reason: string }>, ms = 150) =>
Promise.race([closed, new Promise<'open'>((r) => setTimeout(() => r('open'), ms))]);
const until = async (cond: () => boolean) => {
for (let i = 0; i < 100 && !cond(); i++) await new Promise((r) => setTimeout(r, 10));
};
/** Binary payload of `n` bytes that is valid UTF-8 (ASCII), so its decoded size equals its wire size. */
const binary = (n: number) => Buffer.alloc(n, 0x62);
describe('limits.maxWsMessageBytes on Node (#107)', () => {
const limits = { maxWsMessageBytes: 1024 };
it('T1: a text message of exactly the limit is delivered', async () => {
const { client, messages } = await connect(await serve(limits), '/rt/echo');
client.send('a'.repeat(1024));
await until(() => messages.length > 0);
expect(messages).toEqual(['echo:1024']);
client.close();
});
it('T2: a binary message of exactly the limit is delivered', async () => {
const { client, messages } = await connect(await serve(limits), '/rt/echo');
client.send(binary(1024));
await until(() => messages.length > 0);
expect(messages).toEqual(['echo:1024']);
client.close();
});
it('T3: one byte of text over the limit closes 1009', async () => {
const { client, closed } = await connect(await serve(limits), '/rt/echo');
client.send('a'.repeat(1025));
expect((await closed).code).toBe(1009);
});
it('T4: one byte of binary over the limit closes 1009', async () => {
const { client, closed } = await connect(await serve(limits), '/rt/echo');
client.send(binary(1025));
expect((await closed).code).toBe(1009);
});
it('T5: the limit counts UTF-8 bytes, not characters', async () => {
const { client, closed } = await connect(await serve(limits), '/rt/echo');
client.send('€'.repeat(342)); // 342 UTF-16 units, 1026 UTF-8 bytes
expect((await closed).code).toBe(1009);
});
it('T6: a fragmented message is measured whole', async () => {
const { client, closed } = await connect(await serve(limits), '/rt/echo');
client.send('a'.repeat(400), { fin: false });
client.send('a'.repeat(400), { fin: false });
client.send('a'.repeat(400), { fin: true });
expect((await closed).code).toBe(1009);
});
});
describe('limits.maxWsQueue on Node (#107)', () => {
const limits = { maxWsQueue: 4 };
it('T7: a stalled consumer with the queue exactly full stays open', async () => {
const { client, closed } = await connect(await serve(limits), '/rt/stall');
for (let i = 0; i < 4; i++) client.send(`m${i}`);
expect(await closedWithin(closed)).toBe('open');
client.close();
});
it('T8: one more frame than the queue holds closes 1013, inbound queue full', async () => {
const { client, closed } = await connect(await serve(limits), '/rt/stall');
for (let i = 0; i < 5; i++) client.send(`m${i}`);
expect(await closed).toEqual({ code: 1013, reason: 'inbound queue full' });
});
it('T9: the bound counts undelivered frames, so a delivered one frees a slot', async () => {
const { client, messages, closed } = await connect(await serve(limits), '/rt/one');
for (let i = 0; i < 4; i++) client.send(`m${i}`);
await until(() => messages.length > 0);
expect(messages).toEqual(['took-one']);
client.send('m4'); // 3 left queued + this one = 4
expect(await closedWithin(closed)).toBe('open');
client.close();
});
});
describe('ws limit defaults on Node (#107)', () => {
it('T10: 1 MiB is accepted and 1 MiB + 1 closes 1009', async () => {
const port = await serve();
const ok = await connect(port, '/rt/echo');
ok.client.send('a'.repeat(1_048_576));
await until(() => ok.messages.length > 0);
expect(ok.messages).toEqual(['echo:1048576']);
ok.client.close();
const over = await connect(port, '/rt/echo');
over.client.send('a'.repeat(1_048_577));
expect((await over.closed).code).toBe(1009);
});
it('T10: 16 queued frames are held and the 17th closes 1013', async () => {
const port = await serve();
const held = await connect(port, '/rt/stall');
for (let i = 0; i < 16; i++) held.client.send(`m${i}`);
expect(await closedWithin(held.closed)).toBe('open');
held.client.close();
const over = await connect(port, '/rt/stall');
for (let i = 0; i < 17; i++) over.client.send(`m${i}`);
expect((await over.closed).code).toBe(1013);
});
});
describe('ws limit validation (#107)', () => {
it.each([
['maxWsQueue', 0],
['maxWsQueue', -1],
['maxWsQueue', 1.5],
['maxWsQueue', '16'],
['maxWsQueue', NaN],
['maxWsMessageBytes', 0],
['maxWsMessageBytes', -1],
['maxWsMessageBytes', 1.5],
['maxWsMessageBytes', '16'],
['maxWsMessageBytes', Infinity],
])('T11: limits.%s = %s fails createApp with a TypeError naming the key', (key, value) => {
expect(() => createApp({ modules: [M], limits: { [key]: value } as RequestLimits })).toThrow(
new RegExp(`^limits\\.${key} must be a positive integer`),
);
expect(() => createApp({ modules: [M], limits: { [key]: value } as RequestLimits })).toThrow(TypeError);
});
it('accepts positive integers and absent keys', () => {
expect(() => createApp({ modules: [M], limits: { maxWsQueue: 1, maxWsMessageBytes: 1 } })).not.toThrow();
expect(() => createApp({ modules: [M], limits: {} })).not.toThrow();
});
});
/** A WsSocket over a channel that records closes. */
function fakeSocket() {
const inbound = channel<unknown>();
const closes: Array<[number | undefined, string | undefined]> = [];
const socket: WsSocket = {
inbound,
abort: new AbortController().signal,
isOpen: true,
send: () => {},
close: (code, reason) => closes.push([code, reason]),
terminate: () => {},
};
return { socket, inbound, closes };
}
const tick = () => new Promise((r) => setTimeout(r, 0));
describe('boundInbound (#107)', () => {
it('T15: delivers frames in order to a waiting consumer and to a late one', async () => {
const { socket, inbound } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 4 });
const it = bounded.inbound[Symbol.asyncIterator]();
const first = it.next();
inbound.push('a');
expect(await first).toEqual({ value: 'a', done: false });
inbound.push('b');
inbound.push('c');
await tick();
expect(await it.next()).toEqual({ value: 'b', done: false });
expect(await it.next()).toEqual({ value: 'c', done: false });
});
it('T15: subscribes immediately, so frames sent before the consumer arrives are kept', async () => {
const { socket, inbound } = fakeSocket();
const bounded = boundInbound(socket);
await tick();
inbound.push('early');
await tick();
expect(await bounded.inbound[Symbol.asyncIterator]().next()).toEqual({ value: 'early', done: false });
});
it('T15: closes 1009 on an oversized frame and never delivers it', async () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsMessageBytes: 3 });
await tick();
inbound.push('€'); // 3 bytes: fits
inbound.push('€a'); // 4 bytes
await tick();
expect(closes).toEqual([[1009, 'message too large']]);
const it = bounded.inbound[Symbol.asyncIterator]();
expect(await it.next()).toEqual({ value: '€', done: false });
expect((await it.next()).done).toBe(true);
});
it('T15: closes 1013 on overflow, delivers what was queued, then ends', async () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 2 });
await tick();
for (const m of ['a', 'b', 'c']) inbound.push(m);
await tick();
expect(closes).toEqual([[1013, 'inbound queue full']]);
const got: unknown[] = [];
for await (const m of bounded.inbound) got.push(m);
expect(got).toEqual(['a', 'b']);
});
it('T15: ends when the socket inbound ends', async () => {
const { socket, inbound } = fakeSocket();
const bounded = boundInbound(socket);
const it = bounded.inbound[Symbol.asyncIterator]();
const pending = it.next();
inbound.close();
expect((await pending).done).toBe(true);
expect((await it.next()).done).toBe(true);
});
it('T15: propagates a socket failure to a waiting and a later consumer', async () => {
const { socket, inbound } = fakeSocket();
const bounded = boundInbound(socket);
const it = bounded.inbound[Symbol.asyncIterator]();
const pending = it.next();
const boom = new Error('boom');
inbound.fail(boom);
await expect(pending).rejects.toBe(boom);
await expect(it.next()).rejects.toBe(boom);
});
it('T15: a consumer that returns stops queueing, so it is never closed for not reading', async () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 1 });
const it = bounded.inbound[Symbol.asyncIterator]();
await it.return?.();
for (const m of ['a', 'b', 'c']) inbound.push(m);
await tick();
expect(closes).toEqual([]);
expect((await it.next()).done).toBe(true);
});
it('fans out: two consumers waiting at once both receive the frame', async () => {
const { socket, inbound } = fakeSocket();
const bounded = boundInbound(socket);
const a = bounded.inbound[Symbol.asyncIterator]();
const b = bounded.inbound[Symbol.asyncIterator]();
const [nextA, nextB] = [a.next(), b.next()];
inbound.push('x');
expect(await nextA).toEqual({ value: 'x', done: false });
expect(await nextB).toEqual({ value: 'x', done: false });
});
it('fans out: a consumer that returns does not end the next one', async () => {
const { socket, inbound } = fakeSocket();
const bounded = boundInbound(socket);
const first = bounded.inbound[Symbol.asyncIterator]();
const firstNext = first.next();
inbound.push('a');
expect(await firstNext).toEqual({ value: 'a', done: false });
await first.return?.();
const second = bounded.inbound[Symbol.asyncIterator]();
const secondNext = second.next();
inbound.push('b');
expect(await secondNext).toEqual({ value: 'b', done: false });
});
it('fans out: the bound applies to each consumer, so one stalled reader closes 1013', async () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 2 });
const reader = bounded.inbound[Symbol.asyncIterator]();
bounded.inbound[Symbol.asyncIterator](); // subscribed, never reads
for (const m of ['a', 'b', 'c']) {
const got = reader.next();
inbound.push(m);
await got;
}
expect(closes).toEqual([[1013, 'inbound queue full']]);
});
it('fans out: a frame that overflows any queue reaches no consumer', async () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 1 });
const fast = bounded.inbound[Symbol.asyncIterator]();
bounded.inbound[Symbol.asyncIterator](); // stalled
const first = fast.next();
inbound.push('a'); // fast takes it, stalled queues it: 1/1
expect(await first).toEqual({ value: 'a', done: false });
const second = fast.next();
inbound.push('b'); // stalled is full: rejected for everyone
expect(closes).toEqual([[1013, 'inbound queue full']]);
expect(await second).toEqual({ value: undefined, done: true });
});
it('enforces the queue bound inside a synchronous burst, before the event loop yields', () => {
const { socket, inbound, closes } = fakeSocket();
const bounded = boundInbound(socket, { maxWsQueue: 2 });
bounded.inbound[Symbol.asyncIterator](); // stalled
for (let i = 0; i < 100_000; i++) inbound.push(String(i)); // what `ws` does with one TCP read
expect(closes).toEqual([[1013, 'inbound queue full']]);
});
it('enforces the size bound synchronously too', () => {
const { socket, inbound, closes } = fakeSocket();
boundInbound(socket, { maxWsMessageBytes: 3 });
inbound.push('abcd');
expect(closes).toEqual([[1009, 'message too large']]);
});
it('T15: keeps the socket capabilities other than inbound', () => {
const { socket } = fakeSocket();
const bounded = boundInbound(socket);
expect(bounded.isOpen).toBe(true);
expect(bounded.abort).toBe(socket.abort);
bounded.close(1000, 'bye');
});
});
+114
View File
@@ -0,0 +1,114 @@
import { describe, it, expect, beforeAll, afterAll, afterEach } from 'vitest';
import net from 'net';
import type http from 'http';
import WebSocket from 'ws';
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
// Regression for #104: these drive the real Node `'upgrade'` listener through a `listen(0)` server,
// not `app.upgrade`. The requests are written by hand over a raw socket because a WebSocket client
// refuses or re-encodes the malformed URLs this is about.
@Route('/rt')
class Rt {
@Ws('/echo')
echo(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `echo:${msg}`;
})();
}
// A param route is what makes the bad escape fatal: only param segments are decoded on match.
@Ws('/room/:name')
room(@ctx() { inbound }: any) {
return (async function* () {
for await (const msg of inbound) yield `room:${msg}`;
})();
}
}
@Route('/health')
class Health {
@Get('/')
ok() {
return { ok: true };
}
}
@Module({ mountpoint: '/', controllers: [Rt, Health] })
class M {}
/** Writes a raw upgrade request for `path` and resolves with everything the server sent before closing. */
function rawUpgrade(port: number, path: string): Promise<string> {
return new Promise((resolve, reject) => {
const socket = net.connect(port, '127.0.0.1');
let data = '';
socket.on('connect', () =>
socket.write(
`GET ${path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n` +
'Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Version: 13\r\n\r\n',
),
);
socket.on('data', (chunk) => (data += chunk.toString()));
socket.on('close', () => resolve(data));
socket.on('error', reject);
});
}
describe('Node upgrade listener rejects malformed upgrades (#104)', () => {
let server: http.Server;
let port: number;
const uncaught: unknown[] = [];
const onUncaught = (err: unknown) => uncaught.push(err);
beforeAll(async () => {
process.on('uncaughtException', onUncaught);
process.on('unhandledRejection', onUncaught);
const app = createApp({ modules: [M] });
server = await app.listen(0);
port = (server.address() as { port: number }).port;
});
afterAll(async () => {
process.off('uncaughtException', onUncaught);
process.off('unhandledRejection', onUncaught);
await new Promise((r) => server.close(r));
});
afterEach(async () => {
// T6: a normal request on a new connection succeeds after every rejected upgrade.
const res = await fetch(`http://127.0.0.1:${port}/health`);
expect(res.status).toBe(200);
expect(uncaught).toEqual([]);
});
it('T1: malformed percent-encoding gets a 400 and the socket closes', async () => {
expect(await rawUpgrade(port, '/rt/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /);
});
it('T1: malformed percent-encoding in a param segment gets a 400 instead of crashing', async () => {
expect(await rawUpgrade(port, '/rt/room/%E0%A4%A')).toMatch(/^HTTP\/1\.1 400 /);
});
it('T2: invalid hex in a percent escape gets a 400', async () => {
expect(await rawUpgrade(port, '/rt/room/%ZZ')).toMatch(/^HTTP\/1\.1 400 /);
});
it('T3: a repeated slash gets a 400 instead of matching /rt/echo', async () => {
expect(await rawUpgrade(port, '//rt//echo')).toMatch(/^HTTP\/1\.1 400 /);
});
it('T4: a long path below the header limit takes the normal miss path (404)', async () => {
expect(await rawUpgrade(port, `/rt/${'a'.repeat(8 * 1024)}`)).toMatch(/^HTTP\/1\.1 404 /);
});
it('T5: an unknown ws route gets a written 404, then close', async () => {
expect(await rawUpgrade(port, '/nope')).toMatch(/^HTTP\/1\.1 404 /);
});
it('T7: a valid upgrade still echoes', async () => {
const client = new WebSocket(`ws://127.0.0.1:${port}/rt/echo`);
await new Promise((r) => client.on('open', r));
const got = new Promise<string>((r) => client.on('message', (d) => r(d.toString())));
client.send('hi');
expect(await got).toBe('echo:hi');
client.close();
});
});
+1 -1
View File
@@ -9,7 +9,7 @@ export default defineConfig({
dts: true, dts: true,
clean: true, clean: true,
sourcemap: true, sourcemap: true,
target: 'node18', target: 'node22',
// Give the ESM output a real `require` (via createRequire) so the lazy require('ws') / require('busboy') // Give the ESM output a real `require` (via createRequire) so the lazy require('ws') / require('busboy')
// (optional peer deps) resolve instead of hitting esbuild's "Dynamic require not supported" stub. // (optional peer deps) resolve instead of hitting esbuild's "Dynamic require not supported" stub.
esbuildOptions(options, context) { esbuildOptions(options, context) {