feat(onebot): make the websocket frame cap configurable and diagnosable (#631)

- expose DEFAULT_MAX_PAYLOAD_BYTES; an inbound frame over the cap now reports its
  declared byte size, message type and the effective limit, recovered by walking
  the buffered frame stream so the number is right when a chunk carries several
  frames, the oversized header spans chunks, or control frames are interleaved;
  when the walk cannot reach a verdict the error names the cap without a size
- truncate close reasons to the RFC 6455 control-frame room on a UTF-8 boundary
  (an over-long reason previously produced an invalid control frame)
- add optional maxPayloadBytes (default 100 MiB unchanged) to the three adapters
  that read WebSocket frames: wsServers, wsClients and httpServers with
  enableWebSocket. httpClients rejects the field because it has no WebSocket
  transport, and the value is part of the binding signature so a change rebinds
  the transport instead of being saved without taking effect
- keep the existing 1009 log lines and append the actionable hint instead of
  replacing the template
- WebUI field (including httpServers once the embedded listener is on) and README
  docs for the 100 MiB => ~445 s (7:26) inline PCM consequence
This commit is contained in:
KazusaUwU authored and GitHub committed 2026-11-01 20:29:16 +08:00
1 parent bd40ac3522
commit 8d9f44b6b0
16 files changed
+1035 -77

No files matched your search

+1
View File
@@ -40,6 +40,7 @@ const Server = WebSocketServer;
const _internal = { WebSocket: InternalWebSocket, native };
export { WebSocketClient, WebSocketServer, Server, InternalWebSocket, _internal };
export { DEFAULT_MAX_PAYLOAD_BYTES } from './websocket';
export type { SendOptions, SendCallback, WebSocketRawData } from './websocket';
export type { WebSocketClientOptions } from './client';
+201 -6
View File
@@ -1,7 +1,7 @@
import { EventEmitter } from 'node:events';
import crypto from 'node:crypto';
import type { Socket } from 'node:net';
import native, { type ParsedFrame, type ParserInstance } from './native';
import native, { type ParsedFrame, type ParserInstance, type ParseResult } from './native';
import { type AcceptedPerMessageDeflate, compressRaw, decompressRaw } from './extensions';
// RFC 6455 opcodes.
@@ -19,7 +19,17 @@ export const OPEN = 1;
export const CLOSING = 2;
export const CLOSED = 3;
const DEFAULT_MAX_PAYLOAD = 100 * 1024 * 1024;
/**
* Default cap on one inbound WebSocket message (all fragments included).
* Exported so callers can name the default in configuration and diagnostics
* instead of duplicating the number.
*/
export const DEFAULT_MAX_PAYLOAD_BYTES = 100 * 1024 * 1024;
/** RFC 6455 §5.5 bounds a close frame's payload to 125 bytes; the 2-byte code
* leaves this much room for a reason. Long diagnostics are truncated (never
* mid-code-point) because an over-long reason would make the close invalid. */
const MAX_CLOSE_REASON_BYTES = 123;
export function isValidCloseCode(code: number): boolean {
if (
@@ -44,7 +54,7 @@ export function isValidCloseCode(code: number): boolean {
}
export function encodeClosePayload(code: number | undefined | null, reason?: string): Buffer {
const reasonBuf = reason ? Buffer.from(String(reason), 'utf8') : Buffer.alloc(0);
const reasonBuf = truncateCloseReason(reason);
if (code === undefined || code === null) {
if (reasonBuf.length > 0) {
@@ -60,6 +70,117 @@ export function encodeClosePayload(code: number | undefined | null, reason?: str
return buf;
}
/** UTF-8 safe truncation of a close reason to the RFC 6455 control-frame room. */
function truncateCloseReason(reason: string | undefined): Buffer {
if (!reason) {
return Buffer.alloc(0);
}
const encoded = Buffer.from(String(reason), 'utf8');
if (encoded.length <= MAX_CLOSE_REASON_BYTES) {
return encoded;
}
let end = MAX_CLOSE_REASON_BYTES;
// Back off to a code-point boundary: `encoded[end]` is the first dropped
// byte, and continuation bytes must never lead a truncated string.
while (end > 0 && (encoded[end]! & 0xc0) === 0x80) {
end -= 1;
}
return encoded.subarray(0, end);
}
/** Human label for the message type carried by a frame's opcode. */
function opcodeLabel(opcode: number): string {
if (opcode === OP_TEXT) {
return 'text';
}
if (opcode === OP_BIN) {
return 'binary';
}
return `opcode ${opcode}`;
}
interface FrameHeaderInfo {
opcode: number;
payloadBytes: number;
}
/** Budget for re-reading inbound bytes when an oversized frame is reported. */
const DIAG_BUFFER_LIMIT = 64 * 1024;
/**
* Walk a frame stream from `bytes` and return the first data frame whose declared
* payload exceeds `maxPayload`.
*
* The native parser rejects an oversized frame without saying where it is or how
* large it is, so the reporting path re-reads the bytes buffered since the last
* delivered message. Walking from a frame boundary removes the "the first bytes of
* this chunk are the offending header" assumption: earlier data frames, interleaved
* control frames and a header split across chunks are all stepped over correctly.
* Returns `null` when the walk cannot reach a verdict, in which case the caller
* reports the cap without a size instead of guessing.
*/
function scanOversizedFrame(bytes: Buffer, maxPayload: number): FrameHeaderInfo | null {
let offset = 0;
while (offset + 2 <= bytes.length) {
const first = bytes[offset]!;
const second = bytes[offset + 1]!;
const opcode = first & 0x0f;
const masked = (second & 0x80) !== 0;
const shortLength = second & 0x7f;
let payloadBytes: number;
let headerBytes: number;
if (shortLength === 126) {
if (offset + 4 > bytes.length) {
return null;
}
payloadBytes = bytes.readUInt16BE(offset + 2);
headerBytes = 4;
} else if (shortLength === 127) {
if (offset + 10 > bytes.length) {
return null;
}
const high = bytes.readUInt32BE(offset + 2);
const low = bytes.readUInt32BE(offset + 6);
if (high > 0x1fffff) {
return null;
}
payloadBytes = high * 2 ** 32 + low;
headerBytes = 10;
} else {
payloadBytes = shortLength;
headerBytes = 2;
}
if (masked) {
headerBytes += 4;
}
if (payloadBytes > maxPayload) {
// Only a data frame may legitimately exceed the cap; any other opcode
// means the walk is out of sync, so report nothing rather than a
// misleading number.
return opcode === OP_TEXT || opcode === OP_BIN ? { opcode, payloadBytes } : null;
}
offset += headerBytes + payloadBytes;
}
return null;
}
// Streaming UTF-8 validator used while a text message is being received in
// fragments. Returns false if invalid; `done()` checks code-point boundary.
class Utf8Validator {
@@ -176,6 +297,14 @@ export class WebSocket extends EventEmitter {
protected _msgValidator: Utf8Validator | null = null;
protected _msgCompressed = false;
// Diagnostic re-read of inbound bytes, kept only so an oversized-frame error
// can name the offending frame. It never feeds parsing, is cleared whenever a
// message is delivered, and downgrades the error text (instead of growing)
// once the small budget would be exceeded.
private _diagChunks: Buffer[] = [];
private _diagBytes = 0;
private _diagOverflow = false;
// Close state.
protected _closeCodeSent: number | null = null;
protected _closeCodeReceived: number | null = null;
@@ -194,7 +323,7 @@ export class WebSocket extends EventEmitter {
options = options || {};
this._socket = socket;
this._isServer = !!options.isServer;
this._maxPayload = options.maxPayload ?? DEFAULT_MAX_PAYLOAD;
this._maxPayload = options.maxPayload ?? DEFAULT_MAX_PAYLOAD_BYTES;
this._readyState = options.readyState ?? OPEN;
this._perMessageDeflate = options.extensions?.perMessageDeflate;
this.protocol = options.protocol || '';
@@ -230,10 +359,11 @@ export class WebSocket extends EventEmitter {
return;
}
this._recordDiagnosticBytes(chunk);
const res = this._parser.push(chunk);
if (res.error) {
this._failConnection(res.code || 1002, res.message || 'Protocol error');
this._failConnection(res.code || 1002, this._describeParseError(res));
return;
}
@@ -246,6 +376,67 @@ export class WebSocket extends EventEmitter {
}
}
/**
* Add the numbers a payload-limit failure needs to be actionable: how big the
* offending frame is, its message type, and the effective cap. The native
* parser only reports that the cap was exceeded, so the size is recovered by
* re-walking the buffered bytes; when that walk cannot reach a verdict the
* text names the cap alone instead of inventing a size.
*/
protected _describeParseError(res: ParseResult): string {
const message = res.message || 'Protocol error';
if (res.code !== 1009) {
return message;
}
const info = this._scanDiagnosticBytes();
this._resetDiagnosticBytes();
const limit = `${this._maxPayload} byte limit (maxPayloadBytes)`;
if (!info) {
return `${message}: an inbound frame exceeds the ${limit}`;
}
return `${message}: ${info.payloadBytes} B ${opcodeLabel(info.opcode)} frame exceeds the ${limit}`;
}
/** Keep a bounded copy of the bytes received since the last delivered message. */
private _recordDiagnosticBytes(chunk: Buffer): void {
if (this._diagOverflow) {
return;
}
if (this._diagBytes + chunk.length > DIAG_BUFFER_LIMIT) {
this._diagOverflow = true;
this._diagChunks = [];
this._diagBytes = 0;
return;
}
this._diagChunks.push(chunk);
this._diagBytes += chunk.length;
}
private _resetDiagnosticBytes(): void {
this._diagChunks = [];
this._diagBytes = 0;
this._diagOverflow = false;
}
private _scanDiagnosticBytes(): FrameHeaderInfo | null {
if (this._diagOverflow || this._diagChunks.length === 0) {
return null;
}
const bytes =
this._diagChunks.length === 1
? this._diagChunks[0]!
: Buffer.concat(this._diagChunks, this._diagBytes);
return scanOversizedFrame(bytes, this._maxPayload);
}
protected _onEnd(): void {
if (this._readyState !== CLOSED) {
if (this._closeCodeReceived === null) {
@@ -341,7 +532,10 @@ export class WebSocket extends EventEmitter {
this._msgSize += payload.length;
if (this._msgSize > this._maxPayload) {
this._failConnection(1009, 'Message too large');
this._failConnection(
1009,
`Message too large: ${this._msgSize} B ${opcodeLabel(this._msgOpcode)} message exceeds the ${this._maxPayload} byte limit (maxPayloadBytes)`,
);
return;
}
@@ -378,6 +572,7 @@ export class WebSocket extends EventEmitter {
this._msgSize = 0;
this._msgValidator = null;
this._msgCompressed = false;
this._resetDiagnosticBytes();
this.emit('message', data, isBinary);
}
}
+3 -1
View File
@@ -1033,7 +1033,9 @@ describe('WebSocketClient', () => {
),
);
const err = await events.waitError();
expect(err.message).toBe('WebSocket protocol error: Payload exceeds configured max');
expect(err.message).toBe(
'WebSocket protocol error: Payload exceeds configured max: 5 B text frame exceeds the 4 byte limit (maxPayloadBytes)',
);
expect((err as Error & { code?: number }).code).toBe(1009);
});
+152 -2
View File
@@ -9,6 +9,7 @@ import {
CLOSED,
CLOSING,
CONNECTING,
DEFAULT_MAX_PAYLOAD_BYTES,
OPEN,
OP_BIN,
OP_CLOSE,
@@ -102,6 +103,18 @@ function serverFrame(opcode: number, payload: Buffer, fin = true, rsv = 0): Buff
return native.buildFrame(opcode, fin, payload, null, rsv);
}
/** A masked header declaring `payloadBytes` with no payload — the parser rejects
* on the declared length before buffering any payload. */
function maskedOversizedHeader(opcode: number, payloadBytes: number): Buffer {
const header = Buffer.alloc(14);
header[0] = 0x80 | opcode;
header[1] = 0xff; // masked + 64-bit length
header.writeUInt32BE(Math.floor(payloadBytes / 2 ** 32), 2);
header.writeUInt32BE(payloadBytes % 2 ** 32, 6);
MASK.copy(header, 10);
return header;
}
function parseFrames(
buffers: Array<Buffer | undefined>,
expectMasked: boolean,
@@ -860,7 +873,9 @@ describe.skipIf(!nativeIo)('WebSocket incoming frames', () => {
});
socket.emit('data', clientFrame(OP_TEXT, Buffer.from('xxxxxx'), false));
socket.emit('data', clientFrame(OP_CONT, Buffer.from('xxxxx'), true));
expect(errors[0]!.message).toBe('WebSocket protocol error: Message too large');
expect(errors[0]!.message).toBe(
'WebSocket protocol error: Message too large: 11 B text message exceeds the 10 byte limit (maxPayloadBytes)',
);
expect(errors[0]!.code).toBe(1009);
});
@@ -871,10 +886,145 @@ describe.skipIf(!nativeIo)('WebSocket incoming frames', () => {
errors.push(err);
});
socket.emit('data', clientFrame(OP_TEXT, Buffer.from('hello')));
expect(errors[0]!.message).toBe('WebSocket protocol error: Payload exceeds configured max');
expect(errors[0]!.message).toBe(
'WebSocket protocol error: Payload exceeds configured max: 5 B text frame exceeds the 4 byte limit (maxPayloadBytes)',
);
expect(errors[0]!.code).toBe(1009);
});
it('reports the effective limit and frame size against the 100 MiB default', () => {
const { ws, socket } = createWs({ isServer: true });
const errors: Array<Error & { code?: number }> = [];
ws.on('error', (err) => {
errors.push(err);
});
const declared = 1024 * 1024 * 1024;
socket.emit('data', maskedOversizedHeader(OP_TEXT, declared));
expect(DEFAULT_MAX_PAYLOAD_BYTES).toBe(100 * 1024 * 1024);
expect(errors[0]!.message).toBe(
`WebSocket protocol error: Payload exceeds configured max: ${declared} B text frame exceeds the ${DEFAULT_MAX_PAYLOAD_BYTES} byte limit (maxPayloadBytes)`,
);
expect(errors[0]!.code).toBe(1009);
});
it('names the oversized frame when a smaller frame shares the chunk', () => {
const { ws, socket } = createWs({ isServer: true });
const errors: Array<Error & { code?: number }> = [];
ws.on('error', (err) => {
errors.push(err);
});
const declared = 1024 * 1024 * 1024;
// One TCP read: a complete 5-byte text frame followed by an oversized
// header. The offending header is NOT at offset 0 of the chunk.
socket.emit(
'data',
Buffer.concat([
clientFrame(OP_TEXT, Buffer.from('hello')),
maskedOversizedHeader(OP_TEXT, declared),
]),
);
expect(errors[0]!.message).toBe(
`WebSocket protocol error: Payload exceeds configured max: ${declared} B text frame exceeds the ${DEFAULT_MAX_PAYLOAD_BYTES} byte limit (maxPayloadBytes)`,
);
expect(errors[0]!.code).toBe(1009);
});
it('attributes an oversized frame whose header arrives in two chunks', () => {
const { ws, socket } = createWs({ isServer: true });
const errors: Array<Error & { code?: number }> = [];
ws.on('error', (err) => {
errors.push(err);
});
const declared = 1024 * 1024 * 1024;
const header = maskedOversizedHeader(OP_TEXT, declared);
socket.emit('data', header.subarray(0, 3));
expect(errors).toHaveLength(0); // incomplete header: parser waits
socket.emit('data', header.subarray(3));
expect(errors[0]!.message).toBe(
`WebSocket protocol error: Payload exceeds configured max: ${declared} B text frame exceeds the ${DEFAULT_MAX_PAYLOAD_BYTES} byte limit (maxPayloadBytes)`,
);
expect(errors[0]!.code).toBe(1009);
});
it('skips interleaved control frames while locating the oversized frame', () => {
const { ws, socket } = createWs({ isServer: true });
const errors: Array<Error & { code?: number }> = [];
ws.on('error', (err) => {
errors.push(err);
});
const declared = 1024 * 1024 * 1024;
socket.emit(
'data',
Buffer.concat([
clientFrame(OP_PING, Buffer.from('hb')),
maskedOversizedHeader(OP_BIN, declared),
]),
);
expect(errors[0]!.message).toBe(
`WebSocket protocol error: Payload exceeds configured max: ${declared} B binary frame exceeds the ${DEFAULT_MAX_PAYLOAD_BYTES} byte limit (maxPayloadBytes)`,
);
});
it('reports only the limit when the oversized header is outside the diagnostic budget', () => {
const maxPayload = 1024 * 1024;
const { ws, socket } = createWs({ isServer: true, maxPayload });
const errors: Array<Error & { code?: number }> = [];
ws.on('error', (err) => {
errors.push(err);
});
// Build up more than the 64 KiB diagnostic budget with a fragmented
// message, so the offending header never gets buffered.
const fragment = Buffer.alloc(8 * 1024, 0x61);
for (let i = 0; i < 12; i += 1) {
socket.emit('data', clientFrame(i === 0 ? OP_TEXT : OP_CONT, fragment, false));
}
socket.emit('data', maskedOversizedHeader(OP_TEXT, 2 * 1024 * 1024));
expect(errors[0]!.message).toBe(
'WebSocket protocol error: Payload exceeds configured max: an inbound frame exceeds the 1048576 byte limit (maxPayloadBytes)',
);
expect(errors[0]!.message).not.toMatch(/\d+ B /);
expect(errors[0]!.code).toBe(1009);
});
it('names the message type when a binary frame exceeds the limit', () => {
const { ws, socket } = createWs({ isServer: true, maxPayload: 4 });
const errors: Array<Error & { code?: number }> = [];
ws.on('error', (err) => {
errors.push(err);
});
socket.emit('data', clientFrame(OP_BIN, Buffer.from([1, 2, 3, 4, 5])));
expect(errors[0]!.message).toBe(
'WebSocket protocol error: Payload exceeds configured max: 5 B binary frame exceeds the 4 byte limit (maxPayloadBytes)',
);
expect(errors[0]!.code).toBe(1009);
});
it('accepts a message exactly at the configured limit', () => {
const { ws, socket } = createWs({ isServer: true, maxPayload: 5 });
const messages: Array<{ data: Buffer; isBinary: boolean }> = [];
ws.on('message', (data, isBinary) => {
messages.push({ data, isBinary });
});
socket.emit('data', clientFrame(OP_TEXT, Buffer.from('hello')));
expect(messages).toEqual([{ data: Buffer.from('hello'), isBinary: false }]);
});
it('truncates an over-long close reason on a code-point boundary', () => {
const payload = encodeClosePayload(1009, 'é'.repeat(200));
expect(payload.length).toBeLessThanOrEqual(125);
const reason = payload.subarray(2).toString('utf8');
expect(reason).toBe('é'.repeat(61));
expect(Buffer.from(reason, 'utf8').equals(payload.subarray(2))).toBe(true);
});
it('truncates a 4-byte code point without splitting it', () => {
const payload = encodeClosePayload(1009, '😀'.repeat(50));
expect(payload.length).toBe(122); // 2-byte code + 30 whole code points
const reason = payload.subarray(2).toString('utf8');
expect(reason).toBe('😀'.repeat(30));
expect(Buffer.from(reason, 'utf8').equals(payload.subarray(2))).toBe(true);
});
it('inflates a compressed text frame when deflate was negotiated', () => {
const { ws, socket } = createWs({
isServer: true,