refactor(onebot): extract OneBot protocol translation into @snowluma/onebot

Phase 3 of the 4-package split (RoadMap #3). Moves the entire
`packages/core/src/onebot/` subtree (43 source files + 20 test files
spanning network adapters, action handlers, event converters, message
parser, message store, media store, instance + manager) into the new
`@snowluma/onebot` workspace package. The remaining `@snowluma/core`
now hosts only the api-layer (Bridge class + 13 Api classes), the
hook tooling, the WebUI server, and the runnable `index.ts`.

Why
---
- The OneBot adapter is the public-facing OneBot11 protocol surface;
  it has its own version cadence and its own consumers (third-party
  bots talking OneBot WS / HTTP). Splitting it lets that cadence move
  independently of the Api-on-ctx layer.
- The two were sharing the `packages/core/` build pipeline only
  because they happened to live in the same directory. Nothing in
  the api-layer reaches into OneBot internals.
- Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter
  is a separate assembly from the Core protocol library).

Layout
------
Moved via `git mv` (history preserved):
  packages/core/src/onebot/*  → @snowluma/onebot/src/<x>
  packages/core/tests/onebot/* (6 files)   → @snowluma/onebot/tests/
  packages/core/tests/{message-parser,message-store,event-pipeline,
    media-store,media-url-resolver,event-converter,
    http-server-hot-reload,http-server-content-type,
    api-handler-logging,message-id,group-msg-emoji-like,
    config,media-indexer,network-manager}.test.ts (14 files)
                                              → @snowluma/onebot/tests/

What stays in @snowluma/core
----------------------------
- `bridge/{bridge,bridge-interface,bridge-context,manager}.ts`
- `bridge/apis/*` (the 13 typed Api classes)
- `hook/*` (debugger/injector — tooling for the core protocol layer)
- `webui/*` (admin UI server — application wiring, not the OneBot
  adapter itself)
- `index.ts` (application entry that wires BridgeManager +
  OneBotManager + HookManager + WebUI together)

Changes
-------
- New package `packages/onebot/` (package.json with subpath exports
  mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json,
  vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action-
  dispatch logging tests see debug-level subscribers — copied verbatim
  from core's vitest.config.ts).
- @snowluma/core grows new subpath exports for the api-layer files
  OneBot's type-only imports need: `./bridge`, `./bridge-interface`,
  `./bridge-context`, `./manager`, `./apis`.
- `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`,
  `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`,
  `@snowluma/websocket`.
- `@snowluma/core` depends on `@snowluma/onebot` (for index.ts +
  webui/server.ts wiring).
- 100+ import sites rewritten via sed:
  * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`,
    `'../bridge/manager'` → `'@snowluma/core/manager'`,
    `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`,
    `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`.
  * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`,
    `'../onebot/config'` → `'@snowluma/onebot/config'`, etc.
  * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'`
    after the test file move (one level shallower).
- New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and
  `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads).

Workspace cycle
---------------
core ↔ onebot is allowed by pnpm workspaces. The runtime direction
is one-way: core → onebot (index.ts constructs OneBotManager,
webui/server reads OneBot config). OneBot only reaches into core for
TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo,
DownloadRKeyInfo); those imports use `import type` so they compile
out at runtime and don't introduce a real cycle.

Verification
------------
- Full workspace `pnpm -r typecheck`: all 11 projects clean.
- `@snowluma/core` test suite: 302/302 pass (33 test files).
- `@snowluma/onebot` test suite: 250/250 pass (20 test files;
  pre-existing `network-manager.test.ts` native-addon failure
  unchanged — same baseline as before the split).
- Combined: 552/552 — identical pass count to the pre-Phase-3
  baseline.
- Vite build with stubbed native binary: clean, 2.84 MB bundle /
  224 KB gzip (identical envelope).
This commit is contained in:
DrSmoothl committed 2026-05-21 08:52:00 +08:00
1 parent f7a03ca05a
commit 9a30df9907
71 files changed
+286 -59

No files matched your search

+56
View File
@@ -0,0 +1,56 @@
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
export interface NetworkAdapterContext {
/** Self UIN as string — written into outbound headers. */
uin: string;
/** Shared API dispatcher used by request/response style adapters. */
api: ApiHandler;
/** Build a lifecycle event payload (connect/enable/disable). */
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
/** Build a heartbeat event payload. */
buildHeartbeatEvent(): JsonObject;
}
export enum NetworkReloadType {
/** Configuration unchanged or only soft fields updated. */
Normal = 0,
/** Underlying socket/listener restarted in place. */
Reopened = 1,
/** Was running, now closed. */
Closed = 2,
/** Was idle, now opened. */
Opened = 3,
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
this.name = name;
// Defensive copy so reload diffs never mutate the caller's object.
this.config = structuredClone(config);
this.ctx = ctx;
}
/** Whether the adapter is currently accepting/relaying events. */
get isActive(): boolean { return this.isEnabled; }
/** Snapshot of the active config (read-only). */
get currentConfig(): Readonly<C> { return this.config; }
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
/**
* Receive one fully-shaped OneBot event for forwarding. Adapters that
* don't push events (e.g. HTTP request-response servers) override with a
* no-op.
*/
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
}
@@ -0,0 +1,136 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private readonly log: Logger;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.isEnabled = true;
}
close(): void {
this.isEnabled = false;
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
void this.postEvent(json, event).catch((err) => {
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
private async postEvent(payload: string, event: JsonObject): Promise<void> {
if (!this.isEnabled) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (this.config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
}
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(this.config.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
if (response.ok) {
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
}
} else {
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
}
} catch (error) {
if (this.isEnabled) {
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.ctx.api);
} catch (error) {
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
}
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}
@@ -0,0 +1,260 @@
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private readonly log: Logger;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
// HTTP server never receives events — `isActive` purely tracks the
// bound listener so the network manager can skip dispatch cleanly.
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && !this.server) return;
this.isEnabled = false;
this.server?.close();
this.server = null;
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
// HTTP server only acts on inbound requests; it doesn't push events.
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const server = createServer((req, res) => {
void this.handleRequest(req, res);
});
this.server = server;
server.on('listening', () => {
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
normalizePath(this.config.path ?? '/'),
);
});
server.on('error', (err) => {
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
}
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
// Read `path` + `accessToken` fresh from `this.config` on every
// request so config hot-reloads (`reload()` overwrites `this.config`
// in place) take effect on the very next request without
// re-binding the listener. Matches the ws-server / http-post /
// ws-client adapters, which all read `this.config.accessToken`
// inline at the point of use.
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
let action = '';
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
action = '';
} else if (incomingPath.startsWith(ep)) {
action = incomingPath.substring(ep.length);
} else {
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
return;
}
if (!isAuthorized(req, accessToken)) {
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (req.method === 'GET' && !action) {
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
return;
}
try {
let params: Record<string, unknown> = {};
let echo: unknown;
if (req.method === 'GET') {
parsedUrl.searchParams.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
} else if (req.method === 'POST') {
const bodyContent = await readRequestBody(req);
if (bodyContent.trim()) {
const contentType = req.headers['content-type'] ?? '';
if (contentType.includes('application/x-www-form-urlencoded')) {
const parsed = new URLSearchParams(bodyContent);
parsed.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
if (params.action && !action) {
action = String(params.action);
delete params.action;
}
if (params.echo !== undefined) {
echo = params.echo;
delete params.echo;
}
} else if (contentType.includes('application/json') || !contentType) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
if (parsedBody.action && !action) action = String(parsedBody.action);
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
}
echo = parsedBody.echo;
}
} catch {
if (contentType.includes('application/json')) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
// 无 content-type,JSON 失败则 fallback 到 urlencoded
const parsed = new URLSearchParams(bodyContent);
parsed.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
if (params.action && !action) {
action = String(params.action);
delete params.action;
}
if (params.echo !== undefined) {
echo = params.echo;
delete params.echo;
}
}
} else {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
return;
}
}
} else {
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
return;
}
if (!action) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
return;
}
const response = await this.ctx.api.handle(action, params as JsonObject);
if (echo !== undefined) {
response.echo = echo as JsonValue;
}
writeJson(res, 200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
}
function bindingSignature(net: HttpServerNetwork): string {
// `accessToken` deliberately omitted: it's read per-request from
// `this.config`, so a token change doesn't need to re-bind the
// listener. Including it here would cause a `close()` + `listen()`
// round trip on every token edit — a needless port-rebind that, on
// some hosts, races with the OS releasing the port and lands the
// server in a half-broken state where the old token still
// authenticates because the EADDRINUSE-failing new server never
// replaced the old one. `host`/`port`/`path` still gate a restart
// because Node's HTTP `Server.listen()` binds the socket on those.
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
+8
View File
@@ -0,0 +1,8 @@
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { OneBotNetworkManager } from './network-manager';
export { executeQuickOperation } from './quick-operation';
export { WsClientAdapter } from './ws-client-adapter';
export { WsServerAdapter } from './ws-server-adapter';
@@ -0,0 +1,99 @@
import { createLogger } from '@snowluma/common/logger';
import { buildDispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
import { IOneBotNetworkAdapter } from './adapter';
const log = createLogger('OneBot.Network');
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
export class OneBotNetworkManager {
private readonly adapters = new Map<string, AnyAdapter>();
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
const existing = this.adapters.get(adapter.name);
if (existing) {
// Replacing an adapter under the same name — close the previous one
// before storing the new instance to keep ports/sockets clean.
log.info('replacing adapter [%s]', adapter.name);
void Promise.resolve(existing.close()).catch(() => { /* best-effort */ });
}
this.adapters.set(adapter.name, adapter as AnyAdapter);
}
has(name: string): boolean { return this.adapters.has(name); }
get(name: string): AnyAdapter | null {
return this.adapters.get(name) ?? null;
}
list(): AnyAdapter[] { return [...this.adapters.values()]; }
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
return false;
}
async openAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.open();
} catch (err) {
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
}
async closeAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
this.adapters.clear();
}
async closeOne(name: string): Promise<void> {
const adapter = this.adapters.get(name);
if (!adapter) return;
this.adapters.delete(name);
try {
await adapter.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
}
}
/**
* Dispatch one canonical OneBot event to every active adapter in parallel.
* The dispatch payload is built once so each adapter pays only the cost
* of picking the right pre-serialized variant.
*
* Errors thrown inside an adapter are isolated — one bad adapter never
* blocks the others.
*/
async emitEvent(event: JsonObject): Promise<void> {
if (!this.hasActiveAdapters()) return;
const payload = buildDispatchPayload(event);
const tasks: Promise<unknown>[] = [];
for (const adapter of this.adapters.values()) {
if (!adapter.isActive) continue;
tasks.push(
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((err) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
}),
);
}
await Promise.allSettled(tasks);
}
}
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
@@ -0,0 +1,82 @@
import type { ApiHandler } from '../api-handler';
import type { JsonObject, JsonValue } from '../types';
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
if (postType === 'message') {
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
};
if (operation.at_sender !== false && event.user_id) {
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
});
}
}
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as JsonValue,
});
}
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as JsonValue,
remark: (operation.remark ?? '') as JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as JsonValue,
reason: (operation.reason ?? '') as JsonValue,
});
}
}
}
}
+56
View File
@@ -0,0 +1,56 @@
import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) return true;
} catch { /* ignore malformed URLs */ }
return false;
}
/** Convert anything ws can hand us into a UTF-8 string. */
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
if (typeof raw === 'string') return raw;
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
socket.send(payload, (error?: Error | null) => {
if (error && onError) onError(error);
});
}
/** Best-effort close, treats already-closed sockets as a no-op. */
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
}
/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */
export function normalizePath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */
export function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'ws://127.0.0.1').pathname;
} catch {
return '/';
}
}
@@ -0,0 +1,176 @@
import { WebSocket } from '@snowluma/websocket';
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
private readonly log: Logger;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.explicitlyClosed = false;
this.isEnabled = true;
this.connect();
}
close(): void {
this.explicitlyClosed = true;
this.isEnabled = false;
this.cancelReconnect();
if (this.socket) {
safeClose(this.socket);
this.socket = null;
}
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || !this.socket) return;
if (this.role !== 'Event' && this.role !== 'Universal') return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
safeSend(this.socket, json);
}
private connect(): void {
if (this.explicitlyClosed) return;
if (!this.config.url) return;
if (this.socket) return;
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.ctx.uin,
'X-Client-Role': this.role,
};
if (this.config.accessToken) {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
socket.on('open', () => {
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
});
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, raw).catch((err) => {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
});
socket.on('close', () => {
this.socket = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
socket.on('error', (err: Error) => {
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
});
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
if (this.explicitlyClosed) return;
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.connect();
}, interval);
timer.unref?.();
this.reconnectTimer = timer;
}
private cancelReconnect(): void {
if (!this.reconnectTimer) return;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
if (this.role !== 'Api' && this.role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
if (this.role !== 'Event' && this.role !== 'Universal') return;
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}
@@ -0,0 +1,184 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
interface ForwardConn {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
}
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
// Final lifecycle broadcast before tearing down so attached event clients
// see the disable transition.
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const conn of this.connections.values()) {
if (conn.role === 'Api') continue;
const shaped = shapeEventForAdapter(lifecycle, conn.options);
if (!shaped) continue;
safeSend(conn.socket, JSON.stringify(shaped));
}
this.isEnabled = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
this.connections.clear();
this.wss?.close();
this.wss = null;
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || this.connections.size === 0) return;
for (const conn of this.connections.values()) {
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
const json = pickDispatchJson(payload, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
}
private startServer(): void {
const wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: this.config.path ?? '/',
});
this.wss = wss;
wss.on('listening', () => {
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
});
wss.on('error', (err: Error) => {
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
}
private onConnection(socket: WebSocket, request: IncomingMessage): void {
if (!isAuthorized(request, this.config.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = this.config.role ?? classifyForwardRole(request);
const conn: ForwardConn = { socket, role, options: this.options };
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => this.connections.delete(socket));
socket.on('error', (err: Error) => {
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
});
if (role === 'Event' || role === 'Universal') {
this.sendBootstrapMetaEvents(socket);
}
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'Api';
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}