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

+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,