Refactor OneBot networks and event dispatch

Unify per-adapter network configuration into a single `networks` structure and add migration/normalization for legacy on-disk formats. Introduce per-adapter options (messageFormat, reportSelfMessage, enabled, name) and stronger typing in types.ts. Add event-filter utilities to prebuild two serialized payload variants and pick the right one per adapter to avoid repeated JSON.stringify calls. Update HTTP/WS transports to use adapter names/signatures for hot-reload, respect per-adapter options, and improve logging; WS transport also improves client/server lifecycle/reconnect handling. Mark self-sent messages as `message_sent` in the event converter and wire instance dispatch to use the new DispatchPayload. Misc: README edits and accompanying tests added/updated for the refactor.
This commit is contained in:
手瓜一十雪 committed 2026-05-07 16:01:28 +08:00
1 parent 19a564991c
commit 2a4ca46a99
14 files changed
+1732 -758

No files matched your search

+267 -179
View File
@@ -1,92 +1,76 @@
import fs from 'fs';
import path from 'path';
import { randomBytes } from 'crypto';
import type {
HttpPostEndpoint,
HttpServerEndpoint,
HttpClientNetwork,
HttpServerNetwork,
JsonObject,
MessageFormat,
OneBotConfig,
WsClientEndpoint,
OneBotNetworks,
WsClientNetwork,
WsRole,
WsServerEndpoint,
WsServerNetwork,
} from './types';
const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
export function makeDefaultOneBotConfig(): OneBotConfig {
return {
httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }],
httpPostEndpoints: [],
wsServers: [{ host: '0.0.0.0', port: 3001 }],
wsClients: [],
networks: {
httpServers: [{
name: 'http-default',
host: '0.0.0.0',
port: 3000,
path: '/',
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}],
httpClients: [],
wsServers: [{
name: 'ws-default',
host: '0.0.0.0',
port: 3001,
path: '/',
role: 'universal',
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}],
wsClients: [],
},
musicSignUrl: '',
};
}
function generateAccessToken(): string {
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
}
export function loadOneBotConfig(uin: string): OneBotConfig {
ensureConfigDir();
const merged = deepClone(toJsonObject(makeDefaultOneBotConfig()));
const globalConfig = tryLoadJson(DEFAULT_CONFIG_PATH);
if (globalConfig) {
deepMerge(merged, globalConfig);
}
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
const perUinConfig = tryLoadJson(perUinPath);
if (perUinConfig) {
deepMerge(merged, perUinConfig);
}
const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH);
const perUinRaw = tryLoadJson(perUinPath);
const config = fromJson(merged);
let shouldSave = !perUinConfig;
// Detect legacy on-disk format (top-level per-type arrays). We auto-migrate
// these entries into `networks.*` and rewrite the file on the next save.
const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw);
// Persist normalized endpoints and generated keys.
merged.httpServers = config.httpServers.map((s) => {
const out: JsonObject = {
host: s.host,
port: s.port,
path: s.path ?? '/',
accessToken: s.accessToken ?? '',
};
if (s.name) out.name = s.name;
return out;
});
merged.httpPostEndpoints = config.httpPostEndpoints.map((e) => {
const out: JsonObject = { url: e.url };
if (e.name) out.name = e.name;
if (e.accessToken) out.accessToken = e.accessToken;
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
return out;
});
merged.wsServers = config.wsServers.map((s) => {
const out: JsonObject = {
host: s.host,
port: s.port,
path: s.path ?? '/',
role: s.role ?? 'universal',
accessToken: s.accessToken ?? '',
};
if (s.name) out.name = s.name;
return out;
});
merged.wsClients = config.wsClients.map((c) => {
const out: JsonObject = {
url: c.url,
role: c.role ?? 'universal',
accessToken: c.accessToken ?? '',
};
if (c.name) out.name = c.name;
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
}
return out;
});
merged.musicSignUrl = config.musicSignUrl ?? '';
const sources: JsonObject[] = [];
if (globalRaw) sources.push(globalRaw);
if (perUinRaw) sources.push(perUinRaw);
if (shouldSave) {
saveJson(perUinPath, merged);
}
const config = fromJson(sources);
// Persist normalized form whenever the file is missing OR was in legacy
// format, so downstream code can rely on the unified shape on disk.
const shouldSave = !perUinRaw || legacy;
if (shouldSave) saveOneBotConfig(uin, config);
return config;
}
@@ -94,8 +78,7 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
ensureConfigDir();
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
const jsonObj = toJsonObject(config);
saveJson(perUinPath, jsonObj);
saveJson(perUinPath, toJsonObject(config));
}
function ensureConfigDir(): void {
@@ -103,136 +86,241 @@ function ensureConfigDir(): void {
}
function toJsonObject(config: OneBotConfig): JsonObject {
const nets = config.networks;
return {
httpServers: config.httpServers.map((s) => {
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', accessToken: s.accessToken ?? '' };
if (s.name) out.name = s.name;
return out;
}),
httpPostEndpoints: config.httpPostEndpoints.map((e) => {
const out: JsonObject = { url: e.url };
if (e.name) out.name = e.name;
if (e.accessToken) out.accessToken = e.accessToken;
if (typeof e.timeoutMs === 'number') out.timeoutMs = e.timeoutMs;
return out;
}),
wsServers: config.wsServers.map((s) => {
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', role: s.role ?? 'universal', accessToken: s.accessToken ?? '' };
if (s.name) out.name = s.name;
return out;
}),
wsClients: config.wsClients.map((c) => {
const out: JsonObject = {
url: c.url,
role: c.role ?? 'universal',
accessToken: c.accessToken ?? '',
};
if (c.name) out.name = c.name;
if (typeof c.reconnectIntervalMs === 'number' && Number.isFinite(c.reconnectIntervalMs)) {
out.reconnectIntervalMs = Math.max(1000, Math.trunc(c.reconnectIntervalMs));
}
return out;
}),
networks: {
httpServers: nets.httpServers.map(httpServerToJson),
httpClients: nets.httpClients.map(httpClientToJson),
wsServers: nets.wsServers.map(wsServerToJson),
wsClients: nets.wsClients.map(wsClientToJson),
},
musicSignUrl: config.musicSignUrl ?? '',
};
}
function fromJson(json: JsonObject): OneBotConfig {
const httpServers = toHttpServers(json.httpServers);
const httpPostEndpoints = toHttpPostEndpoints(json.httpPostEndpoints);
const wsServers = toWsServers(json.wsServers);
const wsClients = toWsClients(json.wsClients);
function applyBase(
out: JsonObject,
n: { name: string; enabled?: boolean; accessToken?: string; messageFormat: MessageFormat; reportSelfMessage: boolean },
): void {
out.name = n.name;
if (n.enabled === false) out.enabled = false;
if (n.accessToken) out.accessToken = n.accessToken;
out.messageFormat = n.messageFormat;
out.reportSelfMessage = n.reportSelfMessage;
}
function httpServerToJson(n: HttpServerNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.host = n.host ?? '0.0.0.0';
out.port = n.port;
out.path = n.path ?? '/';
return out;
}
function httpClientToJson(n: HttpClientNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.url = n.url;
if (typeof n.timeoutMs === 'number' && n.timeoutMs > 0) out.timeoutMs = n.timeoutMs;
return out;
}
function wsServerToJson(n: WsServerNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.host = n.host ?? '0.0.0.0';
out.port = n.port;
out.path = n.path ?? '/';
out.role = n.role ?? 'universal';
return out;
}
function wsClientToJson(n: WsClientNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.url = n.url;
out.role = n.role ?? 'universal';
out.reconnectIntervalMs =
typeof n.reconnectIntervalMs === 'number' && Number.isFinite(n.reconnectIntervalMs)
? Math.max(1000, Math.trunc(n.reconnectIntervalMs))
: 5000;
return out;
}
function fromJson(sources: JsonObject[]): OneBotConfig {
// Legacy top-level scalars are pulled DOWN into each adapter on the first
// load: the on-disk schema has no globals anymore, every adapter is
// self-describing. We compute the legacy fallbacks here so that adapters
// missing `messageFormat`/`reportSelfMessage` inherit them once and the
// file is rewritten in normalized form.
let legacyFormat: MessageFormat | undefined;
let legacyReport: boolean | undefined;
let musicSignUrl = '';
for (const src of sources) {
const mf = parseMessageFormat(src.messageFormat);
if (mf) legacyFormat = mf;
if (typeof src.reportSelfMessage === 'boolean') legacyReport = src.reportSelfMessage;
if (typeof src.musicSignUrl === 'string') musicSignUrl = src.musicSignUrl;
}
const inheritedFormat: MessageFormat = legacyFormat ?? 'array';
const inheritedReport: boolean = legacyReport ?? false;
// Pluck per-type arrays from each source: prefer `networks.<kind>` over
// legacy top-level arrays, but accept both. Later sources override earlier
// ones at the network level (last write wins per `(kind, name)` pair).
const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport };
const httpServers = collectByName<HttpServerNetwork>(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults));
const httpClients = collectByName<HttpClientNetwork>(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints');
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
// Seed defaults if all four arrays are empty (brand-new install).
if (
httpServers.length === 0 &&
httpClients.length === 0 &&
wsServers.length === 0 &&
wsClients.length === 0
) {
const defaults = makeDefaultOneBotConfig().networks;
httpServers.push(...defaults.httpServers);
wsServers.push(...defaults.wsServers);
}
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
return { networks, musicSignUrl };
}
function collectByName<T extends { name: string }>(
sources: JsonObject[],
kind: keyof OneBotNetworks,
parse: (raw: JsonObject) => T | null,
legacyKey?: string,
): T[] {
const byName = new Map<string, T>();
const order: string[] = [];
let counter = 0;
const ingest = (rawArr: unknown): void => {
if (!Array.isArray(rawArr)) return;
for (const raw of rawArr) {
if (!isObject(raw)) continue;
const parsed = parse(raw);
if (!parsed) continue;
const name = parsed.name && parsed.name.trim() ? parsed.name.trim() : pickAutoName(kind, byName, ++counter);
parsed.name = name;
if (!byName.has(name)) order.push(name);
byName.set(name, parsed);
}
};
for (const src of sources) {
const nested = isObject(src.networks) ? (src.networks as JsonObject)[kind] : undefined;
ingest(nested);
if (legacyKey) ingest(src[legacyKey]);
ingest(src[kind]);
}
return order.map((n) => byName.get(n)!);
}
function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string {
const prefix =
kind === 'httpServers' ? 'http' :
kind === 'httpClients' ? 'httppost' :
kind === 'wsServers' ? 'ws' :
'wsclient';
let candidate = `${prefix}-${counter}`;
while (used.has(candidate)) {
counter += 1;
candidate = `${prefix}-${counter}`;
}
return candidate;
}
interface AdapterDefaults {
messageFormat: MessageFormat;
reportSelfMessage: boolean;
}
function parseBase(value: JsonObject, defaults: AdapterDefaults) {
return {
httpServers: httpServers.length > 0 ? httpServers : [{ host: '0.0.0.0', port: 3000, path: '/' }],
httpPostEndpoints,
wsServers: wsServers.length > 0 ? wsServers : [{ host: '0.0.0.0', port: 3001 }],
wsClients,
musicSignUrl: typeof json.musicSignUrl === 'string' ? json.musicSignUrl : '',
name: asString(value.name),
enabled: typeof value.enabled === 'boolean' ? value.enabled : undefined,
accessToken: asString(value.accessToken) || undefined,
messageFormat: parseMessageFormat(value.messageFormat) ?? defaults.messageFormat,
reportSelfMessage:
typeof value.reportSelfMessage === 'boolean' ? value.reportSelfMessage : defaults.reportSelfMessage,
};
}
function toHttpServers(value: unknown): HttpServerEndpoint[] {
if (!Array.isArray(value)) return [];
const result: HttpServerEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const host = asString(item.host, '0.0.0.0');
const port = asNumber(item.port, 3000);
const pathValue = asString(item.path, '/');
const endpoint: HttpServerEndpoint = { host, port, path: pathValue };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
result.push(endpoint);
}
return result;
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
const port = asNumber(value.port, 0);
if (port <= 0) return null;
return clean({
...parseBase(value, defaults),
host: asString(value.host, '0.0.0.0'),
port,
path: asString(value.path, '/'),
});
}
function toHttpPostEndpoints(value: unknown): HttpPostEndpoint[] {
if (!Array.isArray(value)) return [];
const result: HttpPostEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const url = asString(item.url);
if (!url) continue;
const endpoint: HttpPostEndpoint = { url };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
const timeout = asNumber(item.timeoutMs, 0);
if (timeout > 0) endpoint.timeoutMs = timeout;
result.push(endpoint);
}
return result;
function parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClientNetwork | null {
const url = asString(value.url);
if (!url) return null;
const timeout = asNumber(value.timeoutMs, 0);
return clean({
...parseBase(value, defaults),
url,
timeoutMs: timeout > 0 ? timeout : undefined,
});
}
function toWsServers(value: unknown): WsServerEndpoint[] {
if (!Array.isArray(value)) return [];
const result: WsServerEndpoint[] = [];
for (const item of value) {
if (!isObject(item)) continue;
const host = asString(item.host, '0.0.0.0');
const port = asNumber(item.port, 3001);
const pathValue = asString(item.path, '/');
const role = asRole(item.role, 'universal');
const endpoint: WsServerEndpoint = { host, port, path: pathValue, role };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
result.push(endpoint);
}
return result;
function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNetwork | null {
const port = asNumber(value.port, 0);
if (port <= 0) return null;
return clean({
...parseBase(value, defaults),
host: asString(value.host, '0.0.0.0'),
port,
path: asString(value.path, '/'),
role: asRole(value.role, 'universal'),
});
}
function toWsClients(value: unknown): WsClientEndpoint[] {
if (!Array.isArray(value)) return [];
const result: WsClientEndpoint[] = [];
function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNetwork | null {
const url = asString(value.url);
if (!url) return null;
const reconnectIntervalMs = asNumber(value.reconnectIntervalMs, 5000);
return clean({
...parseBase(value, defaults),
url,
role: asRole(value.role, 'universal'),
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
});
}
for (const item of value) {
if (!isObject(item)) continue;
const url = asString(item.url);
if (!url) continue;
const role = asRole(item.role, 'universal');
const reconnectIntervalMs = asNumber(item.reconnectIntervalMs, 5000);
const endpoint: WsClientEndpoint = { url, role, reconnectIntervalMs };
const name = asString(item.name);
if (name) endpoint.name = name;
const token = asString(item.accessToken);
if (token) endpoint.accessToken = token;
result.push(endpoint);
function hasLegacyTopLevel(raw: JsonObject): boolean {
return (
Array.isArray(raw.httpServers) ||
Array.isArray(raw.httpPostEndpoints) ||
Array.isArray(raw.wsServers) ||
Array.isArray(raw.wsClients) ||
typeof raw.messageFormat === 'string' ||
typeof raw.reportSelfMessage === 'boolean'
);
}
function parseMessageFormat(value: unknown): MessageFormat | undefined {
if (value === 'array' || value === 'string') return value;
return undefined;
}
function clean<T extends Record<string, unknown>>(obj: T): T {
for (const key of Object.keys(obj) as (keyof T)[]) {
if (obj[key] === undefined) delete obj[key];
}
return result;
return obj;
}
function asRole(value: unknown, fallback: WsRole): WsRole {
+9 -3
View File
@@ -29,12 +29,14 @@ export class EventConverter {
switch (event.kind) {
case 'friend_message':
{
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
return {
time: event.time,
self_id: selfId,
post_type: 'message',
post_type: postType,
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
@@ -54,12 +56,14 @@ export class EventConverter {
case 'group_message':
{
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
return {
time: event.time,
self_id: selfId,
post_type: 'message',
post_type: postType,
message_type: 'group',
sub_type: 'normal',
message_id: messageId,
@@ -83,12 +87,14 @@ export class EventConverter {
case 'temp_message':
{
const isSelf = event.senderUin === selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = this.resolveMessageId(false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT);
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
return {
time: event.time,
self_id: selfId,
post_type: 'message',
post_type: postType,
message_type: 'private',
sub_type: 'group',
message_id: messageId,
+106
View File
@@ -0,0 +1,106 @@
import type { JsonObject, JsonValue, MessageFormat } from './types';
/**
* Per-adapter view of how an event should be reported.
*
* Built once from each adapter's own configuration at (re)load time so the
* per-publish dispatch loop is just a couple of object lookups.
*/
export interface EventReportOptions {
/** Effective `messageFormat` for this adapter. */
messageFormat: MessageFormat;
/** Whether self-sent messages should be forwarded to this adapter. */
reportSelfMessage: boolean;
}
/**
* Extract the dispatch options from an adapter. Each adapter is fully
* self-describing — there is no global fallback. Defaults are applied here
* only as a safety net for partially-deserialized legacy configs.
*/
export function resolveReportOptions(
network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean },
): EventReportOptions {
return {
messageFormat: network.messageFormat ?? 'array',
reportSelfMessage: network.reportSelfMessage ?? false,
};
}
/**
* Pre-built payload covering every adapter variant of a single canonical event.
*
* The bridge produces one OneBot-shaped event per upstream packet. Because
* adapters only differ in (a) whether they receive `message_sent` self-events
* and (b) whether the `message` field is the segment array or its CQ-string
* form, we serialize the event at most twice up-front and let every adapter
* pick the slot it needs in O(1).
*/
export interface DispatchPayload {
/** True when the canonical event is a self-sent message (`post_type='message_sent'`). */
isSelfMessage: boolean;
/** JSON for adapters using `messageFormat: 'array'` (the canonical event). */
arrayJson: string;
/**
* JSON for adapters using `messageFormat: 'string'`. For non-message events
* this points at the same string as `arrayJson` (no transformation needed).
*/
stringJson: string;
}
/**
* Build the dispatch payload for one canonical OneBot event. Performs at most
* two `JSON.stringify` calls (one per format variant) regardless of how many
* adapters the payload will fan out to.
*/
export function buildDispatchPayload(event: JsonObject): DispatchPayload {
const isSelfMessage = event.post_type === 'message_sent';
const arrayJson = JSON.stringify(event);
let stringJson = arrayJson;
const hasMessage = event.post_type === 'message' || event.post_type === 'message_sent';
if (hasMessage && Array.isArray(event.message)) {
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
stringJson = JSON.stringify({ ...event, message: raw as JsonValue });
}
return { isSelfMessage, arrayJson, stringJson };
}
/**
* Pick the pre-serialized payload variant an adapter should send, or `null`
* when the adapter chose not to receive this event. Hot-path helper: one
* branch + one map lookup per connection, no allocation.
*/
export function pickDispatchJson(
payload: DispatchPayload,
options: EventReportOptions,
): string | null {
if (payload.isSelfMessage && !options.reportSelfMessage) return null;
return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson;
}
/**
* One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson}
* for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't
* worth pre-building a full payload for.
*
* Returns `null` when the adapter shouldn't see this event. Otherwise returns
* the original event untouched, or a shallow clone with `message` rewritten.
*/
export function shapeEventForAdapter(
event: JsonObject,
options: EventReportOptions,
): JsonObject | null {
if (event.post_type === 'message_sent' && !options.reportSelfMessage) return null;
if (options.messageFormat === 'string'
&& (event.post_type === 'message' || event.post_type === 'message_sent')
&& Array.isArray(event.message)
) {
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
return { ...event, message: raw as JsonValue };
}
return event;
}
+54 -21
View File
@@ -1,5 +1,12 @@
import type { JsonObject, OneBotConfig, HttpPostEndpoint } from './types';
import type { HttpClientNetwork, JsonObject, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
import {
buildDispatchPayload,
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from './event-filter';
export interface HttpPostTransportContext {
uin: string;
@@ -9,44 +16,57 @@ export interface HttpPostTransportContext {
const log = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
interface ResolvedClient {
network: HttpClientNetwork;
options: EventReportOptions;
}
export class HttpPostTransport {
private readonly context: HttpPostTransportContext;
private endpoints: HttpPostEndpoint[] = [];
private clients = new Map<string, ResolvedClient>();
private stopped = false;
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
this.endpoints = [...config.httpPostEndpoints];
this.clients = resolveClients(config);
this.context = context;
}
start(): void {
this.stopped = false;
const count = this.endpoints.length;
if (count > 0) {
log.info('configured %d HTTP POST endpoint(s)', count);
if (this.clients.size > 0) {
log.info('configured %d HTTP POST adapter(s): %s', this.clients.size, [...this.clients.keys()].join(', '));
}
}
reloadConfig(config: OneBotConfig): void {
this.endpoints = [...config.httpPostEndpoints];
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
this.clients = resolveClients(config);
log.info('reloaded %d HTTP POST adapter(s)', this.clients.size);
}
stop(): void {
this.stopped = true;
}
publishEvent(event: JsonObject): void {
const endpoints = this.endpoints;
if (!endpoints || endpoints.length === 0) return;
/**
* Forward one canonical event to every active HTTP push client.
*
* The instance pre-builds the {@link DispatchPayload} so this method only
* picks the right pre-serialized variant per client (zero extra
* `JSON.stringify` calls). The raw `event` is still kept around because the
* quick-operation handler reads structured fields from it.
*/
publishEvent(event: JsonObject, payload?: DispatchPayload): void {
if (this.stopped || this.clients.size === 0) return;
const payload = JSON.stringify(event);
for (const endpoint of endpoints) {
void this.postEvent(endpoint, payload, event);
const dispatch = payload ?? buildDispatchPayload(event);
for (const client of this.clients.values()) {
const json = pickDispatchJson(dispatch, client.options);
if (json === null) continue;
void this.postEvent(client.network, json, event);
}
}
private async postEvent(endpoint: HttpPostEndpoint, payload: string, event: JsonObject): Promise<void> {
private async postEvent(network: HttpClientNetwork, payload: string, event: JsonObject): Promise<void> {
if (this.stopped) return;
const headers: Record<string, string> = {
@@ -55,14 +75,14 @@ export class HttpPostTransport {
'X-Self-ID': this.context.uin,
};
if (endpoint.accessToken) {
headers['X-Signature'] = await computeHmacSha1(endpoint.accessToken, payload);
if (network.accessToken) {
headers['X-Signature'] = await computeHmacSha1(network.accessToken, payload);
}
const timeoutMs = endpoint.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const timeoutMs = network.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(endpoint.url, {
const response = await fetch(network.url, {
method: 'POST',
headers,
body: payload,
@@ -79,11 +99,11 @@ export class HttpPostTransport {
}
}
} else {
log.warn('POST %s returned %d', endpoint.url, response.status);
log.warn('[%s] POST %s returned %d', network.name, network.url, response.status);
}
} catch (error) {
if (!this.stopped) {
log.warn('POST %s failed: %s', endpoint.url, error instanceof Error ? error.message : String(error));
log.warn('[%s] POST %s failed: %s', network.name, network.url, error instanceof Error ? error.message : String(error));
}
}
}
@@ -100,6 +120,19 @@ export class HttpPostTransport {
}
}
function resolveClients(config: OneBotConfig): Map<string, ResolvedClient> {
const out = new Map<string, ResolvedClient>();
for (const network of config.networks.httpClients) {
if (network.enabled === false) continue;
if (!network.url) continue;
out.set(network.name, {
network,
options: resolveReportOptions(network),
});
}
return out;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
+39 -35
View File
@@ -5,7 +5,7 @@ import {
type ServerResponse,
} from 'http';
import type { ApiHandler } from './api-handler';
import type { HttpServerEndpoint, OneBotConfig } from './types';
import type { HttpServerNetwork, OneBotConfig } from './types';
import { createLogger } from '../utils/logger';
export interface HttpTransportContext {
@@ -14,66 +14,74 @@ export interface HttpTransportContext {
const log = createLogger('OneBot.HTTP');
interface RunningServer {
server: Server;
signature: string;
network: HttpServerNetwork;
}
export class HttpTransport {
private readonly context: HttpTransportContext;
private readonly servers = new Map<string, Server>();
private endpoints: HttpServerEndpoint[] = [];
private readonly servers = new Map<string, RunningServer>();
private networks: HttpServerNetwork[] = [];
constructor(config: OneBotConfig, context: HttpTransportContext) {
this.endpoints = [...config.httpServers];
this.networks = activeNetworks(config);
this.context = context;
}
start(): void {
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
for (const network of this.networks) this.startEndpoint(network);
}
reloadConfig(config: OneBotConfig): void {
const nextEndpoints = [...config.httpServers];
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
const nextNetworks = activeNetworks(config);
const nextByName = new Map(nextNetworks.map((n) => [n.name, n] as const));
for (const [key, server] of this.servers) {
if (!nextKeys.has(key)) {
server.close();
this.servers.delete(key);
log.info('stopped %s', key);
// Stop adapters that no longer exist or whose binding/auth changed.
for (const [name, running] of [...this.servers]) {
const next = nextByName.get(name);
if (!next || httpServerSignature(next) !== running.signature) {
running.server.close();
this.servers.delete(name);
log.info('stopped [%s]', name);
}
}
for (const endpoint of nextEndpoints) {
if (!this.servers.has(httpServerKey(endpoint))) {
this.startEndpoint(endpoint);
// (Re)start adapters that aren't running yet.
for (const network of nextNetworks) {
if (!this.servers.has(network.name)) {
this.startEndpoint(network);
}
}
this.endpoints = nextEndpoints;
this.networks = nextNetworks;
}
stop(): void {
for (const server of this.servers.values()) {
for (const { server } of this.servers.values()) {
server.close();
}
this.servers.clear();
}
private startEndpoint(endpoint: HttpServerEndpoint): void {
const expectedPath = normalizePath(endpoint.path ?? '/');
const endpointToken = endpoint.accessToken ?? '';
private startEndpoint(network: HttpServerNetwork): void {
const expectedPath = normalizePath(network.path ?? '/');
const endpointToken = network.accessToken ?? '';
const server = createServer((req, res) => {
void this.handleRequest(expectedPath, endpointToken, req, res);
});
server.on('listening', () => {
const label = endpoint.name ? `[${endpoint.name}] ` : '';
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
log.success('[%s] listening %s:%d%s', network.name, network.host ?? '0.0.0.0', network.port, expectedPath);
});
server.on('error', (error) => {
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
log.warn('[%s] server error: %s', network.name, error instanceof Error ? error.message : String(error));
});
server.listen(endpoint.port, endpoint.host);
this.servers.set(httpServerKey(endpoint), server);
server.listen(network.port, network.host ?? '0.0.0.0');
this.servers.set(network.name, { server, signature: httpServerSignature(network), network });
}
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
@@ -162,22 +170,18 @@ export class HttpTransport {
}
}
function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'http://127.0.0.1').pathname;
} catch {
return '/';
}
}
function normalizePath(pathValue: string): string {
const path = pathValue.trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function httpServerKey(endpoint: HttpServerEndpoint): string {
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
function httpServerSignature(network: HttpServerNetwork): string {
return `${network.host ?? '0.0.0.0'}:${network.port}${normalizePath(network.path ?? '/')}#${network.accessToken ?? ''}`;
}
function activeNetworks(config: OneBotConfig): HttpServerNetwork[] {
return config.networks.httpServers.filter((n) => n.enabled !== false);
}
function isAuthorized(request: IncomingMessage, token: string): boolean {
+12 -6
View File
@@ -12,6 +12,7 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import { HttpTransport } from './http-transport';
import { HttpPostTransport } from './http-post-transport';
import { WsTransport } from './ws-transport';
import { buildDispatchPayload } from './event-filter';
import { createLogger } from '../utils/logger';
const log = createLogger('Event');
@@ -157,12 +158,16 @@ export class OneBotInstance {
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
this.wsTransport.publishEvent(event);
this.httpPostTransport.publishEvent(event);
// Produce one canonical event, serialize the two format variants once,
// then let each adapter pick its slot at zero allocation cost.
const payload = buildDispatchPayload(event);
this.wsTransport.publishEvent(event, payload);
this.httpPostTransport.publishEvent(event, payload);
}
private logReceivedMessage(event: JsonObject): void {
if (event.post_type !== 'message') return;
const isSelf = event.post_type === 'message_sent';
if (event.post_type !== 'message' && !isSelf) return;
const messageId = toInt(event.message_id);
const isGroup = event.message_type === 'group';
@@ -203,23 +208,24 @@ export class OneBotInstance {
const content = parts.join(' ').trim() || '[空消息]';
const idStr = `ID:${messageId}`;
const selfTag = isSelf ? '[自身] ' : '';
if (isGroup) {
const groupId = toInt(event.group_id);
const userId = toInt(event.user_id);
const sender = event.sender as any;
const nickname = sender?.card || sender?.nickname || String(userId);
log.success(`群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`);
} else {
const userId = toInt(event.user_id);
const sender = event.sender as any;
const nickname = sender?.nickname || String(userId);
log.success(`私聊 ${nickname}(${userId}): ${idStr} ${content}`);
log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`);
}
}
private cacheMessageEvent(event: JsonObject): void {
if (event.post_type !== 'message') return;
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return;
const messageId = toInt(event.message_id);
if (messageId === 0) return;
+56 -31
View File
@@ -19,47 +19,72 @@ export interface OneBotRequest {
echo?: JsonValue;
}
export interface WsServerEndpoint {
name?: string;
host: string;
export type WsRole = 'api' | 'event' | 'universal';
export type MessageFormat = 'array' | 'string';
export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClients';
/**
* Fields shared by every network adapter. `messageFormat` and
* `reportSelfMessage` live on the adapter itself — there is no global default
* fallback; each adapter is fully self-describing.
*
* The `name` is a free-form identifier scoped to the adapter's array; it is
* used for hot-reload bookkeeping and as a label in logs / WebUI.
*/
interface NetworkBase {
name: string;
/** When `false`, the adapter is configured but inactive. Defaults to `true`. */
enabled?: boolean;
accessToken?: string;
/** Output format for this adapter. */
messageFormat: MessageFormat;
/** When `true`, this adapter receives `post_type='message_sent'` self events. */
reportSelfMessage: boolean;
}
export interface HttpServerNetwork extends NetworkBase {
host?: string;
port: number;
path?: string;
role?: WsRole;
accessToken?: string;
}
export interface HttpServerEndpoint {
name?: string;
host: string;
port: number;
path?: string;
accessToken?: string;
}
export interface WsClientEndpoint {
name?: string;
export interface HttpClientNetwork extends NetworkBase {
url: string;
role?: WsRole;
reconnectIntervalMs?: number;
accessToken?: string;
}
export interface HttpPostEndpoint {
name?: string;
url: string;
accessToken?: string;
timeoutMs?: number;
}
export interface OneBotConfig {
httpServers: HttpServerEndpoint[];
httpPostEndpoints: HttpPostEndpoint[];
wsServers: WsServerEndpoint[];
wsClients: WsClientEndpoint[];
musicSignUrl?: string;
export interface WsServerNetwork extends NetworkBase {
host?: string;
port: number;
path?: string;
role?: WsRole;
}
export type WsRole = 'api' | 'event' | 'universal';
export interface WsClientNetwork extends NetworkBase {
url: string;
role?: WsRole;
reconnectIntervalMs?: number;
}
/**
* Network adapters grouped by type. Each adapter is identified by `name`
* within its own array; hot-reload works on a per-(kind, name) basis.
*/
export interface OneBotNetworks {
httpServers: HttpServerNetwork[];
httpClients: HttpClientNetwork[];
wsServers: WsServerNetwork[];
wsClients: WsClientNetwork[];
}
/** Per-UIN OneBot configuration. */
export interface OneBotConfig {
networks: OneBotNetworks;
/** Music card signing service URL (optional). */
musicSignUrl?: string;
}
export interface MessageMeta {
isGroup: boolean;
+235 -177
View File
@@ -1,20 +1,44 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import type { ApiHandler } from './api-handler';
import type { JsonObject, OneBotConfig, WsClientEndpoint, WsRole, WsServerEndpoint } from './types';
import type { JsonObject, OneBotConfig, WsClientNetwork, WsRole, WsServerNetwork } from './types';
import { createLogger } from '../utils/logger';
import {
buildDispatchPayload,
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from './event-filter';
interface ForwardConnection {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
serverName: string;
}
interface ReverseConnection {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
endpointUrl: string;
reconnectIntervalMs: number;
key: string;
name: string;
}
interface RunningWsServer {
wss: WebSocketServer;
signature: string;
network: WsServerNetwork;
options: EventReportOptions;
}
interface RunningWsClient {
network: WsClientNetwork;
signature: string;
options: EventReportOptions;
}
export interface WsTransportContext {
@@ -29,204 +53,242 @@ const log = createLogger('OneBot.WS');
export class WsTransport {
private readonly context: WsTransportContext;
private readonly servers = new Map<string, WebSocketServer>();
private readonly servers = new Map<string, RunningWsServer>();
private readonly clientStates = new Map<string, RunningWsClient>();
private readonly forwardConnections = new Map<WebSocket, ForwardConnection>();
private readonly reverseConnections = new Set<ReverseConnection>();
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
private readonly reconnectTimersByKey = new Map<string, NodeJS.Timeout>();
private readonly activeReverseClientKeys = new Set<string>();
private serverEndpoints: WsServerEndpoint[] = [];
private clientEndpoints: WsClientEndpoint[] = [];
private desiredClientKeys = new Set<string>();
private readonly reverseConnections = new Map<string, ReverseConnection>();
private readonly reconnectTimers = new Map<string, NodeJS.Timeout>();
private serverNetworks: WsServerNetwork[] = [];
private clientNetworks: WsClientNetwork[] = [];
private stopped = false;
constructor(config: OneBotConfig, context: WsTransportContext) {
this.serverEndpoints = [...config.wsServers];
this.clientEndpoints = [...config.wsClients];
this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey));
this.serverNetworks = activeServers(config);
this.clientNetworks = activeClients(config);
this.context = context;
for (const network of this.clientNetworks) {
this.clientStates.set(network.name, {
network,
signature: wsClientSignature(network),
options: resolveReportOptions(network),
});
}
}
start(): void {
this.stopped = false;
this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey));
this.startServers();
this.startReverseClients();
for (const network of this.serverNetworks) this.startServerEndpoint(network);
for (const network of this.clientNetworks) this.startClientEndpoint(network.name);
}
reloadConfig(config: OneBotConfig): void {
const nextServers = [...config.wsServers];
const nextClients = [...config.wsClients];
const nextServerKeys = new Set(nextServers.map(wsServerKey));
const nextClientKeys = new Set(nextClients.map(wsClientKey));
this.desiredClientKeys = nextClientKeys;
const nextServers = activeServers(config);
const nextClients = activeClients(config);
const nextServerByName = new Map(nextServers.map((n) => [n.name, n] as const));
const nextClientByName = new Map(nextClients.map((n) => [n.name, n] as const));
for (const [key, server] of this.servers) {
if (!nextServerKeys.has(key)) {
server.close();
this.servers.delete(key);
log.info('stopped forward server %s', key);
// --- WS Servers ---
for (const [name, running] of [...this.servers]) {
const next = nextServerByName.get(name);
if (!next || wsServerSignature(next) !== running.signature) {
running.wss.close();
this.servers.delete(name);
// Drop forward connections that belonged to the closed adapter.
for (const [socket, conn] of [...this.forwardConnections]) {
if (conn.serverName === name) {
safeClose(socket);
this.forwardConnections.delete(socket);
}
}
log.info('stopped forward server [%s]', name);
} else {
// Same binding — refresh options so reload picks up format changes.
running.network = next;
running.options = resolveReportOptions(next);
for (const conn of this.forwardConnections.values()) {
if (conn.serverName === name) conn.options = running.options;
}
}
}
for (const network of nextServers) {
if (!this.servers.has(network.name)) this.startServerEndpoint(network);
}
// --- WS Clients (reverse) ---
for (const [name, state] of [...this.clientStates]) {
const next = nextClientByName.get(name);
const sig = next ? wsClientSignature(next) : null;
if (!next || sig !== state.signature) {
const conn = this.reverseConnections.get(name);
if (conn) {
safeClose(conn.socket);
this.reverseConnections.delete(name);
}
const timer = this.reconnectTimers.get(name);
if (timer) {
clearTimeout(timer);
this.reconnectTimers.delete(name);
}
this.clientStates.delete(name);
log.info('stopped reverse client [%s]', name);
} else {
state.network = next;
state.options = resolveReportOptions(next);
const conn = this.reverseConnections.get(name);
if (conn) conn.options = state.options;
}
}
for (const network of nextClients) {
if (!this.clientStates.has(network.name)) {
this.clientStates.set(network.name, {
network,
signature: wsClientSignature(network),
options: resolveReportOptions(network),
});
if (!this.stopped) this.startClientEndpoint(network.name);
}
}
for (const endpoint of nextServers) {
if (!this.servers.has(wsServerKey(endpoint))) {
this.startServerEndpoint(endpoint);
}
}
for (const conn of [...this.reverseConnections]) {
if (!nextClientKeys.has(conn.key)) {
this.clearReconnectTimer(conn.key);
this.activeReverseClientKeys.delete(conn.key);
safeClose(conn.socket);
this.reverseConnections.delete(conn);
log.info('stopped reverse client %s', conn.endpointUrl);
}
}
for (const endpoint of nextClients) {
const key = wsClientKey(endpoint);
if (!this.activeReverseClientKeys.has(key) && !this.reconnectTimersByKey.has(key)) {
this.startClientEndpoint(endpoint);
}
}
this.serverEndpoints = nextServers;
this.clientEndpoints = nextClients;
this.serverNetworks = nextServers;
this.clientNetworks = nextClients;
}
stop(): void {
this.stopped = true;
this.desiredClientKeys.clear();
// Final lifecycle broadcast before we mark ourselves stopped.
this.publishEvent(this.context.buildLifecycleEvent('disable'));
this.stopped = true;
for (const timer of this.reconnectTimers) {
for (const timer of this.reconnectTimers.values()) {
clearTimeout(timer);
}
this.reconnectTimers.clear();
this.reconnectTimersByKey.clear();
this.activeReverseClientKeys.clear();
for (const [socket] of this.forwardConnections) {
for (const socket of this.forwardConnections.keys()) {
safeClose(socket);
}
this.forwardConnections.clear();
for (const conn of this.reverseConnections) {
for (const conn of this.reverseConnections.values()) {
safeClose(conn.socket);
}
this.reverseConnections.clear();
for (const server of this.servers.values()) {
server.close();
for (const { wss } of this.servers.values()) {
wss.close();
}
this.servers.clear();
this.clientStates.clear();
}
publishEvent(event: JsonObject): void {
const payload = JSON.stringify(event);
/**
* Fan out one canonical event to every event-receiving WS connection.
*
* The instance pre-builds the {@link DispatchPayload} (two JSON variants at
* most) so each connection is served with a single O(1) pick + send rather
* than re-shaping or re-serializing the event itself. The raw `event` is
* accepted so ad-hoc callers (e.g. `stop()`) can dispatch without allocating
* a payload at the call site.
*/
publishEvent(event: JsonObject, payload?: DispatchPayload): void {
const dispatch = payload ?? buildDispatchPayload(event);
for (const { socket, role } of this.forwardConnections.values()) {
if (role === 'event' || role === 'universal') {
safeSend(socket, payload);
for (const conn of this.forwardConnections.values()) {
if (conn.role !== 'event' && conn.role !== 'universal') continue;
const json = pickDispatchJson(dispatch, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
for (const conn of this.reverseConnections.values()) {
if (conn.role !== 'event' && conn.role !== 'universal') continue;
const json = pickDispatchJson(dispatch, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
}
private startServerEndpoint(network: WsServerNetwork): void {
const wss = new WebSocketServer({
host: network.host ?? '0.0.0.0',
port: network.port,
path: network.path ?? '/',
});
const running: RunningWsServer = {
wss,
signature: wsServerSignature(network),
network,
options: resolveReportOptions(network),
};
this.servers.set(network.name, running);
wss.on('listening', () => {
log.success('[%s] listening %s:%d%s', network.name, network.host ?? '0.0.0.0', network.port, network.path ?? '/');
});
wss.on('connection', (socket, request) => {
if (!isAuthorized(request, running.network.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
}
for (const { socket, role } of this.reverseConnections.values()) {
if (role === 'event' || role === 'universal') {
safeSend(socket, payload);
}
}
}
const role = running.network.role ?? classifyForwardRole(request);
const conn: ForwardConnection = {
socket,
role,
options: running.options,
serverName: running.network.name,
};
this.forwardConnections.set(socket, conn);
private startServers(): void {
for (const endpoint of this.serverEndpoints) {
this.startServerEndpoint(endpoint);
}
}
private startServerEndpoint(endpoint: WsServerEndpoint): void {
const wss = new WebSocketServer({
host: endpoint.host,
port: endpoint.port,
path: endpoint.path ?? '/',
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
wss.on('listening', () => {
const label = endpoint.name ? `[${endpoint.name}] ` : '';
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, endpoint.path ?? '/');
socket.on('close', () => {
this.forwardConnections.delete(socket);
});
wss.on('connection', (socket, request) => {
if (!isAuthorized(request, endpoint.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = endpoint.role ?? classifyForwardRole(request);
const conn: ForwardConnection = { socket, role };
this.forwardConnections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => {
this.forwardConnections.delete(socket);
});
socket.on('error', (error: Error) => {
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
});
this.sendBootstrapMetaEvents(socket, role);
socket.on('error', (error: Error) => {
log.warn('[%s] forward socket error: %s', running.network.name, error instanceof Error ? error.message : String(error));
});
wss.on('error', (error: Error) => {
log.warn('server error: %s', error instanceof Error ? error.message : String(error));
});
this.sendBootstrapMetaEvents(socket, role, conn.options);
});
this.servers.set(wsServerKey(endpoint), wss);
wss.on('error', (error: Error) => {
log.warn('[%s] server error: %s', network.name, error instanceof Error ? error.message : String(error));
});
}
private startReverseClients(): void {
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
}
private startClientEndpoint(endpoint: WsClientEndpoint): void {
const role = endpoint.role ?? 'universal';
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
const key = wsClientKey(endpoint);
if (this.activeReverseClientKeys.has(key) || this.reconnectTimersByKey.has(key)) return;
this.connectReverseClient(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '', endpoint.name, key);
}
private connectReverseClient(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string, name?: string, key?: string): void {
const connKey = key ?? wsClientPartsKey(endpointUrl, role, reconnectIntervalMs, accessToken);
if (this.stopped || !this.desiredClientKeys.has(connKey)) return;
if (this.activeReverseClientKeys.has(connKey)) return;
this.clearReconnectTimer(connKey);
this.activeReverseClientKeys.add(connKey);
private startClientEndpoint(name: string): void {
const state = this.clientStates.get(name);
if (!state || this.stopped) return;
if (this.reverseConnections.has(name) || this.reconnectTimers.has(name)) return;
const network = state.network;
const role = network.role ?? 'universal';
const headers: Record<string, string> = {
'User-Agent': 'OneBot',
'X-Self-ID': this.context.uin,
'X-Client-Role': role,
};
if (network.accessToken) headers.Authorization = `Bearer ${network.accessToken}`;
if (accessToken) {
headers.Authorization = `Bearer ${accessToken}`;
}
const socket = new WebSocket(endpointUrl, { headers });
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: connKey };
this.reverseConnections.add(conn);
const socket = new WebSocket(network.url, { headers });
const conn: ReverseConnection = {
socket,
role,
options: state.options,
endpointUrl: network.url,
reconnectIntervalMs: Math.max(1000, network.reconnectIntervalMs ?? 5000),
name,
};
this.reverseConnections.set(name, conn);
socket.on('open', () => {
const label = name ? `[${name}] ` : '';
log.info('%sreverse connected %s', label, endpointUrl);
this.sendBootstrapMetaEvents(socket, role);
log.info('[%s] reverse connected %s', name, network.url);
this.sendBootstrapMetaEvents(socket, role, state.options);
});
socket.on('message', (raw: Buffer) => {
@@ -234,36 +296,25 @@ export class WsTransport {
});
socket.on('close', () => {
this.reverseConnections.delete(conn);
this.activeReverseClientKeys.delete(connKey);
this.reverseConnections.delete(name);
if (this.stopped) return;
if (!this.desiredClientKeys.has(connKey)) return;
if (this.reconnectTimersByKey.has(connKey)) return;
if (!this.clientStates.has(name)) return;
if (this.reconnectTimers.has(name)) return;
const timer = setTimeout(() => {
this.reconnectTimers.delete(timer);
this.reconnectTimersByKey.delete(connKey);
if (this.stopped || !this.desiredClientKeys.has(connKey)) return;
this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name, connKey);
}, reconnectIntervalMs);
this.reconnectTimers.delete(name);
if (this.stopped || !this.clientStates.has(name)) return;
this.startClientEndpoint(name);
}, conn.reconnectIntervalMs);
timer.unref?.();
this.reconnectTimers.add(timer);
this.reconnectTimersByKey.set(connKey, timer);
this.reconnectTimers.set(name, timer);
});
socket.on('error', (error: Error) => {
log.warn('reverse error %s: %s', endpointUrl, error instanceof Error ? error.message : String(error));
log.warn('[%s] reverse error %s: %s', name, network.url, error instanceof Error ? error.message : String(error));
});
}
private clearReconnectTimer(key: string): void {
const timer = this.reconnectTimersByKey.get(key);
if (!timer) return;
clearTimeout(timer);
this.reconnectTimersByKey.delete(key);
this.reconnectTimers.delete(timer);
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
if (role !== 'api' && role !== 'universal') return;
@@ -274,16 +325,19 @@ export class WsTransport {
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole): void {
private sendBootstrapMetaEvents(socket: WebSocket, role: WsRole, options: EventReportOptions): void {
if (role !== 'event' && role !== 'universal') return;
const connectEvent = this.context.buildLifecycleEvent('connect');
const enableEvent = this.context.buildLifecycleEvent('enable');
const heartbeatEvent = this.context.buildHeartbeatEvent();
safeSend(socket, JSON.stringify(connectEvent));
safeSend(socket, JSON.stringify(enableEvent));
safeSend(socket, JSON.stringify(heartbeatEvent));
const events = [
this.context.buildLifecycleEvent('connect'),
this.context.buildLifecycleEvent('enable'),
this.context.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
@@ -308,18 +362,22 @@ function normalizeWsPath(pathValue: string | undefined): string {
return path.endsWith('/') ? path.slice(0, -1) : path;
}
function wsServerKey(endpoint: WsServerEndpoint): string {
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
function activeServers(config: OneBotConfig): WsServerNetwork[] {
return config.networks.wsServers.filter((n) => n.enabled !== false);
}
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
function activeClients(config: OneBotConfig): WsClientNetwork[] {
return config.networks.wsClients.filter((n) => n.enabled !== false && !!n.url);
}
function wsClientKey(endpoint: WsClientEndpoint): string {
const role = endpoint.role ?? 'universal';
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.accessToken ?? '');
function wsServerSignature(network: WsServerNetwork): string {
return `${network.host ?? '0.0.0.0'}:${network.port}${normalizeWsPath(network.path)}#${network.role ?? 'auto'}#${network.accessToken ?? ''}`;
}
function wsClientSignature(network: WsClientNetwork): string {
const role = network.role ?? 'universal';
const reconnectIntervalMs = Math.max(1000, network.reconnectIntervalMs ?? 5000);
return `${network.url}#${role}#${reconnectIntervalMs}#${network.accessToken ?? ''}`;
}
function isAuthorized(request: IncomingMessage, token: string): boolean {