FPRD-001a: core safety and adapter correctness (#104 #105 #106 #107 #108 #116) #117

Merged
chrnx merged 8 commits from feature/fprd-001a into develop 2026-10-10 16:49:36 +00:00
42 changed files with 2648 additions and 91 deletions

No files matched your search

+93
View File
@@ -6,6 +6,99 @@ 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
npm treats versions as semver and semver forbids leading zeros.
## [Unreleased]
### Breaking
- **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
### Breaking
+1 -1
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.
- **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.
- **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.
- **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.
+37 -13
View File
@@ -8,7 +8,17 @@ import { runPipeline, runSteps, PipelineStep } from '../pipeline';
import { createHttpServer, parseQuery, RouteDef, WsRouteDef, RequestLimits } from '../http';
import type { HttpOptions } from '../http';
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 { JsonTransformer, type ErrorRenderer } from '../transformers';
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 { App, InspectLine, Explain, RoutePlan, MeshConfig } from './types';
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';
@@ -195,6 +205,8 @@ export function createApp(opts: {
);
}
validateWsLimits(opts.limits);
const bus = new Bus();
const logger = opts.logger ?? createDefaultLogger();
if (opts.logRequests) logRequests(bus, logger);
@@ -318,7 +330,7 @@ export function createApp(opts: {
devRoutes,
() => 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 deps = pipelineDeps;
@@ -387,7 +399,7 @@ export function createApp(opts: {
return wrapped;
};
return {
const app: App = {
listen,
close,
handleSignals,
@@ -405,6 +417,10 @@ export function createApp(opts: {
bus,
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. */
@@ -1275,22 +1291,30 @@ function buildAppUpgrade(
streams: Set<() => void>,
ensureBooted: () => Promise<void>,
getMeshControl: () => MeshControl | undefined,
limits?: RequestLimits,
): (request: WsRequest, socket: WsSocket) => Promise<void> {
let wsRoutes: WsRouteDef[] | undefined;
return async (request: WsRequest, socket: WsSocket): Promise<void> => {
// Subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed with no
// subscriber is dropped, so anything the peer sends while providers are still booting would be
// lost. For the mesh control channel that is the `hello` itself — the handshake would hang
// until timeout against a teapot whose providers happened to boot slowly.
const frames = socket.inbound[Symbol.asyncIterator]();
const ready: WsSocket = Object.create(socket, {
inbound: { value: { [Symbol.asyncIterator]: () => frames } },
}) as WsSocket;
// Bound and subscribe to inbound BEFORE awaiting the boot. `channel` is fan-out: a frame pushed
// with no subscriber is dropped, so anything the peer sends while providers are still booting
// would be lost. For the mesh control channel that is the `hello` itself — the handshake would
// hang until timeout against a teapot whose providers happened to boot slowly.
const ready = boundInbound(socket, limits);
await ensureBooted(); // idempotent: no-op once any of fetch/upgrade/listen has booted
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();
// The reserved mesh path, checked before route matching: this is what lets a teapot export
+11 -1
View File
@@ -1,9 +1,10 @@
import { channel } from './channel';
import type { Channel } from './channel';
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 { closeWithDeadline } from './http/shutdown';
import { setPeer } from './http/peer';
// Minimal ambient for the Bun globals we use — avoids a @types/bun devDep.
// Mirrors the real Bun.serve / server.upgrade / ServerWebSocket signatures we call.
@@ -15,6 +16,7 @@ interface BunServerWebSocket {
terminate?(): void;
}
interface BunWebSocketHandler {
maxPayloadLength?: number;
open?(ws: BunServerWebSocket): void;
message(ws: BunServerWebSocket, message: string | Uint8Array): 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 });
}
// 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);
},
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) {
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';
}
/**
* 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> {
iterator: AsyncIterator<T>;
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.
* @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 subs = new Set<Sub<T>>();
const subs = new Set<Omit<Sub<T>, 'iterator'>>();
let done = false;
let closedFlag = false;
@@ -117,5 +137,14 @@ export function channel<T>(opts: { buffer?: number } = {}): Channel<T> {
subs.add(sub);
return sub.iterator;
},
[CHANNEL_TAP](sink) {
if (done) {
sink.end();
return () => {};
}
subs.add(sink);
return () => subs.delete(sink);
},
};
}
+4
View File
@@ -1,6 +1,7 @@
import type { App } from './app/types';
import { eventSocket, toWsRequest, upgradeSafely, type EventfulSocket } from './http/ws-adapter';
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)
// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use.
@@ -82,6 +83,9 @@ export async function serveDeno(app: App, options?: DenoServeOptions): Promise<D
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);
});
+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`.
*
* The adapter owns this and nothing else about the body, because enforcement is the one place the
* runtimes legitimately differ: Node checks the running total as chunks arrive and can abort a
* 10 GB upload after 1 MB, while a fetch runtime has only `request.arrayBuffer()` and can check
* `byteLength` after the fact. Passing the limit *in*, rather than measuring the returned buffer
* here, is what keeps Node's incremental abort — measuring afterwards would force it to buffer
* without bound first.
* The adapter owns this and nothing else about the body, because getting the bytes is the one place
* the runtimes legitimately differ: Node iterates the socket, a fetch runtime reads `request.body`.
* Both check the running total as chunks arrive and abort a 10 GB upload after 1 MB. Passing the
* limit *in*, rather than measuring the returned buffer here, is what makes that incremental abort
* possible — measuring afterwards would force the reader to buffer without bound first.
*
* 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.
@@ -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>;
/**
* 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). */
type ParseResult = { body: unknown } | { error: string; status?: number };
+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 { HttpError } from '../signals';
import { declaresOverLimit } from './body';
/** 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> {
// 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[] = [];
let total = 0;
+43 -3
View File
@@ -18,6 +18,7 @@ import {
} from './core';
import type { BodyFailure, BodyReader } from './body';
import type { RouteDef, WsRouteDef, MeshControl, HttpOptions } from './types';
import type { Logger } from '../logger';
import { nodeRequire } from '../node-require';
interface HandlerConfig {
@@ -78,7 +79,7 @@ export function createHttpServer(
server.requestTimeout = opts?.limits?.requestTimeoutMs ?? 30_000;
server.headersTimeout = opts?.limits?.headersTimeoutMs ?? 10_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;
}
@@ -96,7 +97,14 @@ function createRequestHandler(cfg: HandlerConfig) {
const readBody: BodyReader = (source, limit) => readRequestBytes(source, limit, opts);
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
// (200, 404, error, stream) writes headers through the same patched writeHead.
const secure = deriveSecure(req, trustProxy);
@@ -192,7 +200,39 @@ function createRequestHandler(cfg: HandlerConfig) {
res.writeHead(result.outcome.status, result.outcome.headers);
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
keepAliveTimeoutMs?: number; // default 5_000
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. */
+73 -25
View File
@@ -11,7 +11,8 @@ import {
type Preflight,
} from './core';
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 { renderError, type ErrorRequest } from '../transformers';
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.
*
* Unlike Node, there is no incremental read to abort — `arrayBuffer()` resolves with the whole body
* or not at all, so the limit can only be checked once the bytes are already in memory. That
* difference is exactly why the limit is passed in rather than applied by the shared core.
* Read from `request.body` chunk by chunk rather than through `arrayBuffer()`, which resolves with
* the whole body or not at all and so could only check the limit once every byte was in memory.
* Deno, Bun, workerd and Node all expose `request.body` as a stream, so no runtime needs a branch.
*/
function readFetchBytes(
source: unknown,
@@ -110,21 +111,63 @@ function readFetchBytes(
// Not `async`: a bodiless request answers without allocating a promise at all.
if (!request.body) return { bytes: undefined };
return request.arrayBuffer().then((arrayBuffer) => {
if (arrayBuffer.byteLength > limit) {
// 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.
const url = new URL(request.url);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
// A declared length over the limit is refused before a single chunk is pulled. Cancelling is best
// 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;
}
return { bytes: arrayBuffer.byteLength === 0 ? undefined : Buffer.from(arrayBuffer) };
});
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
// a `url`/`headers` pair captured up-front cost more than the work it saved.
const url = new URL(request.url);
const errReq: ErrorRequest = {
method: request.method,
url: url.pathname + url.search,
headers: headersToRecord(request.headers),
};
return { fail: renderError(new HttpError(413, 'Payload Too Large'), errReq, opts?.onError, opts?.logger) };
}
/**
@@ -176,6 +219,15 @@ function outcomeToResponse(result: HandleResult, bus?: Bus, correlation: Correla
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:
* 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,
secure,
// 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
// there's no socket peer address to fall back to on the fetch path, so the untrusted case
// is simply ''.
ip: opts?.trustProxy
? String(headers['x-forwarded-for'] ?? '')
.split(',')[0]
.trim()
: '',
// 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
// `app.fetch` has none, so there the answer is still ''.
ip: forwardedFor(headers, opts) || peerOf(request),
},
// Already computed above for the shed-503 path; handing it down keeps `cors.origins` to
// one call per request.
+15 -3
View File
@@ -1,4 +1,4 @@
import { channel } from '../channel';
import { channel, type Channel } from '../channel';
import type { App } from '../app/types';
import type { WsRequest, WsSocket } from './ws-core';
import { nodeRequire } from '../node-require';
@@ -10,6 +10,7 @@ import { nodeRequire } from '../node-require';
*/
const decoder = new TextDecoder();
const CONNECTING = 0; // WebSocket.CONNECTING
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()). */
@@ -69,7 +70,18 @@ export function eventSocket(host: EventfulSocket): WsSocket {
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(
host: Pick<EventfulSocket, 'readyState' | 'send' | 'close'> & { terminate?(): void },
inbound: ReturnType<typeof channel<unknown>>,
inbound: Channel<unknown>,
ac: AbortController,
): WsSocket {
return {
+215 -1
View File
@@ -1,8 +1,9 @@
import { isHttpError } from '../signals';
import { CHANNEL_TAP, type TappableChannel } from '../channel';
import type { Bus } from '../bus';
import { correlateRequest } from './core';
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). */
export interface WsRequest {
@@ -22,6 +23,219 @@ export interface WsSocket {
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. */
export function matchWsRoute(
wsRoutes: WsRouteDef[],
+73 -23
View File
@@ -1,8 +1,17 @@
import type http from 'http';
import { channel } from '../channel';
import type { Bus } from '../bus';
import { runWsConnection, matchWsRoute, trackUntil, type WsSocket, type WsRequest } from './ws-core';
import type { WsRouteDef, MeshControl } from './types';
import {
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';
/** 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. */
function reject501(socket: any): void {
socket.write('HTTP/1.1 501 Not Implemented\r\n\r\n');
/** Writes a bodyless HTTP status to the raw socket and destroys it. */
function rejectUpgrade(socket: any, status: number, text: string): void {
socket.write(`HTTP/1.1 ${status} ${text}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
socket.destroy();
}
@@ -31,11 +40,12 @@ function handleMeshUpgrade(
socket: any,
head: Buffer,
streams?: Set<() => void>,
limits?: RequestLimits,
): boolean {
if (path !== meshControl.path) return false;
if (!wss) {
reject501(socket);
rejectUpgrade(socket, 501, 'Not Implemented');
return true;
}
@@ -45,7 +55,7 @@ function handleMeshUpgrade(
// 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.
wss.handleUpgrade(req, socket, head, (ws: any) => {
const neutral = nodeSocket(ws);
const neutral = boundInbound(nodeSocket(ws), limits);
void trackUntil(neutral, meshControl.handle(neutral), streams);
});
@@ -97,29 +107,69 @@ export function attachWs(
bus?: Bus,
meshControl?: MeshControl,
streams?: Set<() => void>,
limits?: RequestLimits,
): void {
if (wsRoutes.length === 0 && !meshControl) return;
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) => {
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;
const route = matchWsRoute(wsRoutes, path);
if (!route) {
socket.destroy();
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();
}
});
}
if (!wss) {
reject501(socket);
return;
}
/** What every upgrade on one server shares. */
interface UpgradeEnv {
wss: any;
wsRoutes: WsRouteDef[];
bus?: Bus;
meshControl?: MeshControl;
streams?: Set<() => void>;
limits?: RequestLimits;
}
wss.handleUpgrade(req, socket, head, (ws: any) => {
void runWsConnection(nodeSocket(ws), nodeWsRequest(req), route, bus, streams);
});
/** 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);
if (!route) {
rejectUpgrade(socket, 404, 'Not Found');
return;
}
if (!wss) {
rejectUpgrade(socket, 501, 'Not Implemented');
return;
}
wss.handleUpgrade(req, socket, head, (ws: any) => {
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. */
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
* 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 {
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);
// 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) => {
let rel: string;
@@ -118,13 +161,13 @@ export function buildStaticResolver(root: string | true): StaticResolver {
const full = nodePath.resolve(abs, '.' + (rel.startsWith('/') ? rel : '/' + rel));
if (full !== abs && !full.startsWith(abs + nodePath.sep)) return undefined; // traversal guard
const rootReal = await resolveRoot();
if (!rootReal) return undefined;
try {
const stat = await fs.promises.stat(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)) };
return await readConfined(fs, nodePath, rootReal, full);
} 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 {}
const app = createApp({ modules: [M] });
@@ -96,4 +105,18 @@ describe('app.upgrade', () => {
await app.upgrade(req, socket);
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}`;
})();
}
// 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] })
class M {}
@@ -47,3 +63,77 @@ test('serveBun: HTTP + WebSocket round-trip', async () => {
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' });
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}`;
})();
}
// 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] })
@@ -69,3 +85,99 @@ Deno.test('serveDeno: HTTP + WebSocket round-trip through the graph', async () =
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.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
const wsRes = await mf.dispatchFetch('http://localhost/rt/echo', {
headers: { Upgrade: 'websocket' },
@@ -84,12 +111,59 @@ async function main() {
});
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 {
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) => {
console.error(err);
process.exit(1);
+32 -2
View File
@@ -1,7 +1,7 @@
// Worker entry for the real workerd (Miniflare) integration test.
// 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).
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';
@Route('/rt')
@@ -11,17 +11,47 @@ class Rt {
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')
echo(@ctx() { inbound }: any) {
return (async function* () {
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] })
class 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 { countingStream } from './helpers/counting-stream';
import { setPeer } from '../src/http/peer';
@Provider({ provides: 'store' })
class Store {
@@ -108,6 +110,57 @@ describe('app.fetch trustProxy gates x-forwarded-for', () => {
);
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', () => {
@@ -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();
});
// #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 () => {
const server = createHttpServer([], [], undefined, undefined,
{ limits: { maxConnections: 2468, requestTimeoutMs: 12345, headersTimeoutMs: 6789, keepAliveTimeoutMs: 4321 } });
+285
View File
@@ -0,0 +1,285 @@
import { afterEach, beforeEach, describe, expect, it, vi } 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: ReturnType<typeof vi.fn> } {
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: ReturnType<typeof vi.fn>;
let uncaught: ReturnType<typeof vi.fn>;
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);
});
});
+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';
// 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;
afterEach(async () => { await app?.close(); });
@@ -88,3 +102,63 @@ describe('bodyDuplicates', () => {
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);
});
});
+108 -1
View File
@@ -1,9 +1,11 @@
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 { tmpdir } from 'node:os';
import { createApp, Route, Get, Module } from '../src/index';
import { buildStaticResolver } from '../src/views';
import { isHttpError } from '../src/signals';
import type { ErrorRenderer } from '../src/transformers';
const root = join(tmpdir(), 'gt-static-test');
mkdirSync(root, { recursive: true });
@@ -67,3 +69,108 @@ describe('static serving', () => {
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();
});
});