fix(onebot): support standard forward WebSocket routes
Accept the standard action, event, and universal paths when a forward WebSocket server listens at the root endpoint. Keep authentication, custom endpoints, embedded listeners, and rejected-path reporting compatible while assigning each accepted connection the correct role. Add real-listener regression coverage for standard paths, trailing slashes, query authentication, invalid paths, and existing lifecycle behavior. Fixes #317
This commit is contained in:
5 files changed
+386
-19
No files matched your search
@@ -131,9 +131,6 @@ export function normalizePath(pathValue: string | undefined): string {
|
||||
}
|
||||
|
||||
export function parseRequestPath(urlValue: string): string {
|
||||
try {
|
||||
return new URL(urlValue, 'ws://127.0.0.1').pathname;
|
||||
} catch {
|
||||
return '/';
|
||||
}
|
||||
const queryIndex = urlValue.indexOf('?');
|
||||
return queryIndex === -1 ? urlValue : urlValue.slice(0, queryIndex);
|
||||
}
|
||||
@@ -4,8 +4,11 @@ import type { IncomingMessage } from 'node:http';
|
||||
import type { DispatchPayload } from '../event-filter';
|
||||
import type { JsonObject, WsServerNetwork } from '../types';
|
||||
import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter';
|
||||
import { normalizePath } from './utils';
|
||||
import { WsServerConnections } from './ws-server-connections';
|
||||
import { normalizePath, parseRequestPath } from './utils';
|
||||
import {
|
||||
WsServerConnections,
|
||||
type WsServerConnectionConfig,
|
||||
} from './ws-server-connections';
|
||||
|
||||
const moduleLog = createLogger('OneBot.WS-Server');
|
||||
|
||||
@@ -17,7 +20,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
|
||||
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx, moduleLog);
|
||||
this.connections = new WsServerConnections(name, config, ctx, this.log, {
|
||||
this.connections = new WsServerConnections(name, standaloneConnectionConfig(config), ctx, this.log, {
|
||||
frame: (event, options) => this.metaFrame(event, options),
|
||||
bootstrap: (options) => this.bootstrapMetaFrames(options),
|
||||
});
|
||||
@@ -90,7 +93,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
}
|
||||
|
||||
protected override onConfigReplaced(next: WsServerNetwork): void {
|
||||
this.connections.updateConfig(next);
|
||||
this.connections.updateConfig(standaloneConnectionConfig(next));
|
||||
}
|
||||
|
||||
onEvent(_event: JsonObject, payload: DispatchPayload): void {
|
||||
@@ -105,9 +108,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
wss = new WebSocketServer({
|
||||
host: this.config.host ?? '0.0.0.0',
|
||||
port: this.config.port,
|
||||
path: normalizePath(this.config.path),
|
||||
verifyClient: ({ req }: { req: IncomingMessage }) =>
|
||||
this.connections.authorizeUpgrade(req),
|
||||
verifyClient: (
|
||||
{ req }: { req: IncomingMessage },
|
||||
done: (allow: boolean, code?: number, message?: string) => void,
|
||||
) => {
|
||||
const requestPath = parseRequestPath(req.url ?? '/');
|
||||
if (!this.connections.acceptsUpgradePath(requestPath)) {
|
||||
this.log.debug('[%s] rejected unknown WebSocket path %s', this.name, requestPath);
|
||||
done(false, 400, 'Bad path for WebSocket');
|
||||
return;
|
||||
}
|
||||
if (!this.connections.authorizeUpgrade(req)) {
|
||||
done(false, 401, 'Unauthorized');
|
||||
return;
|
||||
}
|
||||
done(true);
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
this.recordTransportFailure(error);
|
||||
@@ -170,3 +186,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
function isAlreadyClosedError(error: Error): boolean {
|
||||
return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING';
|
||||
}
|
||||
|
||||
function standaloneConnectionConfig(config: WsServerNetwork): WsServerConnectionConfig {
|
||||
return { ...config, role: config.role ?? 'Universal' };
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import type { JsonObject, NetworkBase, WsRole } from '../types';
|
||||
import type { NetworkAdapterContext } from './adapter';
|
||||
import {
|
||||
isAuthorized,
|
||||
normalizePath,
|
||||
parseRequestPath,
|
||||
rawDataToString,
|
||||
safeClose,
|
||||
@@ -27,7 +28,7 @@ const HEARTBEAT_INTERVAL_MS = 30_000;
|
||||
const HEARTBEAT_MAX_MISSED = 2;
|
||||
const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000;
|
||||
|
||||
export type WsServerConnectionConfig = NetworkBase & { role?: WsRole };
|
||||
export type WsServerConnectionConfig = NetworkBase & { path?: string; role?: WsRole };
|
||||
|
||||
interface ForwardConnection {
|
||||
socket: WebSocket;
|
||||
@@ -100,6 +101,10 @@ export class WsServerConnections {
|
||||
if (tokenChanged) this.disconnectAll(1008, 'access token changed');
|
||||
}
|
||||
|
||||
acceptsUpgradePath(requestPath: string): boolean {
|
||||
return resolveForwardRole(requestPath, this.config) !== null;
|
||||
}
|
||||
|
||||
onEvent(payload: DispatchPayload): void {
|
||||
if (!this.acceptingActions || this.connections.size === 0) return;
|
||||
for (const connection of this.connections.values()) {
|
||||
@@ -128,7 +133,13 @@ export class WsServerConnections {
|
||||
return;
|
||||
}
|
||||
|
||||
const role = this.config.role ?? classifyForwardRole(request);
|
||||
const requestPath = parseRequestPath(request.url ?? '/');
|
||||
const role = resolveForwardRole(requestPath, this.config);
|
||||
if (role === null) {
|
||||
this.log.warn('[%s] rejected WebSocket path after upgrade', this.name);
|
||||
safeClose(socket, 1008, 'invalid path');
|
||||
return;
|
||||
}
|
||||
const stopHeartbeat = startHeartbeat(
|
||||
socket,
|
||||
{ intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED },
|
||||
@@ -252,8 +263,24 @@ export class WsServerConnections {
|
||||
}
|
||||
}
|
||||
|
||||
function classifyForwardRole(request: IncomingMessage): WsRole {
|
||||
const path = parseRequestPath(request.url ?? '/');
|
||||
function resolveForwardRole(requestPath: string, config: WsServerConnectionConfig): WsRole | null {
|
||||
if (
|
||||
config.role !== undefined
|
||||
&& (!requestPath.startsWith('/') || requestPath.startsWith('//'))
|
||||
) return null;
|
||||
|
||||
const path = normalizePath(requestPath);
|
||||
if (config.role === undefined) return classifyForwardRole(path);
|
||||
|
||||
const basePath = normalizePath(config.path);
|
||||
if (path === basePath) return config.role;
|
||||
if (config.role !== 'Universal' || basePath !== '/') return null;
|
||||
if (path === '/api') return 'Api';
|
||||
if (path === '/event') return 'Event';
|
||||
return null;
|
||||
}
|
||||
|
||||
function classifyForwardRole(path: string): WsRole {
|
||||
if (path.endsWith('/api')) return 'Api';
|
||||
if (path.endsWith('/event')) return 'Event';
|
||||
return 'Universal';
|
||||
|
||||
@@ -8,7 +8,10 @@ const { FakeWebSocketServer, servers } = vi.hoisted(() => {
|
||||
class FakeWebSocketServer extends EventEmitter {
|
||||
closeCallback: ((error?: Error) => void) | null = null;
|
||||
readonly options: {
|
||||
verifyClient?: (info: { req: { headers: Record<string, string>; url?: string } }) => boolean;
|
||||
verifyClient?: (
|
||||
info: { req: { headers: Record<string, string>; url?: string } },
|
||||
done: (allow: boolean, code?: number, message?: string) => void,
|
||||
) => void;
|
||||
};
|
||||
constructor(options: unknown) {
|
||||
super();
|
||||
@@ -86,8 +89,13 @@ describe('WsServerAdapter bind/release lifecycle promises', () => {
|
||||
const verify = servers[0].options.verifyClient;
|
||||
|
||||
expect(verify).toBeTypeOf('function');
|
||||
expect(verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } })).toBe(false);
|
||||
expect(verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } })).toBe(true);
|
||||
const denied = vi.fn();
|
||||
verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } }, denied);
|
||||
expect(denied).toHaveBeenCalledWith(false, 401, 'Unauthorized');
|
||||
|
||||
const accepted = vi.fn();
|
||||
verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } }, accepted);
|
||||
expect(accepted).toHaveBeenCalledWith(true);
|
||||
});
|
||||
|
||||
it('rejects bind errors and exposes them as degraded', async () => {
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { getLogLevel, getRecentLogs, setLogLevel } from '@snowluma/common/logger';
|
||||
import { WebSocket, type WebSocketServer } from '@snowluma/websocket';
|
||||
import { buildDispatchPayload } from '../src/event-filter';
|
||||
import { WsServerAdapter } from '../src/network/ws-server-adapter';
|
||||
import type { NetworkAdapterContext } from '../src/network/adapter';
|
||||
import type { JsonObject, WsServerNetwork } from '../src/types';
|
||||
|
||||
function waitForOpen(socket: WebSocket): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('open', resolve);
|
||||
socket.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForMessage(socket: WebSocket): Promise<JsonObject> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('message', (raw: Buffer) => {
|
||||
try {
|
||||
resolve(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
socket.once('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForHandshakeError(socket: WebSocket): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
socket.once('open', () => reject(new Error('unexpected WebSocket upgrade')));
|
||||
socket.once('error', (error: Error) => resolve(error.message));
|
||||
});
|
||||
}
|
||||
|
||||
function context(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
api: {
|
||||
isAcceptingActions: true,
|
||||
processStreamRequest: vi.fn(async (text: string, send: (frame: string) => Promise<void>) => {
|
||||
const request = JSON.parse(text) as { echo?: unknown };
|
||||
await send(JSON.stringify({
|
||||
status: 'ok',
|
||||
retcode: 0,
|
||||
data: { transport: 'websocket' },
|
||||
echo: request.echo,
|
||||
}));
|
||||
}),
|
||||
} as never,
|
||||
buildLifecycleEvent: (subType) => ({
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: subType,
|
||||
}),
|
||||
buildHeartbeatEvent: () => ({
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'heartbeat',
|
||||
interval: 5000,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function config(): WsServerNetwork {
|
||||
return {
|
||||
name: 'ws-routing',
|
||||
host: '127.0.0.1',
|
||||
port: 0,
|
||||
path: '/',
|
||||
role: 'Universal',
|
||||
messageFormat: 'array',
|
||||
reportSelfMessage: false,
|
||||
};
|
||||
}
|
||||
|
||||
describe('WsServerAdapter — OneBot forward WebSocket routes', () => {
|
||||
let adapter: WsServerAdapter | null = null;
|
||||
let socket: WebSocket | null = null;
|
||||
|
||||
afterEach(async () => {
|
||||
await adapter?.close();
|
||||
adapter = null;
|
||||
socket?.terminate();
|
||||
socket = null;
|
||||
});
|
||||
|
||||
it('serves actions without event frames on /api', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'api-route' }));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'api-route')).toBe(true);
|
||||
});
|
||||
expect(frames.filter((frame) => frame.post_type === 'meta_event')).toEqual([]);
|
||||
});
|
||||
|
||||
it('accepts the standard trailing slash on /api/', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
const frames: JsonObject[] = [];
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api/`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'api-slash' }));
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'api-slash')).toBe(true);
|
||||
});
|
||||
expect(frames.filter((frame) => frame.post_type === 'meta_event')).toEqual([]);
|
||||
});
|
||||
|
||||
it('pushes events without accepting actions on /event', async () => {
|
||||
const ctx = context();
|
||||
const api = ctx.api as unknown as { processStreamRequest: ReturnType<typeof vi.fn> };
|
||||
adapter = new WsServerAdapter('ws-routing', config(), ctx);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/event`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.map((frame) => frame.meta_event_type)).toEqual([
|
||||
'lifecycle',
|
||||
'lifecycle',
|
||||
'heartbeat',
|
||||
]);
|
||||
});
|
||||
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'event-route' }));
|
||||
await new Promise((resolve) => setImmediate(resolve));
|
||||
expect(api.processStreamRequest).not.toHaveBeenCalled();
|
||||
|
||||
const event = { post_type: 'notice', notice_type: 'test' };
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.at(-1)).toEqual(event);
|
||||
});
|
||||
});
|
||||
|
||||
it('accepts the standard trailing slash on /event/', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/event/`);
|
||||
const firstFrame = waitForMessage(socket);
|
||||
await waitForOpen(socket);
|
||||
|
||||
await expect(firstFrame).resolves.toMatchObject({
|
||||
post_type: 'meta_event',
|
||||
meta_event_type: 'lifecycle',
|
||||
sub_type: 'connect',
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps / bidirectional', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
await vi.waitFor(() => {
|
||||
expect(frames).toHaveLength(3);
|
||||
});
|
||||
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'universal-route' }));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'universal-route')).toBe(true);
|
||||
});
|
||||
|
||||
const event = { post_type: 'notice', notice_type: 'universal-test' };
|
||||
adapter.onEvent(event, buildDispatchPayload(event));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.at(-1)).toEqual(event);
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects paths outside the configured OneBot endpoints', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/unknown`);
|
||||
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
});
|
||||
|
||||
it('does not include query-string credentials in rejected-path logs', async () => {
|
||||
const previousLevel = getLogLevel();
|
||||
setLogLevel('debug');
|
||||
try {
|
||||
adapter = new WsServerAdapter(
|
||||
'ws-routing',
|
||||
{ ...config(), accessToken: 'expected-secret' },
|
||||
context(),
|
||||
);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(
|
||||
`ws://127.0.0.1:${String(address.port)}/unknown?access_token=log-secret`,
|
||||
);
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
|
||||
const rejection = getRecentLogs(20).find((entry) =>
|
||||
entry.scope === 'OneBot.WS-Server'
|
||||
&& entry.message.includes('rejected unknown WebSocket path /unknown'));
|
||||
expect(rejection).toBeDefined();
|
||||
expect(rejection?.message).not.toContain('log-secret');
|
||||
} finally {
|
||||
setLogLevel(previousLevel);
|
||||
}
|
||||
});
|
||||
|
||||
it('does not normalize a protocol-relative path into the root endpoint', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}//unknown`);
|
||||
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
});
|
||||
|
||||
it('does not normalize a double-slash path into the root endpoint', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', config(), context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}//`);
|
||||
|
||||
await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400');
|
||||
});
|
||||
|
||||
it('accepts standard routes with query-string authentication', async () => {
|
||||
adapter = new WsServerAdapter(
|
||||
'ws-routing',
|
||||
{ ...config(), accessToken: 'query-secret' },
|
||||
context(),
|
||||
);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(
|
||||
`ws://127.0.0.1:${String(address.port)}/api?access_token=query-secret`,
|
||||
);
|
||||
|
||||
await expect(waitForOpen(socket)).resolves.toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats an omitted standalone role as Universal', async () => {
|
||||
adapter = new WsServerAdapter(
|
||||
'ws-routing',
|
||||
{ ...config(), role: undefined },
|
||||
context(),
|
||||
);
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
await waitForOpen(socket);
|
||||
const response = waitForMessage(socket);
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'default-role' }));
|
||||
|
||||
await expect(response).resolves.toMatchObject({ echo: 'default-role' });
|
||||
});
|
||||
|
||||
it('keeps a non-root configured Universal endpoint bidirectional', async () => {
|
||||
adapter = new WsServerAdapter('ws-routing', { ...config(), path: '/api' }, context());
|
||||
await adapter.open();
|
||||
const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo;
|
||||
const frames: JsonObject[] = [];
|
||||
|
||||
socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`);
|
||||
socket.on('message', (raw: Buffer) => {
|
||||
frames.push(JSON.parse(raw.toString('utf8')) as JsonObject);
|
||||
});
|
||||
await waitForOpen(socket);
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.map((frame) => frame.meta_event_type)).toEqual([
|
||||
'lifecycle',
|
||||
'lifecycle',
|
||||
'heartbeat',
|
||||
]);
|
||||
});
|
||||
|
||||
socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'custom-universal' }));
|
||||
await vi.waitFor(() => {
|
||||
expect(frames.some((frame) => frame.echo === 'custom-universal')).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user