feat(ws)!: bound inbound WebSocket message size and queue

Inbound WebSocket traffic was unbounded per connection: Node used ws's
100 MiB default payload, the other runtimes had no cap of their own, and
the queue behind `inbound` was an unbounded channel on every runtime, so
one client could exhaust memory with large messages or a slow consumer.

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

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

Closes #107

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-09 13:59:35 -05:00
1 parent 59763c9af5
commit 0540bef07b
13 files changed
+762 -34

No files matched your search

+64
View File
@@ -21,6 +21,15 @@ class Rt {
})();
}
// 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* () {
@@ -73,3 +82,58 @@ test('serveBun: a malformed upgrade path closes 1008 and the server keeps servin
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);
}
});
+76
View File
@@ -29,6 +29,15 @@ class Rt {
})();
}
// 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* () {
@@ -105,3 +114,70 @@ Deno.test('serveDeno: a malformed upgrade path closes 1008 and the server keeps
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();
}
});
+35 -1
View File
@@ -97,12 +97,46 @@ async function main() {
assert.deepEqual(await closed, { code: 1008, reason: 'invalid request path' });
assert.equal((await mf.dispatchFetch('http://localhost/rt/hello')).status, 200);
console.log('edge (workerd via miniflare): HTTP 200 + WS echo:hi — PASS');
// #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 + 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);
+16 -1
View File
@@ -18,6 +18,15 @@ class Rt {
})();
}
// 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* () {
@@ -30,5 +39,11 @@ class 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),
};
+312
View File
@@ -0,0 +1,312 @@
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('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');
});
});