Merge remote-tracking branch 'upstream' into feat/onebot
This commit is contained in:
commit
99c74b4a66
31 files changed
+2353
-868
No files matched your search
@@ -479,17 +479,10 @@ function elementsToText(elements: MessageElement[]): string {
|
||||
|
||||
function printEvent(event: QQEventVariant): void {
|
||||
switch (event.kind) {
|
||||
case 'group_message': {
|
||||
const c = elementsToText(event.elements);
|
||||
const s = event.senderCard || event.senderNick || String(event.senderUin);
|
||||
eventLog.success('群 %d | %s(%d): %s', event.groupId, s, event.senderUin, c);
|
||||
break;
|
||||
}
|
||||
case 'group_message':
|
||||
case 'friend_message':
|
||||
eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements));
|
||||
break;
|
||||
case 'temp_message':
|
||||
eventLog.info('临时 %d(群%d): %s', event.senderUin, event.groupId, elementsToText(event.elements));
|
||||
// Message logging is handled by OneBot layer with message ID
|
||||
break;
|
||||
case 'group_recall':
|
||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
||||
|
||||
@@ -54,11 +54,21 @@ function makeMentionElem(element: MessageElement): ProtoElem {
|
||||
}
|
||||
|
||||
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
return {
|
||||
srcMsg: {
|
||||
origSeqs: [element.replySeq! & 0xFFFFFFFF],
|
||||
} as any,
|
||||
const seq = element.replySeq! & 0xFFFFFFFF;
|
||||
|
||||
const srcMsg: any = {
|
||||
origSeqs: [seq],
|
||||
};
|
||||
|
||||
// Add additional fields if available for better reply display
|
||||
if (element.replySenderUin) {
|
||||
srcMsg.senderUin = BigInt(element.replySenderUin);
|
||||
}
|
||||
if (element.replyTime) {
|
||||
srcMsg.time = element.replyTime;
|
||||
}
|
||||
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
|
||||
@@ -13,6 +13,10 @@ export interface MessageElement {
|
||||
fileName?: string;
|
||||
fileSize?: number;
|
||||
replySeq?: number;
|
||||
replyMessageId?: number; // For reply: original message ID (for logging)
|
||||
replySenderUin?: number; // For reply: original sender's UIN
|
||||
replyTime?: number; // For reply: original message timestamp
|
||||
replyRandom?: number; // For reply: original message random/msgId
|
||||
url?: string;
|
||||
subType?: number;
|
||||
duration?: number;
|
||||
|
||||
@@ -204,11 +204,24 @@ export class HookManager {
|
||||
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
||||
}
|
||||
|
||||
// Clear injection state first
|
||||
state.injected = false;
|
||||
state.injectResult = null;
|
||||
state.method = '';
|
||||
state.uin = '0';
|
||||
state.status = 'available';
|
||||
|
||||
// Verify unload succeeded by checking if pipe still exists
|
||||
const livePipes = await QqHookClient.listLivePipes();
|
||||
if (livePipes.has(pid)) {
|
||||
// Pipe still exists - unload failed, but let watcher handle reconnection
|
||||
state.error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连';
|
||||
state.status = 'connecting'; // Let watcher pick it up and reconnect
|
||||
log.warn('unload verification failed: PID=%d pipe still exists after unloadModuleManual, watcher will reconnect', pid);
|
||||
} else {
|
||||
// Successfully unloaded
|
||||
state.status = 'available';
|
||||
state.error = '';
|
||||
}
|
||||
} catch (error) {
|
||||
state.status = 'error';
|
||||
state.error = error instanceof Error ? error.message : String(error);
|
||||
@@ -311,7 +324,7 @@ export class HookManager {
|
||||
state.name = proc.name || state.name;
|
||||
state.path = proc.path || state.path;
|
||||
}
|
||||
// Auto-detect hooks that survived a SnowLuma restart.
|
||||
// Auto-detect hooks that survived a SnowLuma restart or failed unload.
|
||||
for (const pid of livePipes) {
|
||||
const state = this.ensureState(pid);
|
||||
if (!state.injected) {
|
||||
|
||||
+267
-179
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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');
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { Bridge } from '../bridge/bridge';
|
||||
import type { ForwardNodePayload } from '../bridge/events';
|
||||
import type { ForwardNodePayload, MessageElement } from '../bridge/events';
|
||||
import type { QQInfo } from '../bridge/qq-info';
|
||||
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
||||
import { elementsToOneBotSegments } from './event-converter';
|
||||
@@ -7,6 +7,9 @@ import { MessageStore } from './message-store';
|
||||
import { parseMessage } from './message-parser';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||
import { createLogger } from '../utils/logger';
|
||||
|
||||
const log = createLogger('OneBot');
|
||||
|
||||
export interface InstanceRef {
|
||||
uin: string;
|
||||
@@ -414,6 +417,68 @@ async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, mess
|
||||
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
|
||||
}
|
||||
|
||||
// --- Send message logging ---
|
||||
|
||||
function logSentMessage(isGroup: boolean, targetId: number, elements: MessageElement[]): void {
|
||||
const type = isGroup ? '群聊' : '私聊';
|
||||
const parts: string[] = [];
|
||||
|
||||
// Check for reply element
|
||||
const replyElem = elements.find(e => e.type === 'reply');
|
||||
if (replyElem && replyElem.replyMessageId) {
|
||||
parts.push(`[回复:${replyElem.replyMessageId}]`);
|
||||
}
|
||||
|
||||
// Build message content preview
|
||||
for (const elem of elements) {
|
||||
if (elem.type === 'reply') continue; // Already handled
|
||||
|
||||
switch (elem.type) {
|
||||
case 'text':
|
||||
if (elem.text) {
|
||||
const preview = elem.text.length > 50 ? elem.text.substring(0, 50) + '...' : elem.text;
|
||||
parts.push(preview);
|
||||
}
|
||||
break;
|
||||
case 'image':
|
||||
parts.push('[图片]');
|
||||
break;
|
||||
case 'face':
|
||||
parts.push('[表情]');
|
||||
break;
|
||||
case 'at':
|
||||
if (elem.text) parts.push(elem.text.trim());
|
||||
break;
|
||||
case 'record':
|
||||
parts.push('[语音]');
|
||||
break;
|
||||
case 'video':
|
||||
parts.push('[视频]');
|
||||
break;
|
||||
case 'json':
|
||||
parts.push('[JSON消息]');
|
||||
break;
|
||||
case 'xml':
|
||||
parts.push('[XML消息]');
|
||||
break;
|
||||
case 'markdown':
|
||||
parts.push('[Markdown]');
|
||||
break;
|
||||
case 'forward':
|
||||
parts.push('[转发消息]');
|
||||
break;
|
||||
case 'poke':
|
||||
parts.push('[戳一戳]');
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const content = parts.join(' ').trim() || '[空消息]';
|
||||
log.info(`${type} ${targetId} | 发送:${content}`);
|
||||
}
|
||||
|
||||
// --- Send message ---
|
||||
|
||||
async function handleSendPrivate(
|
||||
@@ -423,8 +488,21 @@ async function handleSendPrivate(
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) =>
|
||||
ref.messageStore.resolveReplySequence(false, userId, replyMessageId),
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const meta = ref.messageStore.findMeta(replyMessageId);
|
||||
if (meta) {
|
||||
return {
|
||||
senderUin: meta.targetId, // For received messages, targetId is the sender
|
||||
time: meta.timestamp,
|
||||
random: meta.random,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin),
|
||||
musicSignUrl: ref.musicSignUrl,
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
@@ -432,6 +510,9 @@ async function handleSendPrivate(
|
||||
const receipt = await ref.bridge.sendPrivateMessage(userId, elements);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||
|
||||
// Log sent message
|
||||
logSentMessage(false, userId, elements);
|
||||
|
||||
// Cache the sent message meta
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: false,
|
||||
@@ -453,8 +534,21 @@ async function handleSendGroup(
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) =>
|
||||
ref.messageStore.resolveReplySequence(true, groupId, replyMessageId),
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
},
|
||||
resolveReplyMeta: (replyMessageId) => {
|
||||
const event = ref.messageStore.findEvent(replyMessageId);
|
||||
if (event) {
|
||||
return {
|
||||
senderUin: typeof event.user_id === 'number' ? event.user_id : parseInt(String(event.user_id || '0'), 10),
|
||||
time: typeof event.time === 'number' ? event.time : parseInt(String(event.time || '0'), 10),
|
||||
random: 0, // Group messages might not have random field in event
|
||||
};
|
||||
}
|
||||
return null;
|
||||
},
|
||||
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
|
||||
musicSignUrl: ref.musicSignUrl,
|
||||
});
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
@@ -462,6 +556,9 @@ async function handleSendGroup(
|
||||
const receipt = await ref.bridge.sendGroupMessage(groupId, elements);
|
||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||
|
||||
// Log sent message
|
||||
logSentMessage(true, groupId, elements);
|
||||
|
||||
// Cache the sent message meta
|
||||
ref.cacheMessageMeta(messageId, {
|
||||
isGroup: true,
|
||||
|
||||
@@ -12,6 +12,10 @@ 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');
|
||||
|
||||
export class OneBotInstance {
|
||||
readonly uin: string;
|
||||
@@ -153,12 +157,75 @@ export class OneBotInstance {
|
||||
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.wsTransport.publishEvent(event);
|
||||
this.httpPostTransport.publishEvent(event);
|
||||
this.logReceivedMessage(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 {
|
||||
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';
|
||||
|
||||
// Build message preview
|
||||
const parts: string[] = [];
|
||||
const message = event.message;
|
||||
|
||||
if (Array.isArray(message)) {
|
||||
for (const seg of message) {
|
||||
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
|
||||
const type = String(seg.type ?? '');
|
||||
const data: Record<string, unknown> = (
|
||||
typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data)
|
||||
) ? seg.data : {};
|
||||
|
||||
if (type === 'text' && data.text) {
|
||||
const text = String(data.text);
|
||||
const preview = text.length > 50 ? text.substring(0, 50) + '...' : text;
|
||||
parts.push(preview);
|
||||
} else if (type === 'image') {
|
||||
parts.push('[图片]');
|
||||
} else if (type === 'face') {
|
||||
parts.push('[表情]');
|
||||
} else if (type === 'at') {
|
||||
parts.push(`@${data.qq || ''}`);
|
||||
} else if (type === 'reply') {
|
||||
parts.push(`[回复:${data.id || ''}]`);
|
||||
} else if (type === 'record') {
|
||||
parts.push('[语音]');
|
||||
} else if (type === 'video') {
|
||||
parts.push('[视频]');
|
||||
} else {
|
||||
parts.push(`[${type}]`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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(`${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(`${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;
|
||||
|
||||
@@ -7,6 +7,8 @@ import type { JsonValue, JsonObject } from './types';
|
||||
|
||||
export interface ParseMessageOptions {
|
||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
||||
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
|
||||
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
|
||||
musicSignUrl?: string;
|
||||
}
|
||||
|
||||
@@ -88,12 +90,25 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
return { type: 'face', faceId: id };
|
||||
}
|
||||
case 'at': {
|
||||
const qq = String(data.qq ?? '');
|
||||
const qq = String(data.qq ?? '').trim();
|
||||
if (qq === 'all') {
|
||||
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||
}
|
||||
const uin = parseInt(qq, 10);
|
||||
return uin > 0 ? { type: 'at', targetUin: uin, text: `@${uin} ` } : null;
|
||||
if (uin <= 0) return null;
|
||||
|
||||
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
|
||||
let uid = String(data.uid ?? '').trim();
|
||||
if (!uid && options?.resolveMentionUid) {
|
||||
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
|
||||
}
|
||||
|
||||
return {
|
||||
type: 'at',
|
||||
targetUin: uin,
|
||||
uid: uid || undefined,
|
||||
text: name ? `@${name} ` : `@${uin} `,
|
||||
};
|
||||
}
|
||||
case 'reply': {
|
||||
const id = parseInt(String(data.id ?? '0'), 10);
|
||||
@@ -102,7 +117,23 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
||||
if (options?.resolveReplySequence) {
|
||||
const resolved = options.resolveReplySequence(id);
|
||||
if (typeof resolved === 'number' && resolved > 0) {
|
||||
return { type: 'reply', replySeq: resolved };
|
||||
const element: MessageElement = {
|
||||
type: 'reply',
|
||||
replySeq: resolved,
|
||||
replyMessageId: id // Keep the original messageId for logging
|
||||
};
|
||||
|
||||
// Try to get additional meta info for better reply display
|
||||
if (options?.resolveReplyMeta) {
|
||||
const meta = options.resolveReplyMeta(id);
|
||||
if (meta) {
|
||||
element.replySenderUin = meta.senderUin;
|
||||
element.replyTime = meta.time;
|
||||
element.replyRandom = meta.random;
|
||||
}
|
||||
}
|
||||
|
||||
return element;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -120,15 +120,31 @@ export class MessageStore {
|
||||
}
|
||||
|
||||
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
|
||||
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null;
|
||||
const row = this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = ? AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined;
|
||||
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
|
||||
// For private messages, we cannot rely on session_id matching because:
|
||||
// - When receiving: session_id is the sender's UIN
|
||||
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
|
||||
// So for private messages, we only match by message_hash and is_group flag.
|
||||
const row = isGroup
|
||||
? this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(sessionId, messageId) as { sequence: number } | undefined
|
||||
: this.db.prepare(
|
||||
`SELECT sequence
|
||||
FROM messages
|
||||
WHERE is_group = 0 AND message_hash = ?
|
||||
LIMIT 1`
|
||||
).get(messageId) as { sequence: number } | undefined;
|
||||
|
||||
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
|
||||
return null;
|
||||
}
|
||||
return row.sequence;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -10,6 +10,17 @@ const SCRYPT_N = 16384; // cost
|
||||
const SCRYPT_R = 8;
|
||||
const SCRYPT_P = 1;
|
||||
|
||||
/**
|
||||
* Fixed credentials used when SNOWLUMA_DEV_MODE=1 is set. The state is kept
|
||||
* entirely in memory and never written to `config/webui.json`, so toggling
|
||||
* dev mode on/off never disturbs the real persisted password.
|
||||
*/
|
||||
const DEV_PASSWORD = 'snowluma-dev';
|
||||
|
||||
export function isDevAuthMode(): boolean {
|
||||
return process.env.SNOWLUMA_DEV_MODE === '1';
|
||||
}
|
||||
|
||||
export interface WebuiAuthState {
|
||||
passwordHash: string; // hex
|
||||
passwordSalt: string; // hex
|
||||
@@ -89,20 +100,35 @@ function atomicWrite(state: WebuiAuthState): void {
|
||||
export class WebuiAuth {
|
||||
private state: WebuiAuthState;
|
||||
private initialPlain: string | null;
|
||||
private readonly devMode: boolean;
|
||||
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null) {
|
||||
private constructor(state: WebuiAuthState, initialPlain: string | null, devMode: boolean) {
|
||||
this.state = state;
|
||||
this.initialPlain = initialPlain;
|
||||
this.devMode = devMode;
|
||||
}
|
||||
|
||||
static load(): WebuiAuth {
|
||||
if (isDevAuthMode()) {
|
||||
const salt = randomBytes(16);
|
||||
const hash = hashPassword(DEV_PASSWORD, salt);
|
||||
const now = new Date().toISOString();
|
||||
const state: WebuiAuthState = {
|
||||
passwordHash: hash.toString('hex'),
|
||||
passwordSalt: salt.toString('hex'),
|
||||
mustChangePassword: false,
|
||||
generatedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
return new WebuiAuth(state, null, true);
|
||||
}
|
||||
ensureConfigDir();
|
||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||
try {
|
||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (isValidState(parsed)) {
|
||||
return new WebuiAuth(parsed, null);
|
||||
return new WebuiAuth(parsed, null, false);
|
||||
}
|
||||
} catch {
|
||||
/* fallthrough — regenerate */
|
||||
@@ -111,7 +137,17 @@ export class WebuiAuth {
|
||||
const initialPassword = randomBytes(8).toString('hex');
|
||||
const state = generateInitialState(initialPassword);
|
||||
atomicWrite(state);
|
||||
return new WebuiAuth(state, initialPassword);
|
||||
return new WebuiAuth(state, initialPassword, false);
|
||||
}
|
||||
|
||||
/** True when SNOWLUMA_DEV_MODE was active at load time. */
|
||||
isDevMode(): boolean {
|
||||
return this.devMode;
|
||||
}
|
||||
|
||||
/** Fixed dev password (only meaningful when {@link isDevMode} is true). */
|
||||
static get devPassword(): string {
|
||||
return DEV_PASSWORD;
|
||||
}
|
||||
|
||||
/** Returns the auto-generated initial password if this is a fresh install, else null. */
|
||||
@@ -143,6 +179,9 @@ export class WebuiAuth {
|
||||
* After success, mustChangePassword=false and the file is rewritten on disk.
|
||||
*/
|
||||
setPassword(newPassword: string): void {
|
||||
if (this.devMode) {
|
||||
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||
}
|
||||
if (!isStrongPassword(newPassword)) {
|
||||
throw new Error('密码不符合强度要求');
|
||||
}
|
||||
|
||||
@@ -11,13 +11,9 @@ import path from 'path';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { fileURLToPath } from 'url';
|
||||
import os from 'os';
|
||||
import { exec } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
|
||||
import { findAvailablePort } from './port';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
const log = createLogger('WebUI');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
@@ -81,7 +77,14 @@ export async function initWebUI(
|
||||
): Promise<{ port: number }> {
|
||||
const auth = WebuiAuth.load();
|
||||
const initialPassword = auth.takeInitialPassword();
|
||||
if (initialPassword) {
|
||||
if (auth.isDevMode()) {
|
||||
log.warn('=========================================');
|
||||
log.warn('WebUI 已进入开发模式 (SNOWLUMA_DEV_MODE=1)');
|
||||
log.warn('固定密码: %s', WebuiAuth.devPassword);
|
||||
log.warn('config/webui.json 不会被读写,强制改密流程已跳过');
|
||||
log.warn('请勿在生产环境启用此模式');
|
||||
log.warn('=========================================');
|
||||
} else if (initialPassword) {
|
||||
log.info('=========================================');
|
||||
log.info('WebUI 安全认证(首次启动,已生成临时密码)');
|
||||
log.info('默认用户: admin');
|
||||
@@ -269,67 +272,13 @@ export async function initWebUI(
|
||||
return usage;
|
||||
}
|
||||
|
||||
let cachedGpu: { name: string; vendor: string }[] | null = null;
|
||||
let gpuFetchedAt = 0;
|
||||
async function detectGpus(): Promise<{ name: string; vendor: string }[]> {
|
||||
const now = Date.now();
|
||||
if (cachedGpu && now - gpuFetchedAt < 60_000) return cachedGpu;
|
||||
const platform = os.platform();
|
||||
const result: { name: string; vendor: string }[] = [];
|
||||
try {
|
||||
if (platform === 'win32') {
|
||||
const { stdout } = await execAsync('wmic path win32_VideoController get Name /value', {
|
||||
timeout: 4000,
|
||||
windowsHide: true,
|
||||
});
|
||||
for (const line of stdout.split(/\r?\n/)) {
|
||||
const m = line.match(/^Name=(.+)$/);
|
||||
if (m && m[1].trim()) result.push({ name: m[1].trim(), vendor: '' });
|
||||
}
|
||||
} else if (platform === 'linux') {
|
||||
try {
|
||||
const { stdout } = await execAsync('lspci -mm | grep -Ei "vga|3d|display"', { timeout: 4000 });
|
||||
for (const line of stdout.split(/\r?\n/)) {
|
||||
const parts = line.match(/"([^"]+)"\s+"([^"]+)"\s+"([^"]+)"/);
|
||||
if (parts) result.push({ vendor: parts[2], name: parts[3] });
|
||||
}
|
||||
} catch {
|
||||
try {
|
||||
const { stdout } = await execAsync('nvidia-smi --query-gpu=name --format=csv,noheader', { timeout: 4000 });
|
||||
for (const line of stdout.split(/\r?\n/)) {
|
||||
if (line.trim()) result.push({ name: line.trim(), vendor: 'NVIDIA' });
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
} else if (platform === 'darwin') {
|
||||
const { stdout } = await execAsync('system_profiler SPDisplaysDataType -json', { timeout: 5000 });
|
||||
try {
|
||||
const json = JSON.parse(stdout);
|
||||
const list = json.SPDisplaysDataType ?? [];
|
||||
for (const item of list) {
|
||||
if (item._name) result.push({ name: item._name, vendor: item.spdisplays_vendor ?? '' });
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
/* best-effort */
|
||||
}
|
||||
cachedGpu = result;
|
||||
gpuFetchedAt = now;
|
||||
return result;
|
||||
}
|
||||
|
||||
app.get('/api/system', async (c) => {
|
||||
app.get('/api/system', (c) => {
|
||||
const cpus = os.cpus();
|
||||
const usage = sampleCpuLoad();
|
||||
const totalMem = os.totalmem();
|
||||
const freeMem = os.freemem();
|
||||
const usedMem = totalMem - freeMem;
|
||||
const gpus = await detectGpus().catch(() => []);
|
||||
const runtimeMemory = process.memoryUsage();
|
||||
return c.json({
|
||||
hostname: os.hostname(),
|
||||
platform: os.platform(),
|
||||
@@ -352,7 +301,14 @@ export async function initWebUI(
|
||||
used: usedMem,
|
||||
usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0,
|
||||
},
|
||||
gpus,
|
||||
runtime: {
|
||||
pid: process.pid,
|
||||
rss: runtimeMemory.rss,
|
||||
heapTotal: runtimeMemory.heapTotal,
|
||||
heapUsed: runtimeMemory.heapUsed,
|
||||
external: runtimeMemory.external,
|
||||
arrayBuffers: runtimeMemory.arrayBuffers,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user