Compare commits
5
Commits
d0869788a5
...
7fd5d7492e
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7fd5d7492e | ||
|
|
e565b1d4c9 | ||
|
|
e112819f64 | ||
|
|
f4d29d8ee8 | ||
|
|
69bdc8adec |
No files matched your search
+16
-2
@@ -58,13 +58,20 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
constraints at a later segment of an otherwise unreachable route. The route then boots, as
|
constraints at a later segment of an otherwise unreachable route. The route then boots, as
|
||||||
before.
|
before.
|
||||||
|
|
||||||
|
- **Edge WebSocket upgrades no longer trust `cf-connecting-ip` by default** (#119). `edgeHandler`
|
||||||
|
copied the header into `ctx.ip` on every upgrade, so any client that sent it chose its own
|
||||||
|
address. It now counts only under `trustProxy: true`, the same rule HTTP follows. Without it,
|
||||||
|
`ctx.ip` on an edge WebSocket is `''`, as it already was on edge HTTP: workerd exposes no peer
|
||||||
|
address. An app behind Cloudflare that keys anything on the WebSocket IP needs
|
||||||
|
`createApp({ trustProxy: true })`.
|
||||||
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- **`limits.maxWsMessageBytes` and `limits.maxWsQueue`** (#107): per-connection bounds on inbound
|
- **`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`
|
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
|
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
|
before buffering it; Bun before 1.4 does so by dropping the connection, so its peer sees `1006`
|
||||||
`1009`. Deno and workerd expose no such option, so there the message is received in full and then
|
rather than `1009` (Bun 1.4 and later send `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
|
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
|
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.
|
Bun have no connection cap, so set one at the platform or proxy there.
|
||||||
@@ -83,6 +90,13 @@ npm treats versions as semver and semver forbids leading zeros.
|
|||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|
||||||
|
- **Edge HTTP fills `ctx.ip` from `cf-connecting-ip` under `trustProxy`** (#119). `edgeHandler`
|
||||||
|
never read the header for HTTP, so IP-keyed plugins such as rate-limit saw `''`, one bucket for
|
||||||
|
every client. Under `trustProxy: true` the header now sets `ctx.ip`, and it wins over
|
||||||
|
`x-forwarded-for`, because Cloudflare sets it itself while XFF can carry hops the client supplied.
|
||||||
|
Without `trustProxy` it is ignored. Only `edgeHandler` reads it: the Node, Deno and Bun adapters, and a
|
||||||
|
bare `app.fetch`, ignore it as before.
|
||||||
|
|
||||||
- **`static` no longer serves files outside its root through a symlink** (#106). The traversal guard
|
- **`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`
|
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
|
was served. Containment now compares real paths: the requested file, and a directory's
|
||||||
|
|||||||
@@ -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. 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.
|
- **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 before 1.4 drops the connection, so its peer sees `1006`; Bun 1.4 and later send `1009`); 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.
|
||||||
|
|||||||
Generated
+51
-63
@@ -1747,7 +1747,6 @@
|
|||||||
"integrity": "sha512-bRImsxibie+AM7xjdwcrm/gr5YeacI65kSBNzTufa1Ib5iwziaY/lqMtRh9THq6pbV4e1HP9aI2ZxGUumnmaoQ==",
|
"integrity": "sha512-bRImsxibie+AM7xjdwcrm/gr5YeacI65kSBNzTufa1Ib5iwziaY/lqMtRh9THq6pbV4e1HP9aI2ZxGUumnmaoQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"file-type": "21.3.4",
|
"file-type": "21.3.4",
|
||||||
"iterare": "1.2.1",
|
"iterare": "1.2.1",
|
||||||
@@ -1780,7 +1779,6 @@
|
|||||||
"integrity": "sha512-06m63xIRj8+l8uOeh/8LnYupGubkyu4f+bPKIadaSui6vK9KpXgoz7HveT1yOVLcEt0M0oCOEW5EuEXZkEmBBQ==",
|
"integrity": "sha512-06m63xIRj8+l8uOeh/8LnYupGubkyu4f+bPKIadaSui6vK9KpXgoz7HveT1yOVLcEt0M0oCOEW5EuEXZkEmBBQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"fast-safe-stringify": "2.1.1",
|
"fast-safe-stringify": "2.1.1",
|
||||||
"iterare": "1.2.1",
|
"iterare": "1.2.1",
|
||||||
@@ -1821,7 +1819,6 @@
|
|||||||
"integrity": "sha512-+F0hV/4yJM+D/Qwyo5XmKMe6YGEb+ssT2jFWrgdFe1obumXCUeC1GNob/kNeXyzAXm7dcxZVUtmcoqaF6z36jA==",
|
"integrity": "sha512-+F0hV/4yJM+D/Qwyo5XmKMe6YGEb+ssT2jFWrgdFe1obumXCUeC1GNob/kNeXyzAXm7dcxZVUtmcoqaF6z36jA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"cors": "2.8.6",
|
"cors": "2.8.6",
|
||||||
"express": "5.2.1",
|
"express": "5.2.1",
|
||||||
@@ -2569,7 +2566,6 @@
|
|||||||
"integrity": "sha512-CZ4nMxWwgu1HEEFNkeaCptra9QCtkmKdgf3sWh1rl1trIhmxLilgTV4cwcbQ4wemnT4sWQN8CaKOmdYx+g2gMA==",
|
"integrity": "sha512-CZ4nMxWwgu1HEEFNkeaCptra9QCtkmKdgf3sWh1rl1trIhmxLilgTV4cwcbQ4wemnT4sWQN8CaKOmdYx+g2gMA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@typescript-eslint/scope-manager": "8.65.0",
|
"@typescript-eslint/scope-manager": "8.65.0",
|
||||||
"@typescript-eslint/types": "8.65.0",
|
"@typescript-eslint/types": "8.65.0",
|
||||||
@@ -2808,16 +2804,16 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/expect": {
|
"node_modules/@vitest/expect": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.12.tgz",
|
||||||
"integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
|
"integrity": "sha512-vFlTt+YEu9WBpNjdGayNmlMVzrWPi1+sv853/7t2FU7hpO5gAFBKHzQmkCq5Xjpr+evegF2994LQT3hF3mRlqQ==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@standard-schema/spec": "^1.1.0",
|
"@standard-schema/spec": "^1.1.0",
|
||||||
"@types/chai": "^5.2.2",
|
"@types/chai": "^5.2.2",
|
||||||
"@vitest/spy": "4.1.11",
|
"@vitest/spy": "4.1.12",
|
||||||
"@vitest/utils": "4.1.11",
|
"@vitest/utils": "4.1.12",
|
||||||
"chai": "^6.2.2",
|
"chai": "^6.2.2",
|
||||||
"tinyrainbow": "^3.1.0"
|
"tinyrainbow": "^3.1.0"
|
||||||
},
|
},
|
||||||
@@ -2826,13 +2822,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/mocker": {
|
"node_modules/@vitest/mocker": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.12.tgz",
|
||||||
"integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
|
"integrity": "sha512-fKShNpKZzupWZuY0z7egydvL0sqW4INEZBEExMBMAa6izlENEVHwoXgdaTCaBZ5fwlr4xf2o1wXC83n9RpO+NA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitest/spy": "4.1.11",
|
"@vitest/spy": "4.1.12",
|
||||||
"estree-walker": "^3.0.3",
|
"estree-walker": "^3.0.3",
|
||||||
"magic-string": "^0.30.21"
|
"magic-string": "^0.30.21"
|
||||||
},
|
},
|
||||||
@@ -2853,9 +2849,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/pretty-format": {
|
"node_modules/@vitest/pretty-format": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.12.tgz",
|
||||||
"integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
|
"integrity": "sha512-XW9O8+Mxx4VpCtkYdMJLZQQwsVryP9wk7cPKDxtXFfwSak6yRh5+2fep/Y0XF/ElBvJHq8bcYdi6aeuai0opZA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -2866,13 +2862,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/runner": {
|
"node_modules/@vitest/runner": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.12.tgz",
|
||||||
"integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
|
"integrity": "sha512-NKlVKCr5QnCe8jijdMnmkpHHU+WTqiLFR6G0pHji9uRjXK9xJl1k1nTw6F3pOOj2PDcsDt2GKQMI7wIsaT491w==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitest/utils": "4.1.11",
|
"@vitest/utils": "4.1.12",
|
||||||
"pathe": "^2.0.3"
|
"pathe": "^2.0.3"
|
||||||
},
|
},
|
||||||
"funding": {
|
"funding": {
|
||||||
@@ -2880,14 +2876,14 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/snapshot": {
|
"node_modules/@vitest/snapshot": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.12.tgz",
|
||||||
"integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
|
"integrity": "sha512-ko1y1Qgb/slzQ9mr+b89Cuqud8WG1TKtsPD8r7ZUBdvVOGt85Af2HwCqHujrhwJq95hs/9RM7fcAPg57o1vlzw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitest/pretty-format": "4.1.11",
|
"@vitest/pretty-format": "4.1.12",
|
||||||
"@vitest/utils": "4.1.11",
|
"@vitest/utils": "4.1.12",
|
||||||
"magic-string": "^0.30.21",
|
"magic-string": "^0.30.21",
|
||||||
"pathe": "^2.0.3"
|
"pathe": "^2.0.3"
|
||||||
},
|
},
|
||||||
@@ -2896,9 +2892,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/spy": {
|
"node_modules/@vitest/spy": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.12.tgz",
|
||||||
"integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
|
"integrity": "sha512-RGq9x4JNGNTZHEJxvN0oSiJjeSCExm0n2gZKKJZHY9cX5AVA6M7VJILBT3ZJ/tJ/0J9uWT7fETV9/btoi//vSg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"funding": {
|
"funding": {
|
||||||
@@ -2906,13 +2902,13 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@vitest/utils": {
|
"node_modules/@vitest/utils": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.12.tgz",
|
||||||
"integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
|
"integrity": "sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitest/pretty-format": "4.1.11",
|
"@vitest/pretty-format": "4.1.12",
|
||||||
"convert-source-map": "^2.0.0",
|
"convert-source-map": "^2.0.0",
|
||||||
"tinyrainbow": "^3.1.0"
|
"tinyrainbow": "^3.1.0"
|
||||||
},
|
},
|
||||||
@@ -2957,7 +2953,6 @@
|
|||||||
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
|
"integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"acorn": "bin/acorn"
|
"acorn": "bin/acorn"
|
||||||
},
|
},
|
||||||
@@ -3894,7 +3889,6 @@
|
|||||||
"dev": true,
|
"dev": true,
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"esbuild": "bin/esbuild"
|
"esbuild": "bin/esbuild"
|
||||||
},
|
},
|
||||||
@@ -3956,7 +3950,6 @@
|
|||||||
"integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==",
|
"integrity": "sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@eslint-community/eslint-utils": "^4.8.0",
|
"@eslint-community/eslint-utils": "^4.8.0",
|
||||||
"@eslint-community/regexpp": "^4.12.1",
|
"@eslint-community/regexpp": "^4.12.1",
|
||||||
@@ -4291,9 +4284,9 @@
|
|||||||
"license": "BSD-3-Clause"
|
"license": "BSD-3-Clause"
|
||||||
},
|
},
|
||||||
"node_modules/fastify": {
|
"node_modules/fastify": {
|
||||||
"version": "5.12.5",
|
"version": "5.12.7",
|
||||||
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.5.tgz",
|
"resolved": "https://registry.npmjs.org/fastify/-/fastify-5.12.7.tgz",
|
||||||
"integrity": "sha512-OB2k1dlxs5/NAABqeKV2FUHkSD2BbENsCak8yULVcymn3fHIPDVa9TI3SDnJSWYSllZmSYuZXy2gTnsT+Sut1A==",
|
"integrity": "sha512-v4pEPsTRPuqlDIYiQFB+BHjVN4SdHX9u0ABk0ZDUKbbdY1vsNryUd1j4Z+jQEZajvYIVk047Kimva9/AJ79GYw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"funding": [
|
"funding": [
|
||||||
{
|
{
|
||||||
@@ -6026,7 +6019,6 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"nanoid": "^3.3.16",
|
"nanoid": "^3.3.16",
|
||||||
"picocolors": "^1.1.1",
|
"picocolors": "^1.1.1",
|
||||||
@@ -6285,8 +6277,7 @@
|
|||||||
"version": "0.2.2",
|
"version": "0.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/reflect-metadata/-/reflect-metadata-0.2.2.tgz",
|
||||||
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
|
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0"
|
||||||
"peer": true
|
|
||||||
},
|
},
|
||||||
"node_modules/reinterval": {
|
"node_modules/reinterval": {
|
||||||
"version": "1.1.0",
|
"version": "1.1.0",
|
||||||
@@ -6431,7 +6422,6 @@
|
|||||||
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
|
"integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"tslib": "^2.1.0"
|
"tslib": "^2.1.0"
|
||||||
}
|
}
|
||||||
@@ -7203,7 +7193,6 @@
|
|||||||
"integrity": "sha512-rw55FUaqOoI7RvlQwLbhO4nSDApnQ4/CykPuiQ/EPvtrX3WA9Ig55jIt9VvbBJbzJuj12ueRu4PMZ2SxPVbihg==",
|
"integrity": "sha512-rw55FUaqOoI7RvlQwLbhO4nSDApnQ4/CykPuiQ/EPvtrX3WA9Ig55jIt9VvbBJbzJuj12ueRu4PMZ2SxPVbihg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"peer": true,
|
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"esbuild": "~0.28.0"
|
"esbuild": "~0.28.0"
|
||||||
},
|
},
|
||||||
@@ -7753,7 +7742,6 @@
|
|||||||
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
"integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "Apache-2.0",
|
"license": "Apache-2.0",
|
||||||
"peer": true,
|
|
||||||
"bin": {
|
"bin": {
|
||||||
"tsc": "bin/tsc",
|
"tsc": "bin/tsc",
|
||||||
"tsserver": "bin/tsserver"
|
"tsserver": "bin/tsserver"
|
||||||
@@ -7888,9 +7876,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vite": {
|
"node_modules/vite": {
|
||||||
"version": "6.4.3",
|
"version": "6.4.5",
|
||||||
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.3.tgz",
|
"resolved": "https://registry.npmjs.org/vite/-/vite-6.4.5.tgz",
|
||||||
"integrity": "sha512-NTKlcQjlAK7MlQoyb6LgaqHc8sso/pVyUJYWMws3jg21uTJw/LddqIFPcPqP6PzpgbIcZyKI85sFE4HBrQDA8A==",
|
"integrity": "sha512-4enwjFfi4IwtEh0w+jPzpLVOFQiPHmmzPxcHXQOyEur47o6u0jE573DmGpjA+7irXoMLYRZD5ZaFUEneS3abPg==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -8447,19 +8435,19 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/vitest": {
|
"node_modules/vitest": {
|
||||||
"version": "4.1.11",
|
"version": "4.1.12",
|
||||||
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
|
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.12.tgz",
|
||||||
"integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
|
"integrity": "sha512-5eWdz2yb3ajxWF3C8C4TjkXl7FGm3n2E/VlazALrQHzK7nYMSGFnCZto0bbPNl77AwkOZVLk0YnBAejUu0NiWA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@vitest/expect": "4.1.11",
|
"@vitest/expect": "4.1.12",
|
||||||
"@vitest/mocker": "4.1.11",
|
"@vitest/mocker": "4.1.12",
|
||||||
"@vitest/pretty-format": "4.1.11",
|
"@vitest/pretty-format": "4.1.12",
|
||||||
"@vitest/runner": "4.1.11",
|
"@vitest/runner": "4.1.12",
|
||||||
"@vitest/snapshot": "4.1.11",
|
"@vitest/snapshot": "4.1.12",
|
||||||
"@vitest/spy": "4.1.11",
|
"@vitest/spy": "4.1.12",
|
||||||
"@vitest/utils": "4.1.11",
|
"@vitest/utils": "4.1.12",
|
||||||
"es-module-lexer": "^2.0.0",
|
"es-module-lexer": "^2.0.0",
|
||||||
"expect-type": "^1.3.0",
|
"expect-type": "^1.3.0",
|
||||||
"magic-string": "^0.30.21",
|
"magic-string": "^0.30.21",
|
||||||
@@ -8487,12 +8475,12 @@
|
|||||||
"@edge-runtime/vm": "*",
|
"@edge-runtime/vm": "*",
|
||||||
"@opentelemetry/api": "^1.9.0",
|
"@opentelemetry/api": "^1.9.0",
|
||||||
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
|
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
|
||||||
"@vitest/browser-playwright": "4.1.11",
|
"@vitest/browser-playwright": "4.1.12",
|
||||||
"@vitest/browser-preview": "4.1.11",
|
"@vitest/browser-preview": "4.1.12",
|
||||||
"@vitest/browser-webdriverio": "4.1.11",
|
"@vitest/browser-webdriverio": "^4.1.11",
|
||||||
"@vitest/coverage-istanbul": "4.1.11",
|
"@vitest/coverage-istanbul": "4.1.12",
|
||||||
"@vitest/coverage-v8": "4.1.11",
|
"@vitest/coverage-v8": "4.1.12",
|
||||||
"@vitest/ui": "4.1.11",
|
"@vitest/ui": "4.1.12",
|
||||||
"happy-dom": "*",
|
"happy-dom": "*",
|
||||||
"jsdom": "*",
|
"jsdom": "*",
|
||||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||||
|
|||||||
+17
-3
@@ -7,6 +7,7 @@ import { toMermaid, toDOT, graphHtml, type GraphView } from '../graph-viz';
|
|||||||
import { runPipeline, runSteps, PipelineStep } from '../pipeline';
|
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 { trustedProxyClient } from '../http/peer';
|
||||||
import { buildFetch } from '../http/web';
|
import { buildFetch } from '../http/web';
|
||||||
import {
|
import {
|
||||||
boundInbound,
|
boundInbound,
|
||||||
@@ -331,7 +332,10 @@ export function createApp(opts: {
|
|||||||
devRoutes,
|
devRoutes,
|
||||||
() => remoteRoutes,
|
() => remoteRoutes,
|
||||||
);
|
);
|
||||||
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, opts.limits);
|
const upgradeFn = buildAppUpgrade(routePlans, pipelineDeps, streams, bootApp, () => meshControl, {
|
||||||
|
limits: opts.limits,
|
||||||
|
trustProxy: opts.trustProxy,
|
||||||
|
});
|
||||||
|
|
||||||
const listen = async (port: number): Promise<http.Server> => {
|
const listen = async (port: number): Promise<http.Server> => {
|
||||||
const deps = pipelineDeps;
|
const deps = pipelineDeps;
|
||||||
@@ -1395,7 +1399,7 @@ function buildAppUpgrade(
|
|||||||
streams: Set<() => void>,
|
streams: Set<() => void>,
|
||||||
ensureBooted: () => Promise<void>,
|
ensureBooted: () => Promise<void>,
|
||||||
getMeshControl: () => MeshControl | undefined,
|
getMeshControl: () => MeshControl | undefined,
|
||||||
limits?: RequestLimits,
|
{ limits, trustProxy }: { limits?: RequestLimits; trustProxy?: boolean },
|
||||||
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
): (request: WsRequest, socket: WsSocket) => Promise<void> {
|
||||||
let wsRoutes: WsRouteDef[] | undefined;
|
let wsRoutes: WsRouteDef[] | undefined;
|
||||||
|
|
||||||
@@ -1444,10 +1448,20 @@ function buildAppUpgrade(
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
await runWsConnection(ready, request, route, deps.bus, streams);
|
await runWsConnection(ready, withProxyClient(request, trustProxy), route, deps.bus, streams);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `request` with `ip` taken from the proxy header its adapter recorded, when `trustProxy` allows it
|
||||||
|
* (the edge adapter's `cf-connecting-ip`, CARD-23); otherwise `request` unchanged. The same check
|
||||||
|
* `app.fetch` runs, so an edge WebSocket upgrade and an edge HTTP request resolve `ctx.ip` alike.
|
||||||
|
*/
|
||||||
|
function withProxyClient(request: WsRequest, trustProxy: boolean | undefined): WsRequest {
|
||||||
|
const ip = trustedProxyClient(request, trustProxy);
|
||||||
|
return ip ? { ...request, ip } : request;
|
||||||
|
}
|
||||||
|
|
||||||
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
/** The dev-only `/__graph__` route: serves the dependency graph as Mermaid text or an HTML viewer. */
|
||||||
function devGraphRoute(graph: () => GraphView): RouteDef {
|
function devGraphRoute(graph: () => GraphView): RouteDef {
|
||||||
return {
|
return {
|
||||||
|
|||||||
+2
-2
@@ -108,8 +108,8 @@ export async function serveBun(app: App, options?: BunServeShortOptions): Promis
|
|||||||
},
|
},
|
||||||
websocket: {
|
websocket: {
|
||||||
// The pre-buffer half of `limits.maxWsMessageBytes`: Bun refuses an oversized frame before
|
// 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
|
// assembling it. Up to Bun 1.3 it dropped the connection without a close frame, so the peer
|
||||||
// than 1009 — verified on Bun 1.3, and the price of not buffering the message at all.
|
// saw 1006 rather than 1009 — the price of not buffering the message at all. Bun 1.4 sends 1009.
|
||||||
// `app.upgrade` checks the same bound again on the decoded text.
|
// `app.upgrade` checks the same bound again on the decoded text.
|
||||||
maxPayloadLength:
|
maxPayloadLength:
|
||||||
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
(app as { [WS_MAX_MESSAGE_BYTES]?: number })[WS_MAX_MESSAGE_BYTES] ?? DEFAULT_MAX_WS_MESSAGE_BYTES,
|
||||||
|
|||||||
+16
-1
@@ -1,5 +1,6 @@
|
|||||||
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 { setProxyClient } from './http/peer';
|
||||||
|
|
||||||
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
// Minimal ambient for the Cloudflare Workers globals we use — avoids @cloudflare/workers-types.
|
||||||
// Declares only what we call; mirrors the real workerd signatures.
|
// Declares only what we call; mirrors the real workerd signatures.
|
||||||
@@ -30,7 +31,9 @@ export function edgeHandler(
|
|||||||
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
||||||
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
const [client, server] = Object.values(new WebSocketPair()) as [EdgeWebSocket, EdgeWebSocket];
|
||||||
server.accept();
|
server.accept();
|
||||||
const wsReq = toWsRequest(request, request.headers.get('cf-connecting-ip') ?? '');
|
// No peer address on the edge, so `ip` starts empty; the header only fills it under `trustProxy`.
|
||||||
|
const wsReq = toWsRequest(request, '');
|
||||||
|
recordClient(wsReq, request);
|
||||||
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
const lifecycle = upgradeSafely(app, wsReq, eventSocket(server));
|
||||||
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
if (ctx?.waitUntil) ctx.waitUntil(lifecycle);
|
||||||
else void lifecycle;
|
else void lifecycle;
|
||||||
@@ -38,6 +41,18 @@ export function edgeHandler(
|
|||||||
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
return new Response(null, { status: 101, webSocket: client } as ResponseInit & { webSocket: EdgeWebSocket });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
recordClient(request, request);
|
||||||
return app.fetch(request);
|
return app.fetch(request);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hands the app the `cf-connecting-ip` header for `source`, the object the app will be given for this
|
||||||
|
* request. The app — not this adapter — decides whether it counts, since `trustProxy` is an app
|
||||||
|
* option; HTTP and WebSocket both go through here and through the same check on the app side.
|
||||||
|
* Without `trustProxy` the header is ignored and `ctx.ip` stays `''`: workerd exposes no peer address,
|
||||||
|
* and an untrusted header is whatever the client chose to send.
|
||||||
|
*/
|
||||||
|
function recordClient(source: object, request: Request): void {
|
||||||
|
setProxyClient(source, request.headers.get('cf-connecting-ip') ?? '');
|
||||||
|
}
|
||||||
@@ -25,3 +25,28 @@ export function setPeer(request: Request, ip: string): void {
|
|||||||
export function peerOf(request: Request): string {
|
export function peerOf(request: Request): string {
|
||||||
return peers.get(request) ?? '';
|
return peers.get(request) ?? '';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// The client address a runtime adapter read from a header its platform's proxy sets — today only the
|
||||||
|
// edge adapter, from `cf-connecting-ip`. Unlike the socket peer above, a header is client-supplied
|
||||||
|
// unless a proxy in front overwrites it, so it only counts under `trustProxy`; the adapter cannot
|
||||||
|
// decide that, because the option lives on the app, so it records the value and the app decides.
|
||||||
|
// Keyed by the `Request` (HTTP) or the `WsRequest` (WebSocket upgrade) the adapter hands the app, for
|
||||||
|
// the same reasons as the peer: no handler-visible header, no extra public parameter. Same
|
||||||
|
// `globalThis` registration, because `@green-tea/core/edge` is a separate bundle too.
|
||||||
|
const PROXY_KEY = Symbol.for('@green-tea/core:proxy-client');
|
||||||
|
const proxyRegistry = globalThis as { [PROXY_KEY]?: WeakMap<object, string> };
|
||||||
|
const proxyClients = (proxyRegistry[PROXY_KEY] ??= new WeakMap<object, string>());
|
||||||
|
|
||||||
|
/** Records `ip` as the client address a proxy header named for `source`. An empty value is not recorded. */
|
||||||
|
export function setProxyClient(source: object, ip: string): void {
|
||||||
|
if (ip) proxyClients.set(source, ip);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The client address an adapter recorded for `source` from a proxy header, when `trustProxy` is on;
|
||||||
|
* `''` otherwise. The one check both `app.fetch` and `app.upgrade` run, so HTTP and WebSocket cannot
|
||||||
|
* disagree about whether the header counts.
|
||||||
|
*/
|
||||||
|
export function trustedProxyClient(source: object, trustProxy: boolean | undefined): string {
|
||||||
|
return trustProxy ? (proxyClients.get(source) ?? '') : '';
|
||||||
|
}
|
||||||
+2
-2
@@ -22,8 +22,8 @@ export interface RequestLimits {
|
|||||||
* a fragmented message counts as a whole. Must be a positive integer, or `createApp` throws.
|
* 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
|
* 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
|
* `maxPayloadLength`). Before Bun 1.4, Bun then drops the connection without a close frame, so
|
||||||
* sees `1006` instead of `1009`. Deno and the edge offer no such option: there the runtime
|
* the peer sees `1006` instead of `1009`; Bun 1.4 and later send `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
|
* 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`.
|
* limit is checked after receipt — the connection still closes `1009`.
|
||||||
*
|
*
|
||||||
|
|||||||
+5
-2
@@ -11,7 +11,7 @@ import {
|
|||||||
type Preflight,
|
type Preflight,
|
||||||
} from './core';
|
} from './core';
|
||||||
import { mergeInjectedHeaders } from './headers';
|
import { mergeInjectedHeaders } from './headers';
|
||||||
import { peerOf } from './peer';
|
import { peerOf, trustedProxyClient } from './peer';
|
||||||
import { declaresOverLimit, type BodyFailure, type BodyReader, type MaybePromise } from './body';
|
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';
|
||||||
@@ -299,7 +299,10 @@ export function buildFetch(routes: RouteDef[], opts: HttpOptions | undefined) {
|
|||||||
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
|
// proxy is trusted, and take its first hop — an untrusted XFF is client-spoofable.
|
||||||
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
|
// Otherwise the socket peer, which only the Deno and Bun adapters can supply; a bare
|
||||||
// `app.fetch` has none, so there the answer is still ''.
|
// `app.fetch` has none, so there the answer is still ''.
|
||||||
ip: forwardedFor(headers, opts) || peerOf(request),
|
// Ahead of both, under `trustProxy` only: the address the edge adapter read from
|
||||||
|
// `cf-connecting-ip`. Cloudflare sets that header itself, while XFF can carry hops the
|
||||||
|
// client supplied, so on the edge it wins (CARD-23).
|
||||||
|
ip: trustedProxyClient(request, opts?.trustProxy) || forwardedFor(headers, opts) || peerOf(request),
|
||||||
},
|
},
|
||||||
// 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.
|
||||||
|
|||||||
+8
-6
@@ -101,10 +101,12 @@ function exchange(port: number, path: string, frames: string[], until = 2000) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Its
|
// #107: Bun refuses an oversized frame natively (`maxPayloadLength`), before buffering it. Up to
|
||||||
// uWebSockets core drops the TCP connection without a close frame, so the peer sees `1006`, not
|
// Bun 1.3 its uWebSockets core dropped the TCP connection without a close frame, so the peer saw
|
||||||
// the `1009` Node, Deno and the edge send. Asserted rather than papered over: it is the documented
|
// `1006`; from Bun 1.4 it sends a real `1009`, like Node, Deno and the edge. Asserted per version
|
||||||
// Bun difference, and a Bun upgrade that starts sending 1009 should fail here and be noticed.
|
// rather than papered over, so a further change in either direction fails here and is noticed.
|
||||||
|
const [bunMajor, bunMinor] = Bun.version.split('.').map(Number);
|
||||||
|
const OVERSIZE_CLOSE = bunMajor > 1 || (bunMajor === 1 && bunMinor >= 4) ? 1009 : 1006;
|
||||||
test('serveBun: ws message size and inbound queue limits', async () => {
|
test('serveBun: ws message size and inbound queue limits', async () => {
|
||||||
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
const app = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||||
const server = await serveBun(app, { port: 0 });
|
const server = await serveBun(app, { port: 0 });
|
||||||
@@ -114,7 +116,7 @@ test('serveBun: ws message size and inbound queue limits', async () => {
|
|||||||
expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]);
|
expect(atLimit.replies).toEqual([`echo:${'a'.repeat(1024)}`]);
|
||||||
|
|
||||||
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
|
const over = await exchange(port, '/rt/echo', ['a'.repeat(1025)]);
|
||||||
expect(over.close?.code).toBe(1006);
|
expect(over.close?.code).toBe(OVERSIZE_CLOSE);
|
||||||
|
|
||||||
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
|
const full = await exchange(port, '/rt/stall', ['1', '2', '3', '4', '5']);
|
||||||
expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' });
|
expect(full.close).toEqual({ code: 1013, reason: 'inbound queue full' });
|
||||||
@@ -132,7 +134,7 @@ test('serveBun: ws message size default is 1 MiB', async () => {
|
|||||||
expect(atLimit.replies.length).toBe(1);
|
expect(atLimit.replies.length).toBe(1);
|
||||||
|
|
||||||
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
|
const over = await exchange(port, '/rt/echo', ['a'.repeat(1_048_577)]);
|
||||||
expect(over.close?.code).toBe(1006);
|
expect(over.close?.code).toBe(OVERSIZE_CLOSE);
|
||||||
} finally {
|
} finally {
|
||||||
server.stop(true);
|
server.stop(true);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,119 @@
|
|||||||
|
// CARD-23 (#119, D21): on the edge, `cf-connecting-ip` sets `ctx.ip` only under `trustProxy`, for HTTP
|
||||||
|
// and WebSocket alike, and wins over `x-forwarded-for`. The full WebSocket path through workerd
|
||||||
|
// (`WebSocketPair`, a 101 response) cannot run under Node, so it is covered in `test/edge/run.ts`;
|
||||||
|
// here the edge HTTP path runs through `edgeHandler` itself, and the WebSocket side through
|
||||||
|
// `app.upgrade` with the value recorded the way `edgeHandler` records it.
|
||||||
|
import 'reflect-metadata';
|
||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import type { AddressInfo } from 'node:net';
|
||||||
|
import { createApp, Route, Get, Ws, Module, ctx } from '../src/index';
|
||||||
|
import { edgeHandler } from '../src/edge';
|
||||||
|
import { channel } from '../src/channel';
|
||||||
|
import { setProxyClient } from '../src/http/peer';
|
||||||
|
import type { WsSocket, WsRequest } from '../src/http/ws-core';
|
||||||
|
|
||||||
|
@Route('/ip')
|
||||||
|
class IpCtl {
|
||||||
|
@Get('/whoami') whoami(@ctx() c: any) {
|
||||||
|
return { ip: c.ip };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/ws')
|
||||||
|
ws(@ctx() c: any) {
|
||||||
|
return (async function* () {
|
||||||
|
yield String(c.ip);
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
@Module({ mountpoint: '/', controllers: [IpCtl] })
|
||||||
|
class IpModule {}
|
||||||
|
|
||||||
|
const trusting = createApp({ modules: [IpModule], trustProxy: true });
|
||||||
|
const untrusting = createApp({ modules: [IpModule] });
|
||||||
|
|
||||||
|
const whoami = async (handler: (r: Request) => Response | Promise<Response>, headers: Record<string, string>) =>
|
||||||
|
((await (await handler(new Request('http://x/ip/whoami', { headers }))).json()) as { ip: string }).ip;
|
||||||
|
|
||||||
|
describe('edge HTTP: cf-connecting-ip', () => {
|
||||||
|
it('T1: under trustProxy it sets ctx.ip', async () => {
|
||||||
|
expect(await whoami(edgeHandler(trusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('1.2.3.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T2: under trustProxy it wins over x-forwarded-for', async () => {
|
||||||
|
const headers = { 'cf-connecting-ip': '1.2.3.4', 'x-forwarded-for': '9.9.9.9' };
|
||||||
|
expect(await whoami(edgeHandler(trusting), headers)).toBe('1.2.3.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('under trustProxy without the header, x-forwarded-for still applies', async () => {
|
||||||
|
expect(await whoami(edgeHandler(trusting), { 'x-forwarded-for': '9.9.9.9' })).toBe('9.9.9.9');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T3: without trustProxy it is ignored and ctx.ip stays empty', async () => {
|
||||||
|
expect(await whoami(edgeHandler(untrusting), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
function fakeSocket() {
|
||||||
|
const ac = new AbortController();
|
||||||
|
const sent: string[] = [];
|
||||||
|
const socket: WsSocket = {
|
||||||
|
inbound: channel<unknown>(),
|
||||||
|
abort: ac.signal,
|
||||||
|
isOpen: true,
|
||||||
|
send: (d) => sent.push(d),
|
||||||
|
close: () => ac.abort(),
|
||||||
|
terminate: () => ac.abort(),
|
||||||
|
};
|
||||||
|
return { socket, sent };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Upgrades the way `edgeHandler` does: `ip` empty, the header recorded on the `WsRequest`. */
|
||||||
|
async function edgeWsIp(app: typeof trusting, cfConnectingIp: string): Promise<string> {
|
||||||
|
const headers = { 'cf-connecting-ip': cfConnectingIp };
|
||||||
|
const req: WsRequest = { url: '/ip/ws', headers, protocol: 'http', ip: '' };
|
||||||
|
setProxyClient(req, cfConnectingIp);
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
await app.upgrade(req, socket);
|
||||||
|
return sent[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('edge WebSocket: cf-connecting-ip', () => {
|
||||||
|
it('T4: without trustProxy it is ignored and ctx.ip stays empty', async () => {
|
||||||
|
expect(await edgeWsIp(untrusting, '1.2.3.4')).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('T5: under trustProxy it sets ctx.ip', async () => {
|
||||||
|
expect(await edgeWsIp(trusting, '1.2.3.4')).toBe('1.2.3.4');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('an adapter-supplied ip with nothing recorded is passed through unchanged', async () => {
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
await trusting.upgrade({ url: '/ip/ws', headers: {}, protocol: 'http', ip: '203.0.113.7' }, socket);
|
||||||
|
expect(sent).toEqual(['203.0.113.7']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('outside the edge adapter the header means nothing', () => {
|
||||||
|
it('T6: the Node listener under trustProxy ignores cf-connecting-ip', async () => {
|
||||||
|
const server = await createApp({ modules: [IpModule], trustProxy: true }).listen(0);
|
||||||
|
try {
|
||||||
|
const { port } = server.address() as AddressInfo;
|
||||||
|
const res = await fetch(`http://127.0.0.1:${port}/ip/whoami`, { headers: { 'cf-connecting-ip': '1.2.3.4' } });
|
||||||
|
const { ip } = (await res.json()) as { ip: string };
|
||||||
|
expect(ip).not.toBe('1.2.3.4');
|
||||||
|
expect(ip).toMatch(/127\.0\.0\.1|::1/);
|
||||||
|
} finally {
|
||||||
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a bare app.fetch under trustProxy ignores cf-connecting-ip', async () => {
|
||||||
|
expect(await whoami((r) => trusting.fetch(r), { 'cf-connecting-ip': '1.2.3.4' })).toBe('');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('a bare app.upgrade under trustProxy ignores the header in WsRequest.headers', async () => {
|
||||||
|
const { socket, sent } = fakeSocket();
|
||||||
|
await trusting.upgrade({ url: '/ip/ws', headers: { 'cf-connecting-ip': '1.2.3.4' }, protocol: 'http', ip: '' }, socket);
|
||||||
|
expect(sent).toEqual(['']);
|
||||||
|
});
|
||||||
|
});
|
||||||
+26
-1
@@ -138,7 +138,32 @@ async function main() {
|
|||||||
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_576)])).replies.length, 1);
|
||||||
assert.equal((await exchange(mf, 'http://localhost/rt/echo', ['a'.repeat(1_048_577)])).close?.code, 1009);
|
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');
|
// CARD-23 (#119): `cf-connecting-ip` sets ctx.ip only under trustProxy, for HTTP and WS alike,
|
||||||
|
// and wins over x-forwarded-for.
|
||||||
|
const cf = { 'cf-connecting-ip': '1.2.3.4' };
|
||||||
|
const httpIp = async (host: string, headers: Record<string, string>) =>
|
||||||
|
((await (await mf.dispatchFetch(`http://${host}/rt/ip`, { headers })).json()) as { ip: string }).ip;
|
||||||
|
const wsIp = async (host: string, headers: Record<string, string>) => {
|
||||||
|
const res = await mf.dispatchFetch(`http://${host}/rt/ws-ip`, { headers: { Upgrade: 'websocket', ...headers } });
|
||||||
|
const socket = res.webSocket;
|
||||||
|
assert.ok(socket, 'expected a client webSocket on the 101 response');
|
||||||
|
const reply = new Promise<string>((resolve) =>
|
||||||
|
socket.addEventListener('message', (e: { data: unknown }) => resolve(String(e.data))),
|
||||||
|
);
|
||||||
|
socket.accept();
|
||||||
|
const got = await reply;
|
||||||
|
socket.close();
|
||||||
|
return got;
|
||||||
|
};
|
||||||
|
assert.equal(await httpIp('trusted', cf), '1.2.3.4', 'T1 edge HTTP under trustProxy');
|
||||||
|
assert.equal(await httpIp('trusted', { ...cf, 'x-forwarded-for': '9.9.9.9' }), '1.2.3.4', 'T2 cf wins over XFF');
|
||||||
|
assert.equal(await httpIp('localhost', cf), '', 'T3 edge HTTP without trustProxy');
|
||||||
|
assert.equal(await wsIp('localhost', cf), 'ip:', 'T4 edge WS without trustProxy');
|
||||||
|
assert.equal(await wsIp('trusted', cf), 'ip:1.2.3.4', 'T5 edge WS under trustProxy');
|
||||||
|
|
||||||
|
console.log(
|
||||||
|
'edge (workerd via miniflare): HTTP 200 + body limits 413/413/200/413 + WS echo:hi + ws limits + cf-connecting-ip under trustProxy — PASS',
|
||||||
|
);
|
||||||
} finally {
|
} finally {
|
||||||
await mf.dispose();
|
await mf.dispose();
|
||||||
}
|
}
|
||||||
|
|||||||
+22
-3
@@ -35,6 +35,19 @@ class Rt {
|
|||||||
})();
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// CARD-23: what `ctx.ip` resolved to, over HTTP and over a WebSocket upgrade.
|
||||||
|
@Get('/ip')
|
||||||
|
ip(@ctx() c: any) {
|
||||||
|
return { ip: c.ip };
|
||||||
|
}
|
||||||
|
|
||||||
|
@Ws('/ws-ip')
|
||||||
|
wsIp(@ctx() c: any) {
|
||||||
|
return (async function* () {
|
||||||
|
yield `ip:${c.ip}`;
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
@Ws('/room/:name')
|
@Ws('/room/:name')
|
||||||
room(@ctx() { inbound }: any) {
|
room(@ctx() { inbound }: any) {
|
||||||
return (async function* () {
|
return (async function* () {
|
||||||
@@ -49,9 +62,15 @@ 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.
|
// #107: the same graph with tight ws limits, reached through the `limited` host.
|
||||||
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
const limited = createApp({ modules: [M], limits: { maxWsMessageBytes: 1024, maxWsQueue: 4 } });
|
||||||
const handlers = { default: edgeHandler(app), limited: edgeHandler(limited) };
|
// CARD-23: the same graph under `trustProxy`, reached through the `trusted` host.
|
||||||
|
const trusted = createApp({ modules: [M], trustProxy: true });
|
||||||
|
const handlers: Record<string, ReturnType<typeof edgeHandler>> = {
|
||||||
|
default: edgeHandler(app),
|
||||||
|
limited: edgeHandler(limited),
|
||||||
|
trusted: edgeHandler(trusted),
|
||||||
|
};
|
||||||
|
|
||||||
export default {
|
export default {
|
||||||
fetch: (request: Request, env?: unknown, ctx?: Parameters<typeof handlers.default>[2]) =>
|
fetch: (request: Request, env?: unknown, ctx?: Parameters<ReturnType<typeof edgeHandler>>[2]) =>
|
||||||
(new URL(request.url).hostname === 'limited' ? handlers.limited : handlers.default)(request, env, ctx),
|
(handlers[new URL(request.url).hostname] ?? handlers.default)(request, env, ctx),
|
||||||
};
|
};
|
||||||
Reference in new issue
Block a user