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

+8
View File
@@ -66,6 +66,14 @@ SnowLuma 是面向 QQ 客户端的 TypeScript 互操作运行时,将 QQ 原生
JSON 消息段接受标准的 `data.data` 字符串,也兼容 `data.data` 非数组对象和 `{ type: "json", data: "..." }` 简写;`data` 必填,最终内容必须是 JSON 对象。
## 已知限制
### WebSocket 单帧上限与超长语音
SnowLuma 读取 WebSocket 帧的上限默认是 **100 MiB**,可在每个 WebSocket 适配器上用 `maxPayloadBytes` 调整(WebUI 连接配置中为「单帧上限 (bytes)」),服务端与客户端两个方向都生效。
对 OneBot 的内联媒体消息,这等于整段音频必须装进一帧:44.1 kHz 立体声 16-bit PCM(176 400 B/s)在 100 MiB 下只够 **约 445 秒(7 分 26 秒)**。超限时连接以 1009 关闭,日志会给出帧字节数、消息类型和当时生效的上限。更长的音频请让上游改发 URL/文件引用,或在发送前压缩(如 SILK);单纯调大上限会按帧大小占用内存,不建议作为常规手段。
## 开发
需要 Node.js 24+ 与 pnpm 11.25.0,日常开发基于 `dev` 分支:
+75 -2
View File
@@ -24,6 +24,11 @@ const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
const NODE_TIMER_MAX_MS = 2_147_483_647;
/** Bounds for a per-adapter inbound WebSocket frame cap. 2 GiB is several
* orders of magnitude past any real OneBot frame; above that a sender has to
* split its payload instead of expecting a single buffer to hold it. */
const MAX_PAYLOAD_BYTES_MIN = 1024;
const MAX_PAYLOAD_BYTES_MAX = 2 * 1024 * 1024 * 1024;
const PER_UIN_SNAPSHOT_MARKER = 'snapshot';
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = {
@@ -412,11 +417,15 @@ function validateRestoreAdapterArray(
: ['url', 'role', 'reconnectIntervalMs'];
if (kind === 'httpServers') {
specific.push('enableWebSocket');
specific.push('enableWebSocket', 'maxPayloadBytes');
}
if (kind === 'wsServers') {
specific.push('role');
specific.push('role', 'maxPayloadBytes');
}
if (kind === 'wsClients') {
specific.push('maxPayloadBytes');
}
const allowed = new Set<string>([...RESTORE_BASE_ADAPTER_KEYS, ...specific]);
@@ -453,6 +462,20 @@ function validateRestoreAdapterArray(
invalid(`${pathAt}.reportSelfMessage must be a boolean`);
}
if (kind !== 'httpClients' && raw.maxPayloadBytes !== undefined) {
const maxPayload = parseRestoreInteger(raw.maxPayloadBytes);
if (
maxPayload === null ||
maxPayload < MAX_PAYLOAD_BYTES_MIN ||
maxPayload > MAX_PAYLOAD_BYTES_MAX
) {
invalid(
`${pathAt}.maxPayloadBytes must be an integer between ${MAX_PAYLOAD_BYTES_MIN} and ${MAX_PAYLOAD_BYTES_MAX}`,
);
}
}
if (kind === 'httpServers' || kind === 'wsServers') {
const port = parseRestoreInteger(raw.port);
@@ -656,6 +679,7 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
const serverBindings = new Map<string, string>();
validateNetworkList(value.networks, 'httpServers', seen, (item, at) => {
validateServer(item, at);
validateMaxPayloadBytes(item, at);
if (item.enableWebSocket !== undefined && typeof item.enableWebSocket !== 'boolean') {
invalid(`${at}.enableWebSocket must be a boolean`);
@@ -666,6 +690,11 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
validateNetworkList(value.networks, 'httpClients', seen, (item, at) => {
validateClient(item, at, new Set(['http:', 'https:']));
// A frame cap on the pure HTTP POST adapter would be saved and ignored.
if (item.maxPayloadBytes !== undefined) {
invalid(`${at}.maxPayloadBytes is only supported by WebSocket adapters`);
}
if (
item.timeoutMs !== undefined &&
(typeof item.timeoutMs !== 'number' ||
@@ -680,10 +709,12 @@ export function assertValidOneBotConfig(value: unknown): asserts value is OneBot
validateServer(item, at);
validateServerBinding(item, at, serverBindings);
validateRole(item.role, `${at}.role`);
validateMaxPayloadBytes(item, at);
});
validateNetworkList(value.networks, 'wsClients', seen, (item, at) => {
validateClient(item, at, new Set(['ws:', 'wss:']));
validateRole(item.role, `${at}.role`);
validateMaxPayloadBytes(item, at);
if (
item.reconnectIntervalMs !== undefined &&
@@ -816,6 +847,24 @@ function validateNetworkBase(item: JsonObject, at: string): void {
}
}
/** Strict gate for the WebSocket-only frame cap; `httpClients` must not carry it. */
function validateMaxPayloadBytes(item: JsonObject, at: string): void {
if (item.maxPayloadBytes === undefined) {
return;
}
if (
typeof item.maxPayloadBytes !== 'number' ||
!Number.isSafeInteger(item.maxPayloadBytes) ||
item.maxPayloadBytes < MAX_PAYLOAD_BYTES_MIN ||
item.maxPayloadBytes > MAX_PAYLOAD_BYTES_MAX
) {
invalid(
`${at}.maxPayloadBytes must be an integer between ${MAX_PAYLOAD_BYTES_MIN} and ${MAX_PAYLOAD_BYTES_MAX}`,
);
}
}
function validateServer(item: JsonObject, at: string): void {
if (
!Number.isInteger(item.port) ||
@@ -1030,6 +1079,7 @@ function applyBase(
accessToken?: string;
messageFormat: MessageFormat;
reportSelfMessage: boolean;
maxPayloadBytes?: number;
},
): void {
out.name = n.name;
@@ -1044,6 +1094,10 @@ function applyBase(
out.messageFormat = n.messageFormat;
out.reportSelfMessage = n.reportSelfMessage;
if (n.maxPayloadBytes !== undefined) {
out.maxPayloadBytes = n.maxPayloadBytes;
}
}
function httpServerToJson(n: HttpServerNetwork): JsonObject {
@@ -1361,6 +1415,22 @@ function parseBase(value: JsonObject, defaults: AdapterDefaults) {
};
}
/**
* Compatibility parser for the optional frame cap. Clamps like its neighbours
* (`timeoutMs`, `reconnectIntervalMs`) so an on-disk value written by an
* older/newer build still loads; `assertValidOneBotConfig` is the strict gate
* for values saved through the API/WebUI.
*/
function parseMaxPayloadBytes(value: unknown): number | undefined {
const parsed = asNumber(value, 0);
if (parsed <= 0) {
return undefined;
}
return Math.min(Math.max(parsed, MAX_PAYLOAD_BYTES_MIN), MAX_PAYLOAD_BYTES_MAX);
}
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
if (value.enableWebSocket !== undefined && typeof value.enableWebSocket !== 'boolean') {
invalid('http server enableWebSocket must be a boolean');
@@ -1378,6 +1448,7 @@ function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServ
port,
path: asString(value.path, '/'),
enableWebSocket: value.enableWebSocket === true,
maxPayloadBytes: parseMaxPayloadBytes(value.maxPayloadBytes),
});
}
@@ -1410,6 +1481,7 @@ function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNe
port,
path: asString(value.path, '/'),
role: asRole(value.role, 'Universal'),
maxPayloadBytes: parseMaxPayloadBytes(value.maxPayloadBytes),
});
}
@@ -1427,6 +1499,7 @@ function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNe
url,
role: asRole(value.role, 'Universal'),
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
maxPayloadBytes: parseMaxPayloadBytes(value.maxPayloadBytes),
});
}
@@ -215,7 +215,12 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
protected override bindingSignature(config: HttpServerNetwork): string {
const webSocket = config.enableWebSocket === true ? 'ws' : 'http';
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}`;
// The frame cap is fixed when the WebSocketServer is constructed, so a
// change must rebind instead of silently keeping the old limit — but only
// when this adapter actually owns a WebSocket transport, otherwise the
// HTTP listener would be torn down for a value it never uses.
const maxPayload = config.enableWebSocket === true ? (config.maxPayloadBytes ?? '') : '';
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path ?? '/')}#${webSocket}#${maxPayload}`;
}
protected override onConfigReplaced(next: HttpServerNetwork): void {
@@ -242,6 +247,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
if (this.config.enableWebSocket === true) {
webSocketServer = new WebSocketServer({
server,
maxPayload: this.config.maxPayloadBytes,
verifyClient: ({ req }: { req: IncomingMessage }) =>
this.webSocketConnections.authorizeUpgrade(req),
});
+7
View File
@@ -2,6 +2,13 @@ import { StreamTransportClosedError } from '../streaming';
import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
/**
* Appended to a 1009 (frame-over-cap) log line. Shared so the client and server
* adapters cannot drift apart on the advice they give.
*/
export const MAX_PAYLOAD_HINT =
"Raise this adapter's maxPayloadBytes, or have the peer send a smaller frame (a URL/file reference or SILK instead of inline PCM)";
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) {
return true;
@@ -8,7 +8,14 @@ import {
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend, safeSendAsync, startHeartbeat } from './utils';
import {
MAX_PAYLOAD_HINT,
rawDataToString,
safeClose,
safeSend,
safeSendAsync,
startHeartbeat,
} from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
@@ -107,7 +114,9 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
}
protected override bindingSignature(config: WsClientNetwork): string {
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}`;
// The frame cap is baked into the socket when it is created, so a change
// must reconnect instead of silently keeping the old limit.
return `${config.url}#${config.role ?? 'Universal'}#${Math.max(1000, config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${config.accessToken ?? ''}#${config.maxPayloadBytes ?? ''}`;
}
protected override willEnable(config: WsClientNetwork): boolean {
@@ -160,7 +169,10 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
const socket = new WebSocket(this.config.url, {
headers,
maxPayload: this.config.maxPayloadBytes,
});
this.socket = socket;
// Per-socket so a hot-reload overlap (old close firing after the new socket
// is assigned, see #97) can only ever stop its own keepalive.
@@ -255,11 +267,16 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
});
socket.on('error', (err: Error) => {
// Keep the established `error <url>:` line intact (deployments grep
// it); the actionable hint is appended, never substituted.
const message = err instanceof Error ? err.message : String(err);
this.log.warn(
'[%s] error %s: %s',
this.name,
this.config.url,
err instanceof Error ? err.message : String(err),
(err as Error & { code?: number }).code === 1009
? `${message}. ${MAX_PAYLOAD_HINT}`
: message,
);
});
}
@@ -154,7 +154,9 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
}
protected override bindingSignature(config: WsServerNetwork): string {
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}`;
// The frame cap is fixed when the WebSocketServer is constructed, so a
// change must rebind instead of silently keeping the old limit.
return `${config.host ?? '0.0.0.0'}:${config.port}${normalizePath(config.path)}#${config.role ?? 'auto'}#${config.accessToken ?? ''}#${config.maxPayloadBytes ?? ''}`;
}
protected override onConfigReplaced(next: WsServerNetwork): void {
@@ -177,6 +179,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
maxPayload: this.config.maxPayloadBytes,
verifyClient: (
{ req }: { req: IncomingMessage },
done: (allow: boolean, code?: number, message?: string) => void,
@@ -10,6 +10,7 @@ import {
import type { JsonObject, NetworkBase, WsRole } from '../types';
import type { NetworkAdapterContext } from './adapter';
import {
MAX_PAYLOAD_HINT,
isAuthorized,
normalizePath,
parseRequestPath,
@@ -211,10 +212,15 @@ export class WsServerConnections {
this.connections.delete(socket);
});
socket.on('error', (error: Error) => {
// Keep the established `socket error:` line intact (deployments grep
// it); the actionable hint is appended, never substituted.
const message = error instanceof Error ? error.message : String(error);
this.log.warn(
'[%s] socket error: %s',
this.name,
error instanceof Error ? error.message : String(error),
(error as Error & { code?: number }).code === 1009
? `${message}. ${MAX_PAYLOAD_HINT}`
: message,
);
});
+24 -3
View File
@@ -38,7 +38,28 @@ export interface NetworkBase {
reportSelfMessage: boolean;
}
export interface HttpServerNetwork extends NetworkBase {
/**
* Inbound WebSocket frame cap, shared by the three adapters that read WebSocket
* frames: `wsServers`, `wsClients`, and `httpServers` with `enableWebSocket`.
* It is deliberately not part of {@link NetworkBase}: `httpClients` has no
* WebSocket transport, and a saved-but-ignored option is worse than none.
*/
export interface WsFrameLimitConfig {
/**
* Cap on one inbound WebSocket message, in bytes (all fragments included).
* Omitted means the transport default of 100 MiB
* (`DEFAULT_MAX_PAYLOAD_BYTES`).
*
* Frames larger than the cap close the connection with 1009. A OneBot peer
* that sends media inline has to fit the whole payload into one frame: at
* 44.1 kHz stereo 16-bit PCM (176 400 B/s), 100 MiB is ~445 s (7:26), so
* longer audio must arrive as a URL/file reference or be compressed (SILK).
* Raising this value raises peak memory by the frame size.
*/
maxPayloadBytes?: number;
}
export interface HttpServerNetwork extends NetworkBase, WsFrameLimitConfig {
host?: string;
port: number;
path?: string;
@@ -51,14 +72,14 @@ export interface HttpClientNetwork extends NetworkBase {
timeoutMs?: number;
}
export interface WsServerNetwork extends NetworkBase {
export interface WsServerNetwork extends NetworkBase, WsFrameLimitConfig {
host?: string;
port: number;
path?: string;
role?: WsRole;
}
export interface WsClientNetwork extends NetworkBase {
export interface WsClientNetwork extends NetworkBase, WsFrameLimitConfig {
url: string;
role?: WsRole;
reconnectIntervalMs?: number;
+134
View File
@@ -148,6 +148,44 @@ describe('assertValidOneBotConfig', () => {
expect(() => assertValidOneBotConfig(ws)).toThrow(/reconnectIntervalMs/);
});
it('bounds maxPayloadBytes when one is configured', () => {
for (const invalid of [0, 1023, 2 * 1024 * 1024 * 1024 + 1, 1024.5, '104857600']) {
const config = makeDefaultOneBotConfig();
config.networks.wsServers[0].maxPayloadBytes = invalid as unknown as number;
expect(() => assertValidOneBotConfig(config), String(invalid)).toThrow(
/maxPayloadBytes/,
);
}
const accepted = makeDefaultOneBotConfig();
accepted.networks.wsServers[0].maxPayloadBytes = 1024;
expect(() => assertValidOneBotConfig(accepted)).not.toThrow();
// The third WebSocket-capable adapter: httpServers with the embedded WS.
const httpWs = makeDefaultOneBotConfig();
httpWs.networks.httpServers[0].enableWebSocket = true;
httpWs.networks.httpServers[0].maxPayloadBytes = 2048;
expect(() => assertValidOneBotConfig(httpWs)).not.toThrow();
});
it('rejects maxPayloadBytes on the pure HTTP client adapter', () => {
const config = makeDefaultOneBotConfig();
config.networks.httpClients.push({
name: 'mirror',
url: 'http://127.0.0.1:9000',
messageFormat: 'array',
reportSelfMessage: false,
});
// HttpPostAdapter has no WebSocket transport, so the value could only be
// saved and silently ignored.
(config.networks.httpClients[0] as unknown as Record<string, unknown>).maxPayloadBytes =
1024;
expect(() => assertValidOneBotConfig(config)).toThrow(
/maxPayloadBytes is only supported by WebSocket adapters/,
);
});
it('rejects server paths that cannot match a URL pathname', () => {
for (const invalidPath of ['api', '/api?token=x', '/api#fragment', ' /api']) {
const config = makeDefaultOneBotConfig();
@@ -365,6 +403,102 @@ describe('loadOneBotConfig', () => {
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
});
it('round-trips maxPayloadBytes (both directions) and omits it when unset', () => {
const uin = '10020';
const config = makeDefaultOneBotConfig();
config.networks.wsServers[0].maxPayloadBytes = 512 * 1024 * 1024;
config.networks.wsClients.push({
name: 'astrbot',
url: 'ws://127.0.0.1:6199/ws',
messageFormat: 'array',
reportSelfMessage: false,
maxPayloadBytes: 256 * 1024 * 1024,
});
saveOneBotConfig(uin, config);
const onDisk = JSON.parse(
fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'),
);
expect(onDisk.networks.wsServers[0].maxPayloadBytes).toBe(512 * 1024 * 1024);
expect(onDisk.networks.wsClients[0].maxPayloadBytes).toBe(256 * 1024 * 1024);
// Unset adapters must not gain the key, so existing configs stay byte-stable.
expect(onDisk.networks.httpServers[0].maxPayloadBytes).toBeUndefined();
const reloaded = loadOneBotConfig(uin);
expect(reloaded.networks.wsServers[0].maxPayloadBytes).toBe(512 * 1024 * 1024);
expect(reloaded.networks.wsClients[0]!.maxPayloadBytes).toBe(256 * 1024 * 1024);
const prepared = prepareOneBotConfigForRestore(onDisk, 'per-uin');
const preparedNetworks = prepared.value.networks as {
wsClients: Array<Record<string, unknown>>;
};
expect(preparedNetworks.wsClients[0]!.maxPayloadBytes).toBe(256 * 1024 * 1024);
const junk = structuredClone(onDisk) as {
networks: { wsClients: Array<Record<string, unknown>> };
};
junk.networks.wsClients[0]!.maxPayloadBytes = 0;
expect(() => prepareOneBotConfigForRestore(junk, 'per-uin')).toThrow(/maxPayloadBytes/);
});
it('persists maxPayloadBytes for httpServers and drops it for httpClients', () => {
const uin = '10021';
const config = makeDefaultOneBotConfig();
config.networks.httpServers[0].enableWebSocket = true;
config.networks.httpServers[0].maxPayloadBytes = 4096;
saveOneBotConfig(uin, config);
const onDisk = JSON.parse(
fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'),
);
expect(onDisk.networks.httpServers[0].maxPayloadBytes).toBe(4096);
expect(loadOneBotConfig(uin).networks.httpServers[0].maxPayloadBytes).toBe(4096);
expect(() => prepareOneBotConfigForRestore(onDisk, 'per-uin')).not.toThrow();
// A restore source that carries the key on a non-WS adapter is rejected
// rather than accepted into a config where it can never apply.
const withHttpClient = structuredClone(onDisk) as {
networks: { httpClients: Array<Record<string, unknown>> };
};
withHttpClient.networks.httpClients.push({
name: 'mirror',
url: 'http://127.0.0.1:9000',
maxPayloadBytes: 4096,
});
expect(() => prepareOneBotConfigForRestore(withHttpClient, 'per-uin')).toThrow(
/maxPayloadBytes is not supported/,
);
// A hand-written file is parsed permissively, but the key is not carried
// into the canonical config (nor written back).
const dir = path.join(tempDir, 'config');
fs.writeFileSync(
path.join(dir, 'onebot_10022.json'),
JSON.stringify({
mode: 'snapshot',
networks: {
httpServers: [],
httpClients: [
{
name: 'mirror',
url: 'http://127.0.0.1:9000',
messageFormat: 'array',
reportSelfMessage: false,
maxPayloadBytes: 4096,
},
],
wsServers: [],
wsClients: [],
},
}),
'utf8',
);
const loaded = loadOneBotConfig('10022');
expect(
(loaded.networks.httpClients[0] as unknown as Record<string, unknown>).maxPayloadBytes,
).toBeUndefined();
});
it('replays a saved per-UIN snapshot without reviving deleted global adapters', () => {
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
@@ -0,0 +1,269 @@
// The native WebSocket addon is not built in a plain checkout, so the
// transport is faked (same pattern as network-bootstrap-meta.test.ts). These
// tests pin the config → transport wiring for `maxPayloadBytes`: the value must
// reach both WebSocketServer and WebSocket, an unset value must leave the
// transport default alone, and changing it must rebind/reconnect because the
// cap is fixed when the socket is created.
import { beforeEach, describe, expect, it, vi } from 'vitest';
const { FakeWebSocket, FakeWebSocketServer, clientInstances, clientOptions, servers } = vi.hoisted(
() => {
// eslint-disable-next-line @typescript-eslint/no-require-imports
const { EventEmitter } = require('node:events') as typeof import('node:events');
const clientInstances: FakeWebSocket[] = [];
const clientOptions: unknown[] = [];
const servers: FakeWebSocketServer[] = [];
class FakeWebSocket extends EventEmitter {
public readyState = 1;
constructor(
public readonly url = '',
options?: unknown,
) {
super();
clientInstances.push(this);
clientOptions.push(options);
}
send(): void {}
close(): void {
this.readyState = 3;
}
terminate(): void {
this.readyState = 3;
}
}
class FakeWebSocketServer extends EventEmitter {
public closed = false;
constructor(public readonly options?: unknown) {
super();
servers.push(this);
}
close(cb?: (error?: Error) => void): void {
this.closed = true;
cb?.();
}
}
return { FakeWebSocket, FakeWebSocketServer, clientInstances, clientOptions, servers };
},
);
vi.mock('@snowluma/websocket', () => ({
WebSocket: FakeWebSocket,
WebSocketServer: FakeWebSocketServer,
}));
import type { NetworkAdapterContext } from '../src/network/adapter';
import { HttpServerAdapter } from '../src/network/http-server-adapter';
import { WsClientAdapter } from '../src/network/ws-client-adapter';
import { WsServerAdapter } from '../src/network/ws-server-adapter';
import type { HttpServerNetwork, WsClientNetwork, WsServerNetwork } from '../src/types';
function ctx(): NetworkAdapterContext {
return {
uin: '10001',
api: { processStreamRequest: async () => {}, isAcceptingActions: true } as never,
buildLifecycleEvent: () => ({ post_type: 'meta_event' }),
buildHeartbeatEvent: () => ({ post_type: 'meta_event' }),
};
}
function serverConfig(over: Partial<WsServerNetwork> = {}): WsServerNetwork {
return {
name: 'ws-in',
enabled: true,
host: '127.0.0.1',
port: 3001,
path: '/',
role: 'Universal',
accessToken: '',
maxPayloadBytes: undefined,
...over,
} as WsServerNetwork;
}
function clientConfig(over: Partial<WsClientNetwork> = {}): WsClientNetwork {
return {
name: 'ws-out',
enabled: true,
url: 'ws://127.0.0.1:6199/ws',
role: 'Universal',
reconnectIntervalMs: 1000,
maxPayloadBytes: undefined,
...over,
} as WsClientNetwork;
}
async function openServer(adapter: WsServerAdapter): Promise<void> {
const opening = adapter.open();
servers[servers.length - 1]!.emit('listening');
await opening;
}
describe('WsServerAdapter — maxPayloadBytes wiring', () => {
beforeEach(() => {
servers.length = 0;
});
it('forwards the configured cap to the WebSocketServer', async () => {
const adapter = new WsServerAdapter(
'ws-in',
serverConfig({ maxPayloadBytes: 262_144_000 }),
ctx(),
);
await openServer(adapter);
expect(servers[0]!.options).toMatchObject({ maxPayload: 262_144_000 });
await adapter.close();
});
it('leaves the transport default in place when the cap is unset', async () => {
const adapter = new WsServerAdapter('ws-in', serverConfig(), ctx());
await openServer(adapter);
expect((servers[0]!.options as { maxPayload?: number }).maxPayload).toBeUndefined();
await adapter.close();
});
it('rebinds when only maxPayloadBytes changes', async () => {
const adapter = new WsServerAdapter(
'ws-in',
serverConfig({ maxPayloadBytes: 1024 }),
ctx(),
);
await openServer(adapter);
const reloading = adapter.reload(serverConfig({ maxPayloadBytes: 2048 }));
await vi.waitFor(() => expect(servers).toHaveLength(2));
servers[1]!.emit('listening');
expect(await reloading).toBe(1); // NetworkReloadType.Reopened
expect(servers[1]!.options).toMatchObject({ maxPayload: 2048 });
expect(servers[0]!.closed).toBe(true);
await adapter.close();
});
});
describe('WsClientAdapter — maxPayloadBytes wiring', () => {
beforeEach(() => {
clientInstances.length = 0;
clientOptions.length = 0;
});
it('forwards the configured cap to the WebSocket client', () => {
const adapter = new WsClientAdapter(
'ws-out',
clientConfig({ maxPayloadBytes: 524_288_000 }),
ctx(),
);
adapter.open();
expect(clientOptions[0]).toMatchObject({ maxPayload: 524_288_000 });
adapter.forceClose();
});
it('leaves the transport default in place when the cap is unset', () => {
const adapter = new WsClientAdapter('ws-out', clientConfig(), ctx());
adapter.open();
expect((clientOptions[0] as { maxPayload?: number }).maxPayload).toBeUndefined();
adapter.forceClose();
});
it('reconnects when only maxPayloadBytes changes', async () => {
const adapter = new WsClientAdapter(
'ws-out',
clientConfig({ maxPayloadBytes: 1024 }),
ctx(),
);
adapter.open();
const first = clientInstances[0]!;
first.emit('open');
// The old socket's close event fires after the new one exists; the
// adapter ignores it (#97), so the reconnect must come from reload().
await adapter.reload(clientConfig({ maxPayloadBytes: 4096 }));
expect(clientInstances).toHaveLength(2);
expect(clientOptions[1]).toMatchObject({ maxPayload: 4096 });
adapter.forceClose();
});
});
// The third place that reads WebSocket frames: the WebSocket server embedded in
// an HTTP listener. It has no fake-specific seam beyond the WebSocketServer mock,
// so these cases run the real HTTP listener on an ephemeral port.
describe('HttpServerAdapter (embedded WebSocket) — maxPayloadBytes wiring', () => {
beforeEach(() => {
servers.length = 0;
});
function httpConfig(over: Partial<HttpServerNetwork> = {}): HttpServerNetwork {
return {
name: 'http-in',
enabled: true,
host: '127.0.0.1',
port: 0,
path: '/',
enableWebSocket: true,
accessToken: '',
messageFormat: 'array',
reportSelfMessage: false,
maxPayloadBytes: undefined,
...over,
} as HttpServerNetwork;
}
it('forwards the configured cap to the embedded WebSocketServer', async () => {
const adapter = new HttpServerAdapter(
'http-in',
httpConfig({ maxPayloadBytes: 131_072 }),
ctx(),
);
await adapter.open();
expect(servers[0]!.options).toMatchObject({ maxPayload: 131_072 });
await adapter.close();
});
it('leaves the transport default in place when the cap is unset', async () => {
const adapter = new HttpServerAdapter('http-in', httpConfig(), ctx());
await adapter.open();
expect((servers[0]!.options as { maxPayload?: number }).maxPayload).toBeUndefined();
await adapter.close();
});
it('rebinds when only maxPayloadBytes changes', async () => {
const adapter = new HttpServerAdapter(
'http-in',
httpConfig({ maxPayloadBytes: 1024 }),
ctx(),
);
await adapter.open();
const reloading = adapter.reload(httpConfig({ maxPayloadBytes: 2048 }));
await vi.waitFor(() => expect(servers).toHaveLength(2));
expect(await reloading).toBe(1); // NetworkReloadType.Reopened
expect(servers[1]!.options).toMatchObject({ maxPayload: 2048 });
await adapter.close();
});
it('does not rebind for a cap change while the adapter has no WebSocket transport', async () => {
const adapter = new HttpServerAdapter(
'http-in',
httpConfig({ enableWebSocket: false, maxPayloadBytes: 1024 }),
ctx(),
);
await adapter.open();
expect(servers).toHaveLength(0); // no WS server without the opt-in
const reloading = adapter.reload(
httpConfig({ enableWebSocket: false, maxPayloadBytes: 2048 }),
);
expect(await reloading).toBe(0); // NetworkReloadType.Normal: listener untouched
await adapter.close();
});
});
+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,
@@ -346,25 +346,29 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
const it = draft as HttpServerNetwork;
const set = patch as (c: Partial<HttpServerNetwork>) => void;
return (
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
<Field
label="端口"
type="number"
value={it.port}
onChange={(v) => set({ port: Number(v) || 0 })}
/>
<Field
label="路径"
placeholder="/"
value={it.path}
onChange={(v) => set({ path: v || undefined })}
/>
<div className="flex flex-col gap-2">
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
<Field
label="端口"
type="number"
value={it.port}
onChange={(v) => set({ port: Number(v) || 0 })}
/>
<Field
label="路径"
placeholder="/"
value={it.path}
onChange={(v) => set({ path: v || undefined })}
/>
</div>
{/* The cap only exists for the embedded WebSocket listener. */}
{it.enableWebSocket === true ? maxPayloadField(it.maxPayloadBytes, set) : null}
</div>
);
}
@@ -396,25 +400,28 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
const it = draft as WsServerNetwork;
const set = patch as (c: Partial<WsServerNetwork>) => void;
return (
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
<Field
label="端口"
type="number"
value={it.port}
onChange={(v) => set({ port: Number(v) || 0 })}
/>
<Field
label="路径"
placeholder="/"
value={it.path}
onChange={(v) => set({ path: v || undefined })}
/>
<div className="flex flex-col gap-2">
<div className="grid gap-3 sm:grid-cols-[1fr_120px_140px]">
<Field
label="主机"
placeholder="127.0.0.1"
value={it.host}
onChange={(v) => set({ host: v || undefined })}
/>
<Field
label="端口"
type="number"
value={it.port}
onChange={(v) => set({ port: Number(v) || 0 })}
/>
<Field
label="路径"
placeholder="/"
value={it.path}
onChange={(v) => set({ path: v || undefined })}
/>
</div>
{maxPayloadField(it.maxPayloadBytes, set)}
</div>
);
}
@@ -423,20 +430,23 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
const it = draft as WsClientNetwork;
const set = patch as (c: Partial<WsClientNetwork>) => void;
return (
<div className="grid gap-3 sm:grid-cols-[1fr_160px]">
<Field
label="目标 URL"
type="url"
placeholder="ws://..."
value={it.url}
onChange={(v) => set({ url: v })}
/>
<Field
label="重连间隔 (ms)"
type="number"
value={it.reconnectIntervalMs}
onChange={(v) => set({ reconnectIntervalMs: Number(v) || undefined })}
/>
<div className="flex flex-col gap-2">
<div className="grid gap-3 sm:grid-cols-[1fr_160px_160px]">
<Field
label="目标 URL"
type="url"
placeholder="ws://..."
value={it.url}
onChange={(v) => set({ url: v })}
/>
<Field
label="重连间隔 (ms)"
type="number"
value={it.reconnectIntervalMs}
onChange={(v) => set({ reconnectIntervalMs: Number(v) || undefined })}
/>
</div>
{maxPayloadField(it.maxPayloadBytes, set)}
</div>
);
}
@@ -444,6 +454,40 @@ function KindFields<K extends NetworkKind>({ kind, draft, patch }: KindFieldsPro
return null;
}
/**
* Inbound WebSocket frame cap. Shared by every editor that owns a WebSocket
* transport (wsServers, wsClients, httpServers with the embedded listener): the
* value is empty by default (transport default of 100 MiB), and the hint spells
* out why inline PCM audio hits it at ~7:26.
*/
function maxPayloadField(
value: number | undefined,
set: (patch: { maxPayloadBytes?: number }) => void,
) {
return (
<div className="flex flex-col gap-2">
<div className="grid gap-3 sm:grid-cols-[160px_1fr] sm:items-end">
<Field
label="单帧上限 (bytes)"
type="number"
min={1024}
max={2147483648}
step={1024}
placeholder="104857600"
value={value}
onChange={(v) => set({ maxPayloadBytes: Number(v) || undefined })}
/>
</div>
<p className="text-xs leading-relaxed text-muted-foreground">
入站 WebSocket 单帧上限,留空即默认 100 MiB(104857600),有效范围 1024 –
2147483648。44.1 kHz 立体声 PCM 语音约 445
秒(7:26)就会触顶并断开连接;超长音频应由上游改发 URL/文件或压缩为
SILK,调大上限会按帧大小增加内存占用。
</p>
</div>
);
}
// ─────────────── shared form bits ───────────────
interface FieldProps {
@@ -452,10 +496,23 @@ interface FieldProps {
onChange: (v: string) => void;
placeholder?: string;
type?: 'text' | 'number' | 'url';
min?: number;
max?: number;
step?: number;
error?: string;
}
function Field({ label, value, onChange, placeholder, type = 'text', error }: FieldProps) {
function Field({
label,
value,
onChange,
placeholder,
type = 'text',
min,
max,
step,
error,
}: FieldProps) {
return (
<div className="flex flex-col gap-1.5">
<Label>{label}</Label>
@@ -464,6 +521,9 @@ function Field({ label, value, onChange, placeholder, type = 'text', error }: Fi
value={value ?? ''}
onChange={(e) => onChange(e.target.value)}
placeholder={placeholder}
min={min}
max={max}
step={step}
className={cn(error && 'border-destructive focus-visible:ring-destructive/40')}
/>
{error && <p className="text-xs text-destructive">{error}</p>}
+9 -3
View File
@@ -109,7 +109,13 @@ interface NetworkBase {
reportSelfMessage: boolean;
}
export interface HttpServerNetwork extends NetworkBase {
/** Mirrors the server's WsFrameLimitConfig: only adapters with a WS transport. */
interface WsFrameLimitConfig {
/** Inbound WebSocket frame cap in bytes; omitted means the 100 MiB default. */
maxPayloadBytes?: number;
}
export interface HttpServerNetwork extends NetworkBase, WsFrameLimitConfig {
host?: string;
port: number;
path?: string;
@@ -121,14 +127,14 @@ export interface HttpClientNetwork extends NetworkBase {
timeoutMs?: number;
}
export interface WsServerNetwork extends NetworkBase {
export interface WsServerNetwork extends NetworkBase, WsFrameLimitConfig {
host?: string;
port: number;
path?: string;
role?: WsRole;
}
export interface WsClientNetwork extends NetworkBase {
export interface WsClientNetwork extends NetworkBase, WsFrameLimitConfig {
url: string;
role?: WsRole;
reconnectIntervalMs?: number;