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:
1 parent
bd40ac3522
commit
8d9f44b6b0
16 files changed
+1035
-77
No files matched your search
@@ -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),
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user