Merge remote-tracking branch 'upstream' into feat/onebot
This commit is contained in:
commit
99c74b4a66
31 files changed
+2317
-832
No files matched your search
@@ -5,58 +5,14 @@
|
|||||||
## 关于项目
|
## 关于项目
|
||||||
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
|
项目处于开发初期,仅支持部分功能,持续高速迭代中,仅支持有头。
|
||||||
|
|
||||||
## 仓库结构
|
## 测试要求
|
||||||
|
1. 外部库能正常加载
|
||||||
|
|
||||||
本仓库使用 **pnpm workspace** 进行多包管理。
|
2. 外部库能正常卸载
|
||||||
|
|
||||||
```
|
3. 卸载时Pipe以及副作用被清除
|
||||||
SnowLuma/
|
|
||||||
├─ packages/
|
|
||||||
│ ├─ core/ @snowluma/core - Node.js 运行时(NTQQ packet sniffer + Hook + OneBot)
|
|
||||||
│ ├─ webui/ webui - React + Vite 前端
|
|
||||||
│ └─ runtime/ @snowluma/runtime - 发行包资源
|
|
||||||
│ ├─ launcher.bat
|
|
||||||
│ ├─ package.json (随 dist 一起发布的运行时依赖清单)
|
|
||||||
│ └─ native/ 平台预编译产物 (snowluma-win32-x64.{dll,node})
|
|
||||||
├─ tools/ 辅助脚本(如 Python OneBot WS 测试)
|
|
||||||
├─ tsconfig.base.json
|
|
||||||
├─ tsconfig.json monorepo 根 TS 项目(仅含 references)
|
|
||||||
├─ pnpm-workspace.yaml
|
|
||||||
└─ package.json monorepo 根(脚本委托给 pnpm filter)
|
|
||||||
```
|
|
||||||
|
|
||||||
构建产物统一输出到仓库根 `dist/`,与发行流水线保持兼容。
|
4. 当Snowluma重启时可恢复所有Pipe管道
|
||||||
|
|
||||||
## 常用命令
|
|
||||||
|
|
||||||
```bash
|
|
||||||
# 安装依赖
|
|
||||||
pnpm install
|
|
||||||
|
|
||||||
# 开发 — 核心运行时(tsx)
|
|
||||||
pnpm dev
|
|
||||||
|
|
||||||
# 开发 — WebUI 前端(vite dev server)
|
|
||||||
pnpm dev:web
|
|
||||||
|
|
||||||
# 仅构建核心
|
|
||||||
pnpm build
|
|
||||||
|
|
||||||
# 仅构建 WebUI
|
|
||||||
pnpm build:webui
|
|
||||||
|
|
||||||
# 一次构建核心 + WebUI 完整发行版(顺序固定 core → webui)
|
|
||||||
pnpm build:all
|
|
||||||
|
|
||||||
# 单元测试 / 类型检查 / Lint
|
|
||||||
pnpm test
|
|
||||||
pnpm typecheck
|
|
||||||
pnpm lint
|
|
||||||
|
|
||||||
# 直接对单个包操作
|
|
||||||
pnpm --filter @snowluma/core dev
|
|
||||||
pnpm --filter webui build
|
|
||||||
```
|
|
||||||
|
|
||||||
## 鸣谢
|
## 鸣谢
|
||||||
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto
|
||||||
@@ -72,4 +28,4 @@ pnpm --filter webui build
|
|||||||
## 加入我们
|
## 加入我们
|
||||||
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
|
||||||
|
|
||||||
[SnowLuma-Tg](https://t.me/napcatqq)
|
[SnowLuma-TG](https://t.me/napcatqq)
|
||||||
@@ -9,6 +9,7 @@
|
|||||||
"build:webui": "pnpm --filter webui build",
|
"build:webui": "pnpm --filter webui build",
|
||||||
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
|
"build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter webui build",
|
||||||
"dev": "pnpm --filter @snowluma/core dev",
|
"dev": "pnpm --filter @snowluma/core dev",
|
||||||
|
"dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs",
|
||||||
"dev:web": "pnpm --filter webui dev",
|
"dev:web": "pnpm --filter webui dev",
|
||||||
"test": "pnpm --filter @snowluma/core test",
|
"test": "pnpm --filter @snowluma/core test",
|
||||||
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
"test:watch": "pnpm --filter @snowluma/core test:watch",
|
||||||
@@ -17,6 +18,7 @@
|
|||||||
"start": "node dist/index.mjs"
|
"start": "node dist/index.mjs"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"cross-env": "^10.1.0",
|
||||||
"typescript": "catalog:"
|
"typescript": "catalog:"
|
||||||
},
|
},
|
||||||
"pnpm": {
|
"pnpm": {
|
||||||
|
|||||||
@@ -479,17 +479,10 @@ function elementsToText(elements: MessageElement[]): string {
|
|||||||
|
|
||||||
function printEvent(event: QQEventVariant): void {
|
function printEvent(event: QQEventVariant): void {
|
||||||
switch (event.kind) {
|
switch (event.kind) {
|
||||||
case 'group_message': {
|
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 'friend_message':
|
case 'friend_message':
|
||||||
eventLog.info('私聊 %s(%d): %s', event.senderNick || String(event.senderUin), event.senderUin, elementsToText(event.elements));
|
|
||||||
break;
|
|
||||||
case 'temp_message':
|
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;
|
break;
|
||||||
case 'group_recall':
|
case 'group_recall':
|
||||||
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
|
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 {
|
function makeReplyElem(element: MessageElement): ProtoElem {
|
||||||
return {
|
const seq = element.replySeq! & 0xFFFFFFFF;
|
||||||
srcMsg: {
|
|
||||||
origSeqs: [element.replySeq! & 0xFFFFFFFF],
|
const srcMsg: any = {
|
||||||
} as 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 {
|
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||||
|
|||||||
@@ -13,6 +13,10 @@ export interface MessageElement {
|
|||||||
fileName?: string;
|
fileName?: string;
|
||||||
fileSize?: number;
|
fileSize?: number;
|
||||||
replySeq?: 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;
|
url?: string;
|
||||||
subType?: number;
|
subType?: number;
|
||||||
duration?: number;
|
duration?: number;
|
||||||
|
|||||||
@@ -204,11 +204,24 @@ export class HookManager {
|
|||||||
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
log.info('SnowLuma unloaded from PID=%d via unloadModuleManual', pid);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Clear injection state first
|
||||||
state.injected = false;
|
state.injected = false;
|
||||||
state.injectResult = null;
|
state.injectResult = null;
|
||||||
state.method = '';
|
state.method = '';
|
||||||
state.uin = '0';
|
state.uin = '0';
|
||||||
|
|
||||||
|
// 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.status = 'available';
|
||||||
|
state.error = '';
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
state.status = 'error';
|
state.status = 'error';
|
||||||
state.error = error instanceof Error ? error.message : String(error);
|
state.error = error instanceof Error ? error.message : String(error);
|
||||||
@@ -311,7 +324,7 @@ export class HookManager {
|
|||||||
state.name = proc.name || state.name;
|
state.name = proc.name || state.name;
|
||||||
state.path = proc.path || state.path;
|
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) {
|
for (const pid of livePipes) {
|
||||||
const state = this.ensureState(pid);
|
const state = this.ensureState(pid);
|
||||||
if (!state.injected) {
|
if (!state.injected) {
|
||||||
|
|||||||
+261
-173
@@ -1,92 +1,76 @@
|
|||||||
import fs from 'fs';
|
import fs from 'fs';
|
||||||
import path from 'path';
|
import path from 'path';
|
||||||
|
import { randomBytes } from 'crypto';
|
||||||
import type {
|
import type {
|
||||||
HttpPostEndpoint,
|
HttpClientNetwork,
|
||||||
HttpServerEndpoint,
|
HttpServerNetwork,
|
||||||
JsonObject,
|
JsonObject,
|
||||||
|
MessageFormat,
|
||||||
OneBotConfig,
|
OneBotConfig,
|
||||||
WsClientEndpoint,
|
OneBotNetworks,
|
||||||
|
WsClientNetwork,
|
||||||
WsRole,
|
WsRole,
|
||||||
WsServerEndpoint,
|
WsServerNetwork,
|
||||||
} from './types';
|
} from './types';
|
||||||
|
|
||||||
const CONFIG_DIR = 'config';
|
const CONFIG_DIR = 'config';
|
||||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||||
|
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||||
|
|
||||||
export function makeDefaultOneBotConfig(): OneBotConfig {
|
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||||
return {
|
return {
|
||||||
httpServers: [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
networks: {
|
||||||
httpPostEndpoints: [],
|
httpServers: [{
|
||||||
wsServers: [{ host: '0.0.0.0', port: 3001 }],
|
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: [],
|
wsClients: [],
|
||||||
|
},
|
||||||
musicSignUrl: '',
|
musicSignUrl: '',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function generateAccessToken(): string {
|
||||||
|
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
|
||||||
|
}
|
||||||
|
|
||||||
export function loadOneBotConfig(uin: string): OneBotConfig {
|
export function loadOneBotConfig(uin: string): OneBotConfig {
|
||||||
ensureConfigDir();
|
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 perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||||
const perUinConfig = tryLoadJson(perUinPath);
|
const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH);
|
||||||
if (perUinConfig) {
|
const perUinRaw = tryLoadJson(perUinPath);
|
||||||
deepMerge(merged, perUinConfig);
|
|
||||||
}
|
|
||||||
|
|
||||||
const config = fromJson(merged);
|
// Detect legacy on-disk format (top-level per-type arrays). We auto-migrate
|
||||||
let shouldSave = !perUinConfig;
|
// these entries into `networks.*` and rewrite the file on the next save.
|
||||||
|
const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw);
|
||||||
|
|
||||||
// Persist normalized endpoints and generated keys.
|
const sources: JsonObject[] = [];
|
||||||
merged.httpServers = config.httpServers.map((s) => {
|
if (globalRaw) sources.push(globalRaw);
|
||||||
const out: JsonObject = {
|
if (perUinRaw) sources.push(perUinRaw);
|
||||||
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 ?? '';
|
|
||||||
|
|
||||||
if (shouldSave) {
|
const config = fromJson(sources);
|
||||||
saveJson(perUinPath, merged);
|
|
||||||
}
|
// 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;
|
return config;
|
||||||
}
|
}
|
||||||
@@ -94,8 +78,7 @@ export function loadOneBotConfig(uin: string): OneBotConfig {
|
|||||||
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
|
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
|
||||||
ensureConfigDir();
|
ensureConfigDir();
|
||||||
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
|
||||||
const jsonObj = toJsonObject(config);
|
saveJson(perUinPath, toJsonObject(config));
|
||||||
saveJson(perUinPath, jsonObj);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function ensureConfigDir(): void {
|
function ensureConfigDir(): void {
|
||||||
@@ -103,136 +86,241 @@ function ensureConfigDir(): void {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function toJsonObject(config: OneBotConfig): JsonObject {
|
function toJsonObject(config: OneBotConfig): JsonObject {
|
||||||
|
const nets = config.networks;
|
||||||
return {
|
return {
|
||||||
httpServers: config.httpServers.map((s) => {
|
networks: {
|
||||||
const out: JsonObject = { host: s.host, port: s.port, path: s.path ?? '/', accessToken: s.accessToken ?? '' };
|
httpServers: nets.httpServers.map(httpServerToJson),
|
||||||
if (s.name) out.name = s.name;
|
httpClients: nets.httpClients.map(httpClientToJson),
|
||||||
return out;
|
wsServers: nets.wsServers.map(wsServerToJson),
|
||||||
}),
|
wsClients: nets.wsClients.map(wsClientToJson),
|
||||||
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;
|
|
||||||
}),
|
|
||||||
musicSignUrl: config.musicSignUrl ?? '',
|
musicSignUrl: config.musicSignUrl ?? '',
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function fromJson(json: JsonObject): OneBotConfig {
|
function applyBase(
|
||||||
const httpServers = toHttpServers(json.httpServers);
|
out: JsonObject,
|
||||||
const httpPostEndpoints = toHttpPostEndpoints(json.httpPostEndpoints);
|
n: { name: string; enabled?: boolean; accessToken?: string; messageFormat: MessageFormat; reportSelfMessage: boolean },
|
||||||
const wsServers = toWsServers(json.wsServers);
|
): void {
|
||||||
const wsClients = toWsClients(json.wsClients);
|
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 {
|
return {
|
||||||
httpServers: httpServers.length > 0 ? httpServers : [{ host: '0.0.0.0', port: 3000, path: '/' }],
|
name: asString(value.name),
|
||||||
httpPostEndpoints,
|
enabled: typeof value.enabled === 'boolean' ? value.enabled : undefined,
|
||||||
wsServers: wsServers.length > 0 ? wsServers : [{ host: '0.0.0.0', port: 3001 }],
|
accessToken: asString(value.accessToken) || undefined,
|
||||||
wsClients,
|
messageFormat: parseMessageFormat(value.messageFormat) ?? defaults.messageFormat,
|
||||||
musicSignUrl: typeof json.musicSignUrl === 'string' ? json.musicSignUrl : '',
|
reportSelfMessage:
|
||||||
|
typeof value.reportSelfMessage === 'boolean' ? value.reportSelfMessage : defaults.reportSelfMessage,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
function toHttpServers(value: unknown): HttpServerEndpoint[] {
|
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
|
||||||
if (!Array.isArray(value)) return [];
|
const port = asNumber(value.port, 0);
|
||||||
const result: HttpServerEndpoint[] = [];
|
if (port <= 0) return null;
|
||||||
|
return clean({
|
||||||
for (const item of value) {
|
...parseBase(value, defaults),
|
||||||
if (!isObject(item)) continue;
|
host: asString(value.host, '0.0.0.0'),
|
||||||
const host = asString(item.host, '0.0.0.0');
|
port,
|
||||||
const port = asNumber(item.port, 3000);
|
path: asString(value.path, '/'),
|
||||||
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 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 toHttpPostEndpoints(value: unknown): HttpPostEndpoint[] {
|
function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNetwork | null {
|
||||||
if (!Array.isArray(value)) return [];
|
const port = asNumber(value.port, 0);
|
||||||
const result: HttpPostEndpoint[] = [];
|
if (port <= 0) return null;
|
||||||
|
return clean({
|
||||||
for (const item of value) {
|
...parseBase(value, defaults),
|
||||||
if (!isObject(item)) continue;
|
host: asString(value.host, '0.0.0.0'),
|
||||||
const url = asString(item.url);
|
port,
|
||||||
if (!url) continue;
|
path: asString(value.path, '/'),
|
||||||
const endpoint: HttpPostEndpoint = { url };
|
role: asRole(value.role, 'universal'),
|
||||||
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 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),
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
function toWsServers(value: unknown): WsServerEndpoint[] {
|
function hasLegacyTopLevel(raw: JsonObject): boolean {
|
||||||
if (!Array.isArray(value)) return [];
|
return (
|
||||||
const result: WsServerEndpoint[] = [];
|
Array.isArray(raw.httpServers) ||
|
||||||
|
Array.isArray(raw.httpPostEndpoints) ||
|
||||||
for (const item of value) {
|
Array.isArray(raw.wsServers) ||
|
||||||
if (!isObject(item)) continue;
|
Array.isArray(raw.wsClients) ||
|
||||||
const host = asString(item.host, '0.0.0.0');
|
typeof raw.messageFormat === 'string' ||
|
||||||
const port = asNumber(item.port, 3001);
|
typeof raw.reportSelfMessage === 'boolean'
|
||||||
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 parseMessageFormat(value: unknown): MessageFormat | undefined {
|
||||||
|
if (value === 'array' || value === 'string') return value;
|
||||||
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function toWsClients(value: unknown): WsClientEndpoint[] {
|
function clean<T extends Record<string, unknown>>(obj: T): T {
|
||||||
if (!Array.isArray(value)) return [];
|
for (const key of Object.keys(obj) as (keyof T)[]) {
|
||||||
const result: WsClientEndpoint[] = [];
|
if (obj[key] === undefined) delete obj[key];
|
||||||
|
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
return obj;
|
||||||
return result;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
function asRole(value: unknown, fallback: WsRole): WsRole {
|
function asRole(value: unknown, fallback: WsRole): WsRole {
|
||||||
|
|||||||
@@ -29,12 +29,14 @@ export class EventConverter {
|
|||||||
switch (event.kind) {
|
switch (event.kind) {
|
||||||
case 'friend_message':
|
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 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_);
|
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||||
return {
|
return {
|
||||||
time: event.time,
|
time: event.time,
|
||||||
self_id: selfId,
|
self_id: selfId,
|
||||||
post_type: 'message',
|
post_type: postType,
|
||||||
message_type: 'private',
|
message_type: 'private',
|
||||||
sub_type: 'friend',
|
sub_type: 'friend',
|
||||||
message_id: messageId,
|
message_id: messageId,
|
||||||
@@ -54,12 +56,14 @@ export class EventConverter {
|
|||||||
|
|
||||||
case 'group_message':
|
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 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_);
|
const segments = await elementsToJson(event.elements, true, event.groupId, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||||
return {
|
return {
|
||||||
time: event.time,
|
time: event.time,
|
||||||
self_id: selfId,
|
self_id: selfId,
|
||||||
post_type: 'message',
|
post_type: postType,
|
||||||
message_type: 'group',
|
message_type: 'group',
|
||||||
sub_type: 'normal',
|
sub_type: 'normal',
|
||||||
message_id: messageId,
|
message_id: messageId,
|
||||||
@@ -83,12 +87,14 @@ export class EventConverter {
|
|||||||
|
|
||||||
case 'temp_message':
|
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 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_);
|
const segments = await elementsToJson(event.elements, false, event.senderUin, this.imageUrlResolver_, this.mediaUrlResolver_, this.messageIdResolver_);
|
||||||
return {
|
return {
|
||||||
time: event.time,
|
time: event.time,
|
||||||
self_id: selfId,
|
self_id: selfId,
|
||||||
post_type: 'message',
|
post_type: postType,
|
||||||
message_type: 'private',
|
message_type: 'private',
|
||||||
sub_type: 'group',
|
sub_type: 'group',
|
||||||
message_id: messageId,
|
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 { createLogger } from '../utils/logger';
|
||||||
|
import {
|
||||||
|
buildDispatchPayload,
|
||||||
|
pickDispatchJson,
|
||||||
|
resolveReportOptions,
|
||||||
|
type DispatchPayload,
|
||||||
|
type EventReportOptions,
|
||||||
|
} from './event-filter';
|
||||||
|
|
||||||
export interface HttpPostTransportContext {
|
export interface HttpPostTransportContext {
|
||||||
uin: string;
|
uin: string;
|
||||||
@@ -9,44 +16,57 @@ export interface HttpPostTransportContext {
|
|||||||
const log = createLogger('OneBot.POST');
|
const log = createLogger('OneBot.POST');
|
||||||
const DEFAULT_TIMEOUT_MS = 5000;
|
const DEFAULT_TIMEOUT_MS = 5000;
|
||||||
|
|
||||||
|
interface ResolvedClient {
|
||||||
|
network: HttpClientNetwork;
|
||||||
|
options: EventReportOptions;
|
||||||
|
}
|
||||||
|
|
||||||
export class HttpPostTransport {
|
export class HttpPostTransport {
|
||||||
private readonly context: HttpPostTransportContext;
|
private readonly context: HttpPostTransportContext;
|
||||||
private endpoints: HttpPostEndpoint[] = [];
|
private clients = new Map<string, ResolvedClient>();
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
constructor(config: OneBotConfig, context: HttpPostTransportContext) {
|
||||||
this.endpoints = [...config.httpPostEndpoints];
|
this.clients = resolveClients(config);
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
this.stopped = false;
|
this.stopped = false;
|
||||||
const count = this.endpoints.length;
|
if (this.clients.size > 0) {
|
||||||
if (count > 0) {
|
log.info('configured %d HTTP POST adapter(s): %s', this.clients.size, [...this.clients.keys()].join(', '));
|
||||||
log.info('configured %d HTTP POST endpoint(s)', count);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadConfig(config: OneBotConfig): void {
|
reloadConfig(config: OneBotConfig): void {
|
||||||
this.endpoints = [...config.httpPostEndpoints];
|
this.clients = resolveClients(config);
|
||||||
log.info('reloaded %d HTTP POST endpoint(s)', this.endpoints.length);
|
log.info('reloaded %d HTTP POST adapter(s)', this.clients.size);
|
||||||
}
|
}
|
||||||
|
|
||||||
stop(): void {
|
stop(): void {
|
||||||
this.stopped = true;
|
this.stopped = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
publishEvent(event: JsonObject): void {
|
/**
|
||||||
const endpoints = this.endpoints;
|
* Forward one canonical event to every active HTTP push client.
|
||||||
if (!endpoints || endpoints.length === 0) return;
|
*
|
||||||
|
* 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);
|
const dispatch = payload ?? buildDispatchPayload(event);
|
||||||
for (const endpoint of endpoints) {
|
for (const client of this.clients.values()) {
|
||||||
void this.postEvent(endpoint, payload, event);
|
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;
|
if (this.stopped) return;
|
||||||
|
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
@@ -55,14 +75,14 @@ export class HttpPostTransport {
|
|||||||
'X-Self-ID': this.context.uin,
|
'X-Self-ID': this.context.uin,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (endpoint.accessToken) {
|
if (network.accessToken) {
|
||||||
headers['X-Signature'] = await computeHmacSha1(endpoint.accessToken, payload);
|
headers['X-Signature'] = await computeHmacSha1(network.accessToken, payload);
|
||||||
}
|
}
|
||||||
|
|
||||||
const timeoutMs = endpoint.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
const timeoutMs = network.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(endpoint.url, {
|
const response = await fetch(network.url, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers,
|
headers,
|
||||||
body: payload,
|
body: payload,
|
||||||
@@ -79,11 +99,11 @@ export class HttpPostTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} 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) {
|
} catch (error) {
|
||||||
if (!this.stopped) {
|
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> {
|
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
|
||||||
const { createHmac } = await import('crypto');
|
const { createHmac } = await import('crypto');
|
||||||
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ import {
|
|||||||
type ServerResponse,
|
type ServerResponse,
|
||||||
} from 'http';
|
} from 'http';
|
||||||
import type { ApiHandler } from './api-handler';
|
import type { ApiHandler } from './api-handler';
|
||||||
import type { HttpServerEndpoint, OneBotConfig } from './types';
|
import type { HttpServerNetwork, OneBotConfig } from './types';
|
||||||
import { createLogger } from '../utils/logger';
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
export interface HttpTransportContext {
|
export interface HttpTransportContext {
|
||||||
@@ -14,66 +14,74 @@ export interface HttpTransportContext {
|
|||||||
|
|
||||||
const log = createLogger('OneBot.HTTP');
|
const log = createLogger('OneBot.HTTP');
|
||||||
|
|
||||||
|
interface RunningServer {
|
||||||
|
server: Server;
|
||||||
|
signature: string;
|
||||||
|
network: HttpServerNetwork;
|
||||||
|
}
|
||||||
|
|
||||||
export class HttpTransport {
|
export class HttpTransport {
|
||||||
private readonly context: HttpTransportContext;
|
private readonly context: HttpTransportContext;
|
||||||
private readonly servers = new Map<string, Server>();
|
private readonly servers = new Map<string, RunningServer>();
|
||||||
private endpoints: HttpServerEndpoint[] = [];
|
private networks: HttpServerNetwork[] = [];
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
constructor(config: OneBotConfig, context: HttpTransportContext) {
|
||||||
this.endpoints = [...config.httpServers];
|
this.networks = activeNetworks(config);
|
||||||
this.context = context;
|
this.context = context;
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
for (const endpoint of this.endpoints) this.startEndpoint(endpoint);
|
for (const network of this.networks) this.startEndpoint(network);
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadConfig(config: OneBotConfig): void {
|
reloadConfig(config: OneBotConfig): void {
|
||||||
const nextEndpoints = [...config.httpServers];
|
const nextNetworks = activeNetworks(config);
|
||||||
const nextKeys = new Set(nextEndpoints.map(httpServerKey));
|
const nextByName = new Map(nextNetworks.map((n) => [n.name, n] as const));
|
||||||
|
|
||||||
for (const [key, server] of this.servers) {
|
// Stop adapters that no longer exist or whose binding/auth changed.
|
||||||
if (!nextKeys.has(key)) {
|
for (const [name, running] of [...this.servers]) {
|
||||||
server.close();
|
const next = nextByName.get(name);
|
||||||
this.servers.delete(key);
|
if (!next || httpServerSignature(next) !== running.signature) {
|
||||||
log.info('stopped %s', key);
|
running.server.close();
|
||||||
|
this.servers.delete(name);
|
||||||
|
log.info('stopped [%s]', name);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const endpoint of nextEndpoints) {
|
// (Re)start adapters that aren't running yet.
|
||||||
if (!this.servers.has(httpServerKey(endpoint))) {
|
for (const network of nextNetworks) {
|
||||||
this.startEndpoint(endpoint);
|
if (!this.servers.has(network.name)) {
|
||||||
|
this.startEndpoint(network);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
this.endpoints = nextEndpoints;
|
this.networks = nextNetworks;
|
||||||
}
|
}
|
||||||
|
|
||||||
stop(): void {
|
stop(): void {
|
||||||
for (const server of this.servers.values()) {
|
for (const { server } of this.servers.values()) {
|
||||||
server.close();
|
server.close();
|
||||||
}
|
}
|
||||||
this.servers.clear();
|
this.servers.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
private startEndpoint(endpoint: HttpServerEndpoint): void {
|
private startEndpoint(network: HttpServerNetwork): void {
|
||||||
const expectedPath = normalizePath(endpoint.path ?? '/');
|
const expectedPath = normalizePath(network.path ?? '/');
|
||||||
const endpointToken = endpoint.accessToken ?? '';
|
const endpointToken = network.accessToken ?? '';
|
||||||
const server = createServer((req, res) => {
|
const server = createServer((req, res) => {
|
||||||
void this.handleRequest(expectedPath, endpointToken, req, res);
|
void this.handleRequest(expectedPath, endpointToken, req, res);
|
||||||
});
|
});
|
||||||
|
|
||||||
server.on('listening', () => {
|
server.on('listening', () => {
|
||||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
log.success('[%s] listening %s:%d%s', network.name, network.host ?? '0.0.0.0', network.port, expectedPath);
|
||||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, expectedPath);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
server.on('error', (error) => {
|
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);
|
server.listen(network.port, network.host ?? '0.0.0.0');
|
||||||
this.servers.set(httpServerKey(endpoint), server);
|
this.servers.set(network.name, { server, signature: httpServerSignature(network), network });
|
||||||
}
|
}
|
||||||
|
|
||||||
private async handleRequest(expectedPath: string, accessToken: string, req: IncomingMessage, res: ServerResponse): Promise<void> {
|
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 {
|
function normalizePath(pathValue: string): string {
|
||||||
const path = pathValue.trim() || '/';
|
const path = pathValue.trim() || '/';
|
||||||
if (path === '/') return '/';
|
if (path === '/') return '/';
|
||||||
return path.endsWith('/') ? path.slice(0, -1) : path;
|
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||||
}
|
}
|
||||||
|
|
||||||
function httpServerKey(endpoint: HttpServerEndpoint): string {
|
function httpServerSignature(network: HttpServerNetwork): string {
|
||||||
return `${endpoint.host}:${endpoint.port}${normalizePath(endpoint.path ?? '/')}#${endpoint.accessToken ?? ''}`;
|
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 {
|
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import type { Bridge } from '../bridge/bridge';
|
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 { QQInfo } from '../bridge/qq-info';
|
||||||
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
import type { ApiActionContext, MessageSendResult } from './api-handler';
|
||||||
import { elementsToOneBotSegments } from './event-converter';
|
import { elementsToOneBotSegments } from './event-converter';
|
||||||
@@ -7,6 +7,9 @@ import { MessageStore } from './message-store';
|
|||||||
import { parseMessage } from './message-parser';
|
import { parseMessage } from './message-parser';
|
||||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||||
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
import type { JsonObject, JsonValue, MessageMeta } from './types';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
const log = createLogger('OneBot');
|
||||||
|
|
||||||
export interface InstanceRef {
|
export interface InstanceRef {
|
||||||
uin: string;
|
uin: string;
|
||||||
@@ -414,6 +417,68 @@ async function handleSetEssence(bridge: Bridge, messageStore: MessageStore, mess
|
|||||||
await bridge.setGroupEssence(meta.targetId, meta.sequence, meta.random, enable);
|
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 ---
|
// --- Send message ---
|
||||||
|
|
||||||
async function handleSendPrivate(
|
async function handleSendPrivate(
|
||||||
@@ -423,8 +488,21 @@ async function handleSendPrivate(
|
|||||||
autoEscape: boolean,
|
autoEscape: boolean,
|
||||||
): Promise<MessageSendResult> {
|
): Promise<MessageSendResult> {
|
||||||
const elements = await parseMessage(message, autoEscape, {
|
const elements = await parseMessage(message, autoEscape, {
|
||||||
resolveReplySequence: (replyMessageId) =>
|
resolveReplySequence: (replyMessageId) => {
|
||||||
ref.messageStore.resolveReplySequence(false, userId, 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,
|
musicSignUrl: ref.musicSignUrl,
|
||||||
});
|
});
|
||||||
if (elements.length === 0) throw new Error('message is empty');
|
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 receipt = await ref.bridge.sendPrivateMessage(userId, elements);
|
||||||
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
// Log sent message
|
||||||
|
logSentMessage(false, userId, elements);
|
||||||
|
|
||||||
// Cache the sent message meta
|
// Cache the sent message meta
|
||||||
ref.cacheMessageMeta(messageId, {
|
ref.cacheMessageMeta(messageId, {
|
||||||
isGroup: false,
|
isGroup: false,
|
||||||
@@ -453,8 +534,21 @@ async function handleSendGroup(
|
|||||||
autoEscape: boolean,
|
autoEscape: boolean,
|
||||||
): Promise<MessageSendResult> {
|
): Promise<MessageSendResult> {
|
||||||
const elements = await parseMessage(message, autoEscape, {
|
const elements = await parseMessage(message, autoEscape, {
|
||||||
resolveReplySequence: (replyMessageId) =>
|
resolveReplySequence: (replyMessageId) => {
|
||||||
ref.messageStore.resolveReplySequence(true, groupId, 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,
|
musicSignUrl: ref.musicSignUrl,
|
||||||
});
|
});
|
||||||
if (elements.length === 0) throw new Error('message is empty');
|
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 receipt = await ref.bridge.sendGroupMessage(groupId, elements);
|
||||||
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
// Log sent message
|
||||||
|
logSentMessage(true, groupId, elements);
|
||||||
|
|
||||||
// Cache the sent message meta
|
// Cache the sent message meta
|
||||||
ref.cacheMessageMeta(messageId, {
|
ref.cacheMessageMeta(messageId, {
|
||||||
isGroup: true,
|
isGroup: true,
|
||||||
|
|||||||
@@ -12,6 +12,10 @@ import type { JsonObject, MessageMeta, OneBotConfig } from './types';
|
|||||||
import { HttpTransport } from './http-transport';
|
import { HttpTransport } from './http-transport';
|
||||||
import { HttpPostTransport } from './http-post-transport';
|
import { HttpPostTransport } from './http-post-transport';
|
||||||
import { WsTransport } from './ws-transport';
|
import { WsTransport } from './ws-transport';
|
||||||
|
import { buildDispatchPayload } from './event-filter';
|
||||||
|
import { createLogger } from '../utils/logger';
|
||||||
|
|
||||||
|
const log = createLogger('Event');
|
||||||
|
|
||||||
export class OneBotInstance {
|
export class OneBotInstance {
|
||||||
readonly uin: string;
|
readonly uin: string;
|
||||||
@@ -153,12 +157,75 @@ export class OneBotInstance {
|
|||||||
|
|
||||||
private dispatchEvent(event: JsonObject): void {
|
private dispatchEvent(event: JsonObject): void {
|
||||||
this.cacheMessageEvent(event);
|
this.cacheMessageEvent(event);
|
||||||
this.wsTransport.publishEvent(event);
|
this.logReceivedMessage(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 {
|
||||||
|
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 {
|
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);
|
const messageId = toInt(event.message_id);
|
||||||
if (messageId === 0) return;
|
if (messageId === 0) return;
|
||||||
|
|||||||
@@ -7,6 +7,8 @@ import type { JsonValue, JsonObject } from './types';
|
|||||||
|
|
||||||
export interface ParseMessageOptions {
|
export interface ParseMessageOptions {
|
||||||
resolveReplySequence?: (replyMessageId: number) => number | null;
|
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;
|
musicSignUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,12 +90,25 @@ async function segmentToElement(type: string, data: Record<string, unknown>, opt
|
|||||||
return { type: 'face', faceId: id };
|
return { type: 'face', faceId: id };
|
||||||
}
|
}
|
||||||
case 'at': {
|
case 'at': {
|
||||||
const qq = String(data.qq ?? '');
|
const qq = String(data.qq ?? '').trim();
|
||||||
if (qq === 'all') {
|
if (qq === 'all') {
|
||||||
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
|
||||||
}
|
}
|
||||||
const uin = parseInt(qq, 10);
|
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': {
|
case 'reply': {
|
||||||
const id = parseInt(String(data.id ?? '0'), 10);
|
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) {
|
if (options?.resolveReplySequence) {
|
||||||
const resolved = options.resolveReplySequence(id);
|
const resolved = options.resolveReplySequence(id);
|
||||||
if (typeof resolved === 'number' && resolved > 0) {
|
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 {
|
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
|
||||||
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) return null;
|
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
|
||||||
const row = this.db.prepare(
|
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
|
`SELECT sequence
|
||||||
FROM messages
|
FROM messages
|
||||||
WHERE is_group = ? AND session_id = ? AND message_hash = ?
|
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
|
||||||
LIMIT 1`
|
LIMIT 1`
|
||||||
).get(isGroup ? 1 : 0, sessionId, messageId) as { sequence: number } | undefined;
|
).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;
|
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
return row.sequence;
|
return row.sequence;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,47 +19,72 @@ export interface OneBotRequest {
|
|||||||
echo?: JsonValue;
|
echo?: JsonValue;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WsServerEndpoint {
|
export type WsRole = 'api' | 'event' | 'universal';
|
||||||
name?: string;
|
|
||||||
host: string;
|
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;
|
port: number;
|
||||||
path?: string;
|
path?: string;
|
||||||
role?: WsRole;
|
|
||||||
accessToken?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HttpServerEndpoint {
|
export interface HttpClientNetwork extends NetworkBase {
|
||||||
name?: string;
|
|
||||||
host: string;
|
|
||||||
port: number;
|
|
||||||
path?: string;
|
|
||||||
accessToken?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WsClientEndpoint {
|
|
||||||
name?: string;
|
|
||||||
url: string;
|
url: string;
|
||||||
role?: WsRole;
|
|
||||||
reconnectIntervalMs?: number;
|
|
||||||
accessToken?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HttpPostEndpoint {
|
|
||||||
name?: string;
|
|
||||||
url: string;
|
|
||||||
accessToken?: string;
|
|
||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface OneBotConfig {
|
export interface WsServerNetwork extends NetworkBase {
|
||||||
httpServers: HttpServerEndpoint[];
|
host?: string;
|
||||||
httpPostEndpoints: HttpPostEndpoint[];
|
port: number;
|
||||||
wsServers: WsServerEndpoint[];
|
path?: string;
|
||||||
wsClients: WsClientEndpoint[];
|
role?: WsRole;
|
||||||
musicSignUrl?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 {
|
export interface MessageMeta {
|
||||||
isGroup: boolean;
|
isGroup: boolean;
|
||||||
|
|||||||
@@ -1,20 +1,44 @@
|
|||||||
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
|
||||||
import type { IncomingMessage } from 'http';
|
import type { IncomingMessage } from 'http';
|
||||||
import type { ApiHandler } from './api-handler';
|
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 { createLogger } from '../utils/logger';
|
||||||
|
import {
|
||||||
|
buildDispatchPayload,
|
||||||
|
pickDispatchJson,
|
||||||
|
resolveReportOptions,
|
||||||
|
shapeEventForAdapter,
|
||||||
|
type DispatchPayload,
|
||||||
|
type EventReportOptions,
|
||||||
|
} from './event-filter';
|
||||||
|
|
||||||
interface ForwardConnection {
|
interface ForwardConnection {
|
||||||
socket: WebSocket;
|
socket: WebSocket;
|
||||||
role: WsRole;
|
role: WsRole;
|
||||||
|
options: EventReportOptions;
|
||||||
|
serverName: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface ReverseConnection {
|
interface ReverseConnection {
|
||||||
socket: WebSocket;
|
socket: WebSocket;
|
||||||
role: WsRole;
|
role: WsRole;
|
||||||
|
options: EventReportOptions;
|
||||||
endpointUrl: string;
|
endpointUrl: string;
|
||||||
reconnectIntervalMs: number;
|
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 {
|
export interface WsTransportContext {
|
||||||
@@ -29,143 +53,192 @@ const log = createLogger('OneBot.WS');
|
|||||||
export class WsTransport {
|
export class WsTransport {
|
||||||
private readonly context: WsTransportContext;
|
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 forwardConnections = new Map<WebSocket, ForwardConnection>();
|
||||||
private readonly reverseConnections = new Set<ReverseConnection>();
|
private readonly reverseConnections = new Map<string, ReverseConnection>();
|
||||||
private readonly reconnectTimers = new Set<NodeJS.Timeout>();
|
private readonly reconnectTimers = new Map<string, NodeJS.Timeout>();
|
||||||
private readonly reconnectTimersByKey = new Map<string, NodeJS.Timeout>();
|
private serverNetworks: WsServerNetwork[] = [];
|
||||||
private readonly activeReverseClientKeys = new Set<string>();
|
private clientNetworks: WsClientNetwork[] = [];
|
||||||
private serverEndpoints: WsServerEndpoint[] = [];
|
|
||||||
private clientEndpoints: WsClientEndpoint[] = [];
|
|
||||||
private desiredClientKeys = new Set<string>();
|
|
||||||
private stopped = false;
|
private stopped = false;
|
||||||
|
|
||||||
constructor(config: OneBotConfig, context: WsTransportContext) {
|
constructor(config: OneBotConfig, context: WsTransportContext) {
|
||||||
this.serverEndpoints = [...config.wsServers];
|
this.serverNetworks = activeServers(config);
|
||||||
this.clientEndpoints = [...config.wsClients];
|
this.clientNetworks = activeClients(config);
|
||||||
this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey));
|
|
||||||
this.context = context;
|
this.context = context;
|
||||||
|
for (const network of this.clientNetworks) {
|
||||||
|
this.clientStates.set(network.name, {
|
||||||
|
network,
|
||||||
|
signature: wsClientSignature(network),
|
||||||
|
options: resolveReportOptions(network),
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
start(): void {
|
start(): void {
|
||||||
this.stopped = false;
|
this.stopped = false;
|
||||||
this.desiredClientKeys = new Set(this.clientEndpoints.map(wsClientKey));
|
for (const network of this.serverNetworks) this.startServerEndpoint(network);
|
||||||
this.startServers();
|
for (const network of this.clientNetworks) this.startClientEndpoint(network.name);
|
||||||
this.startReverseClients();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
reloadConfig(config: OneBotConfig): void {
|
reloadConfig(config: OneBotConfig): void {
|
||||||
const nextServers = [...config.wsServers];
|
const nextServers = activeServers(config);
|
||||||
const nextClients = [...config.wsClients];
|
const nextClients = activeClients(config);
|
||||||
const nextServerKeys = new Set(nextServers.map(wsServerKey));
|
const nextServerByName = new Map(nextServers.map((n) => [n.name, n] as const));
|
||||||
const nextClientKeys = new Set(nextClients.map(wsClientKey));
|
const nextClientByName = new Map(nextClients.map((n) => [n.name, n] as const));
|
||||||
this.desiredClientKeys = nextClientKeys;
|
|
||||||
|
|
||||||
for (const [key, server] of this.servers) {
|
// --- WS Servers ---
|
||||||
if (!nextServerKeys.has(key)) {
|
for (const [name, running] of [...this.servers]) {
|
||||||
server.close();
|
const next = nextServerByName.get(name);
|
||||||
this.servers.delete(key);
|
if (!next || wsServerSignature(next) !== running.signature) {
|
||||||
log.info('stopped forward server %s', key);
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
for (const endpoint of nextServers) {
|
// --- WS Clients (reverse) ---
|
||||||
if (!this.servers.has(wsServerKey(endpoint))) {
|
for (const [name, state] of [...this.clientStates]) {
|
||||||
this.startServerEndpoint(endpoint);
|
const next = nextClientByName.get(name);
|
||||||
}
|
const sig = next ? wsClientSignature(next) : null;
|
||||||
}
|
if (!next || sig !== state.signature) {
|
||||||
|
const conn = this.reverseConnections.get(name);
|
||||||
for (const conn of [...this.reverseConnections]) {
|
if (conn) {
|
||||||
if (!nextClientKeys.has(conn.key)) {
|
|
||||||
this.clearReconnectTimer(conn.key);
|
|
||||||
this.activeReverseClientKeys.delete(conn.key);
|
|
||||||
safeClose(conn.socket);
|
safeClose(conn.socket);
|
||||||
this.reverseConnections.delete(conn);
|
this.reverseConnections.delete(name);
|
||||||
log.info('stopped reverse client %s', conn.endpointUrl);
|
}
|
||||||
|
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 nextClients) {
|
this.serverNetworks = nextServers;
|
||||||
const key = wsClientKey(endpoint);
|
this.clientNetworks = nextClients;
|
||||||
if (!this.activeReverseClientKeys.has(key) && !this.reconnectTimersByKey.has(key)) {
|
|
||||||
this.startClientEndpoint(endpoint);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.serverEndpoints = nextServers;
|
|
||||||
this.clientEndpoints = nextClients;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stop(): void {
|
stop(): void {
|
||||||
this.stopped = true;
|
// Final lifecycle broadcast before we mark ourselves stopped.
|
||||||
this.desiredClientKeys.clear();
|
|
||||||
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
this.publishEvent(this.context.buildLifecycleEvent('disable'));
|
||||||
|
this.stopped = true;
|
||||||
|
|
||||||
for (const timer of this.reconnectTimers) {
|
for (const timer of this.reconnectTimers.values()) {
|
||||||
clearTimeout(timer);
|
clearTimeout(timer);
|
||||||
}
|
}
|
||||||
this.reconnectTimers.clear();
|
this.reconnectTimers.clear();
|
||||||
this.reconnectTimersByKey.clear();
|
|
||||||
this.activeReverseClientKeys.clear();
|
|
||||||
|
|
||||||
for (const [socket] of this.forwardConnections) {
|
for (const socket of this.forwardConnections.keys()) {
|
||||||
safeClose(socket);
|
safeClose(socket);
|
||||||
}
|
}
|
||||||
this.forwardConnections.clear();
|
this.forwardConnections.clear();
|
||||||
|
|
||||||
for (const conn of this.reverseConnections) {
|
for (const conn of this.reverseConnections.values()) {
|
||||||
safeClose(conn.socket);
|
safeClose(conn.socket);
|
||||||
}
|
}
|
||||||
this.reverseConnections.clear();
|
this.reverseConnections.clear();
|
||||||
|
|
||||||
for (const server of this.servers.values()) {
|
for (const { wss } of this.servers.values()) {
|
||||||
server.close();
|
wss.close();
|
||||||
}
|
}
|
||||||
this.servers.clear();
|
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()) {
|
for (const conn of this.forwardConnections.values()) {
|
||||||
if (role === 'event' || role === 'universal') {
|
if (conn.role !== 'event' && conn.role !== 'universal') continue;
|
||||||
safeSend(socket, payload);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
for (const { socket, role } of this.reverseConnections.values()) {
|
private startServerEndpoint(network: WsServerNetwork): void {
|
||||||
if (role === 'event' || role === 'universal') {
|
|
||||||
safeSend(socket, payload);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private startServers(): void {
|
|
||||||
for (const endpoint of this.serverEndpoints) {
|
|
||||||
this.startServerEndpoint(endpoint);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private startServerEndpoint(endpoint: WsServerEndpoint): void {
|
|
||||||
const wss = new WebSocketServer({
|
const wss = new WebSocketServer({
|
||||||
host: endpoint.host,
|
host: network.host ?? '0.0.0.0',
|
||||||
port: endpoint.port,
|
port: network.port,
|
||||||
path: endpoint.path ?? '/',
|
path: network.path ?? '/',
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const running: RunningWsServer = {
|
||||||
|
wss,
|
||||||
|
signature: wsServerSignature(network),
|
||||||
|
network,
|
||||||
|
options: resolveReportOptions(network),
|
||||||
|
};
|
||||||
|
this.servers.set(network.name, running);
|
||||||
|
|
||||||
wss.on('listening', () => {
|
wss.on('listening', () => {
|
||||||
const label = endpoint.name ? `[${endpoint.name}] ` : '';
|
log.success('[%s] listening %s:%d%s', network.name, network.host ?? '0.0.0.0', network.port, network.path ?? '/');
|
||||||
log.success('%slistening %s:%d%s', label, endpoint.host, endpoint.port, endpoint.path ?? '/');
|
|
||||||
});
|
});
|
||||||
|
|
||||||
wss.on('connection', (socket, request) => {
|
wss.on('connection', (socket, request) => {
|
||||||
if (!isAuthorized(request, endpoint.accessToken ?? '')) {
|
if (!isAuthorized(request, running.network.accessToken ?? '')) {
|
||||||
safeClose(socket, 1008, 'invalid access token');
|
safeClose(socket, 1008, 'invalid access token');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const role = endpoint.role ?? classifyForwardRole(request);
|
const role = running.network.role ?? classifyForwardRole(request);
|
||||||
const conn: ForwardConnection = { socket, role };
|
const conn: ForwardConnection = {
|
||||||
|
socket,
|
||||||
|
role,
|
||||||
|
options: running.options,
|
||||||
|
serverName: running.network.name,
|
||||||
|
};
|
||||||
this.forwardConnections.set(socket, conn);
|
this.forwardConnections.set(socket, conn);
|
||||||
|
|
||||||
socket.on('message', (raw: Buffer) => {
|
socket.on('message', (raw: Buffer) => {
|
||||||
@@ -177,56 +250,45 @@ export class WsTransport {
|
|||||||
});
|
});
|
||||||
|
|
||||||
socket.on('error', (error: Error) => {
|
socket.on('error', (error: Error) => {
|
||||||
log.warn('forward socket error: %s', error instanceof Error ? error.message : String(error));
|
log.warn('[%s] forward socket error: %s', running.network.name, error instanceof Error ? error.message : String(error));
|
||||||
});
|
});
|
||||||
|
|
||||||
this.sendBootstrapMetaEvents(socket, role);
|
this.sendBootstrapMetaEvents(socket, role, conn.options);
|
||||||
});
|
});
|
||||||
|
|
||||||
wss.on('error', (error: Error) => {
|
wss.on('error', (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));
|
||||||
});
|
});
|
||||||
|
|
||||||
this.servers.set(wsServerKey(endpoint), wss);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private startReverseClients(): void {
|
private startClientEndpoint(name: string): void {
|
||||||
for (const endpoint of this.clientEndpoints) this.startClientEndpoint(endpoint);
|
const state = this.clientStates.get(name);
|
||||||
}
|
if (!state || this.stopped) return;
|
||||||
|
if (this.reverseConnections.has(name) || this.reconnectTimers.has(name)) return;
|
||||||
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);
|
|
||||||
|
|
||||||
|
const network = state.network;
|
||||||
|
const role = network.role ?? 'universal';
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
'User-Agent': 'OneBot',
|
'User-Agent': 'OneBot',
|
||||||
'X-Self-ID': this.context.uin,
|
'X-Self-ID': this.context.uin,
|
||||||
'X-Client-Role': role,
|
'X-Client-Role': role,
|
||||||
};
|
};
|
||||||
|
if (network.accessToken) headers.Authorization = `Bearer ${network.accessToken}`;
|
||||||
|
|
||||||
if (accessToken) {
|
const socket = new WebSocket(network.url, { headers });
|
||||||
headers.Authorization = `Bearer ${accessToken}`;
|
const conn: ReverseConnection = {
|
||||||
}
|
socket,
|
||||||
|
role,
|
||||||
const socket = new WebSocket(endpointUrl, { headers });
|
options: state.options,
|
||||||
const conn: ReverseConnection = { socket, role, endpointUrl, reconnectIntervalMs, key: connKey };
|
endpointUrl: network.url,
|
||||||
this.reverseConnections.add(conn);
|
reconnectIntervalMs: Math.max(1000, network.reconnectIntervalMs ?? 5000),
|
||||||
|
name,
|
||||||
|
};
|
||||||
|
this.reverseConnections.set(name, conn);
|
||||||
|
|
||||||
socket.on('open', () => {
|
socket.on('open', () => {
|
||||||
const label = name ? `[${name}] ` : '';
|
log.info('[%s] reverse connected %s', name, network.url);
|
||||||
log.info('%sreverse connected %s', label, endpointUrl);
|
this.sendBootstrapMetaEvents(socket, role, state.options);
|
||||||
this.sendBootstrapMetaEvents(socket, role);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('message', (raw: Buffer) => {
|
socket.on('message', (raw: Buffer) => {
|
||||||
@@ -234,36 +296,25 @@ export class WsTransport {
|
|||||||
});
|
});
|
||||||
|
|
||||||
socket.on('close', () => {
|
socket.on('close', () => {
|
||||||
this.reverseConnections.delete(conn);
|
this.reverseConnections.delete(name);
|
||||||
this.activeReverseClientKeys.delete(connKey);
|
|
||||||
if (this.stopped) return;
|
if (this.stopped) return;
|
||||||
if (!this.desiredClientKeys.has(connKey)) return;
|
if (!this.clientStates.has(name)) return;
|
||||||
if (this.reconnectTimersByKey.has(connKey)) return;
|
if (this.reconnectTimers.has(name)) return;
|
||||||
|
|
||||||
const timer = setTimeout(() => {
|
const timer = setTimeout(() => {
|
||||||
this.reconnectTimers.delete(timer);
|
this.reconnectTimers.delete(name);
|
||||||
this.reconnectTimersByKey.delete(connKey);
|
if (this.stopped || !this.clientStates.has(name)) return;
|
||||||
if (this.stopped || !this.desiredClientKeys.has(connKey)) return;
|
this.startClientEndpoint(name);
|
||||||
this.connectReverseClient(endpointUrl, role, reconnectIntervalMs, accessToken, name, connKey);
|
}, conn.reconnectIntervalMs);
|
||||||
}, reconnectIntervalMs);
|
|
||||||
timer.unref?.();
|
timer.unref?.();
|
||||||
this.reconnectTimers.add(timer);
|
this.reconnectTimers.set(name, timer);
|
||||||
this.reconnectTimersByKey.set(connKey, timer);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
socket.on('error', (error: Error) => {
|
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> {
|
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
|
||||||
if (role !== 'api' && role !== 'universal') return;
|
if (role !== 'api' && role !== 'universal') return;
|
||||||
|
|
||||||
@@ -274,16 +325,19 @@ export class WsTransport {
|
|||||||
safeSend(socket, response);
|
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;
|
if (role !== 'event' && role !== 'universal') return;
|
||||||
|
|
||||||
const connectEvent = this.context.buildLifecycleEvent('connect');
|
const events = [
|
||||||
const enableEvent = this.context.buildLifecycleEvent('enable');
|
this.context.buildLifecycleEvent('connect'),
|
||||||
const heartbeatEvent = this.context.buildHeartbeatEvent();
|
this.context.buildLifecycleEvent('enable'),
|
||||||
|
this.context.buildHeartbeatEvent(),
|
||||||
safeSend(socket, JSON.stringify(connectEvent));
|
];
|
||||||
safeSend(socket, JSON.stringify(enableEvent));
|
for (const event of events) {
|
||||||
safeSend(socket, JSON.stringify(heartbeatEvent));
|
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;
|
return path.endsWith('/') ? path.slice(0, -1) : path;
|
||||||
}
|
}
|
||||||
|
|
||||||
function wsServerKey(endpoint: WsServerEndpoint): string {
|
function activeServers(config: OneBotConfig): WsServerNetwork[] {
|
||||||
return `${endpoint.host}:${endpoint.port}${normalizeWsPath(endpoint.path)}#${endpoint.role ?? 'auto'}#${endpoint.accessToken ?? ''}`;
|
return config.networks.wsServers.filter((n) => n.enabled !== false);
|
||||||
}
|
}
|
||||||
|
|
||||||
function wsClientPartsKey(endpointUrl: string, role: WsRole, reconnectIntervalMs: number, accessToken: string): string {
|
function activeClients(config: OneBotConfig): WsClientNetwork[] {
|
||||||
return `${endpointUrl}#${role}#${reconnectIntervalMs}#${accessToken}`;
|
return config.networks.wsClients.filter((n) => n.enabled !== false && !!n.url);
|
||||||
}
|
}
|
||||||
|
|
||||||
function wsClientKey(endpoint: WsClientEndpoint): string {
|
function wsServerSignature(network: WsServerNetwork): string {
|
||||||
const role = endpoint.role ?? 'universal';
|
return `${network.host ?? '0.0.0.0'}:${network.port}${normalizeWsPath(network.path)}#${network.role ?? 'auto'}#${network.accessToken ?? ''}`;
|
||||||
const reconnectIntervalMs = Math.max(1000, endpoint.reconnectIntervalMs ?? 5000);
|
}
|
||||||
return wsClientPartsKey(endpoint.url, role, reconnectIntervalMs, endpoint.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 {
|
function isAuthorized(request: IncomingMessage, token: string): boolean {
|
||||||
|
|||||||
@@ -10,6 +10,17 @@ const SCRYPT_N = 16384; // cost
|
|||||||
const SCRYPT_R = 8;
|
const SCRYPT_R = 8;
|
||||||
const SCRYPT_P = 1;
|
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 {
|
export interface WebuiAuthState {
|
||||||
passwordHash: string; // hex
|
passwordHash: string; // hex
|
||||||
passwordSalt: string; // hex
|
passwordSalt: string; // hex
|
||||||
@@ -89,20 +100,35 @@ function atomicWrite(state: WebuiAuthState): void {
|
|||||||
export class WebuiAuth {
|
export class WebuiAuth {
|
||||||
private state: WebuiAuthState;
|
private state: WebuiAuthState;
|
||||||
private initialPlain: string | null;
|
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.state = state;
|
||||||
this.initialPlain = initialPlain;
|
this.initialPlain = initialPlain;
|
||||||
|
this.devMode = devMode;
|
||||||
}
|
}
|
||||||
|
|
||||||
static load(): WebuiAuth {
|
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();
|
ensureConfigDir();
|
||||||
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
if (fs.existsSync(WEBUI_CONFIG_PATH)) {
|
||||||
try {
|
try {
|
||||||
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8');
|
||||||
const parsed = JSON.parse(raw) as unknown;
|
const parsed = JSON.parse(raw) as unknown;
|
||||||
if (isValidState(parsed)) {
|
if (isValidState(parsed)) {
|
||||||
return new WebuiAuth(parsed, null);
|
return new WebuiAuth(parsed, null, false);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
/* fallthrough — regenerate */
|
/* fallthrough — regenerate */
|
||||||
@@ -111,7 +137,17 @@ export class WebuiAuth {
|
|||||||
const initialPassword = randomBytes(8).toString('hex');
|
const initialPassword = randomBytes(8).toString('hex');
|
||||||
const state = generateInitialState(initialPassword);
|
const state = generateInitialState(initialPassword);
|
||||||
atomicWrite(state);
|
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. */
|
/** 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.
|
* After success, mustChangePassword=false and the file is rewritten on disk.
|
||||||
*/
|
*/
|
||||||
setPassword(newPassword: string): void {
|
setPassword(newPassword: string): void {
|
||||||
|
if (this.devMode) {
|
||||||
|
throw new Error('开发模式 (SNOWLUMA_DEV_MODE=1) 已禁用密码修改');
|
||||||
|
}
|
||||||
if (!isStrongPassword(newPassword)) {
|
if (!isStrongPassword(newPassword)) {
|
||||||
throw new Error('密码不符合强度要求');
|
throw new Error('密码不符合强度要求');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,13 +11,9 @@ import path from 'path';
|
|||||||
import { existsSync, readFileSync } from 'fs';
|
import { existsSync, readFileSync } from 'fs';
|
||||||
import { fileURLToPath } from 'url';
|
import { fileURLToPath } from 'url';
|
||||||
import os from 'os';
|
import os from 'os';
|
||||||
import { exec } from 'child_process';
|
|
||||||
import { promisify } from 'util';
|
|
||||||
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
|
import { WebuiAuth, evaluatePasswordRules, isStrongPassword } from './auth';
|
||||||
import { findAvailablePort } from './port';
|
import { findAvailablePort } from './port';
|
||||||
|
|
||||||
const execAsync = promisify(exec);
|
|
||||||
|
|
||||||
const log = createLogger('WebUI');
|
const log = createLogger('WebUI');
|
||||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
@@ -81,7 +77,14 @@ export async function initWebUI(
|
|||||||
): Promise<{ port: number }> {
|
): Promise<{ port: number }> {
|
||||||
const auth = WebuiAuth.load();
|
const auth = WebuiAuth.load();
|
||||||
const initialPassword = auth.takeInitialPassword();
|
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('=========================================');
|
||||||
log.info('WebUI 安全认证(首次启动,已生成临时密码)');
|
log.info('WebUI 安全认证(首次启动,已生成临时密码)');
|
||||||
log.info('默认用户: admin');
|
log.info('默认用户: admin');
|
||||||
@@ -269,67 +272,13 @@ export async function initWebUI(
|
|||||||
return usage;
|
return usage;
|
||||||
}
|
}
|
||||||
|
|
||||||
let cachedGpu: { name: string; vendor: string }[] | null = null;
|
app.get('/api/system', (c) => {
|
||||||
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) => {
|
|
||||||
const cpus = os.cpus();
|
const cpus = os.cpus();
|
||||||
const usage = sampleCpuLoad();
|
const usage = sampleCpuLoad();
|
||||||
const totalMem = os.totalmem();
|
const totalMem = os.totalmem();
|
||||||
const freeMem = os.freemem();
|
const freeMem = os.freemem();
|
||||||
const usedMem = totalMem - freeMem;
|
const usedMem = totalMem - freeMem;
|
||||||
const gpus = await detectGpus().catch(() => []);
|
const runtimeMemory = process.memoryUsage();
|
||||||
return c.json({
|
return c.json({
|
||||||
hostname: os.hostname(),
|
hostname: os.hostname(),
|
||||||
platform: os.platform(),
|
platform: os.platform(),
|
||||||
@@ -352,7 +301,14 @@ export async function initWebUI(
|
|||||||
used: usedMem,
|
used: usedMem,
|
||||||
usagePercent: totalMem ? (usedMem / totalMem) * 100 : 0,
|
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,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,16 +1,151 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
|
||||||
import { loadOneBotConfig, makeDefaultOneBotConfig } from '../src/onebot/config';
|
import fs from 'fs';
|
||||||
|
import os from 'os';
|
||||||
|
import path from 'path';
|
||||||
|
import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/onebot/config';
|
||||||
|
|
||||||
|
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
||||||
|
|
||||||
describe('makeDefaultOneBotConfig', () => {
|
describe('makeDefaultOneBotConfig', () => {
|
||||||
it('returns default config structure', () => {
|
it('returns default unified networks structure', () => {
|
||||||
const config = makeDefaultOneBotConfig();
|
const config = makeDefaultOneBotConfig();
|
||||||
expect(config.httpServers).toHaveLength(1);
|
expect(config.networks.httpServers).toHaveLength(1);
|
||||||
expect(config.httpServers[0].host).toBe('0.0.0.0');
|
expect(config.networks.httpServers[0].name).toBe('http-default');
|
||||||
expect(config.httpServers[0].port).toBe(3000);
|
expect(config.networks.httpServers[0].host).toBe('0.0.0.0');
|
||||||
expect(config.httpPostEndpoints).toEqual([]);
|
expect(config.networks.httpServers[0].port).toBe(3000);
|
||||||
expect(config.wsServers).toHaveLength(1);
|
expect(config.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||||
expect(config.wsServers[0].port).toBe(3001);
|
expect(config.networks.httpServers[0].messageFormat).toBe('array');
|
||||||
expect(config.wsClients).toEqual([]);
|
expect(config.networks.httpServers[0].reportSelfMessage).toBe(false);
|
||||||
|
expect(config.networks.httpClients).toEqual([]);
|
||||||
|
expect(config.networks.wsServers).toHaveLength(1);
|
||||||
|
expect(config.networks.wsServers[0].port).toBe(3001);
|
||||||
|
expect(config.networks.wsServers[0].role).toBe('universal');
|
||||||
|
expect(config.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||||
|
expect(config.networks.wsServers[0].messageFormat).toBe('array');
|
||||||
|
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
|
||||||
|
expect(config.networks.wsClients).toEqual([]);
|
||||||
expect(config.musicSignUrl).toBe('');
|
expect(config.musicSignUrl).toBe('');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('loadOneBotConfig', () => {
|
||||||
|
let tempDir: string;
|
||||||
|
let prevCwd: string;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-config-'));
|
||||||
|
prevCwd = process.cwd();
|
||||||
|
process.chdir(tempDir);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
process.chdir(prevCwd);
|
||||||
|
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('creates and persists default config when none exists', () => {
|
||||||
|
const uin = '10001';
|
||||||
|
const config = loadOneBotConfig(uin);
|
||||||
|
expect(config.networks.httpServers).toHaveLength(1);
|
||||||
|
|
||||||
|
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
|
||||||
|
expect(onDisk.networks).toBeDefined();
|
||||||
|
expect(Array.isArray(onDisk.networks.httpServers)).toBe(true);
|
||||||
|
expect(onDisk.networks.httpServers[0].name).toBe('http-default');
|
||||||
|
expect(onDisk.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||||
|
expect(onDisk.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
|
||||||
|
// Legacy keys must not appear in the persisted file.
|
||||||
|
expect(onDisk.httpServers).toBeUndefined();
|
||||||
|
expect(onDisk.wsServers).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('migrates legacy per-type arrays into networks groups', () => {
|
||||||
|
const uin = '10002';
|
||||||
|
const dir = path.join(tempDir, 'config');
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
const legacy = {
|
||||||
|
httpServers: [{ host: '0.0.0.0', port: 3100, path: '/', accessToken: 'tok' }],
|
||||||
|
httpPostEndpoints: [{ name: 'main-bot', url: 'http://127.0.0.1:5700' }],
|
||||||
|
wsServers: [{ host: '0.0.0.0', port: 3101 }],
|
||||||
|
wsClients: [{ url: 'ws://127.0.0.1:8080' }],
|
||||||
|
musicSignUrl: 'https://example.com/sign',
|
||||||
|
messageFormat: 'string',
|
||||||
|
reportSelfMessage: true,
|
||||||
|
};
|
||||||
|
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
|
||||||
|
|
||||||
|
const config = loadOneBotConfig(uin);
|
||||||
|
expect(config.networks.httpServers).toHaveLength(1);
|
||||||
|
expect(config.networks.httpServers[0].port).toBe(3100);
|
||||||
|
expect(config.networks.httpServers[0].accessToken).toBe('tok');
|
||||||
|
expect(config.networks.httpServers[0].messageFormat).toBe('string');
|
||||||
|
expect(config.networks.httpServers[0].reportSelfMessage).toBe(true);
|
||||||
|
|
||||||
|
expect(config.networks.httpClients).toHaveLength(1);
|
||||||
|
expect(config.networks.httpClients[0].name).toBe('main-bot');
|
||||||
|
expect(config.networks.httpClients[0].url).toBe('http://127.0.0.1:5700');
|
||||||
|
expect(config.networks.httpClients[0].messageFormat).toBe('string');
|
||||||
|
expect(config.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||||
|
|
||||||
|
expect(config.networks.wsServers).toHaveLength(1);
|
||||||
|
expect(config.networks.wsServers[0].port).toBe(3101);
|
||||||
|
expect(config.networks.wsServers[0].messageFormat).toBe('string');
|
||||||
|
expect(config.networks.wsServers[0].reportSelfMessage).toBe(true);
|
||||||
|
|
||||||
|
expect(config.networks.wsClients).toHaveLength(1);
|
||||||
|
expect(config.networks.wsClients[0].url).toBe('ws://127.0.0.1:8080');
|
||||||
|
expect(config.networks.wsClients[0].messageFormat).toBe('string');
|
||||||
|
expect(config.networks.wsClients[0].reportSelfMessage).toBe(true);
|
||||||
|
|
||||||
|
expect(config.musicSignUrl).toBe('https://example.com/sign');
|
||||||
|
|
||||||
|
// File should now be in unified format on disk.
|
||||||
|
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8'));
|
||||||
|
expect(onDisk.networks).toBeDefined();
|
||||||
|
expect(onDisk.httpServers).toBeUndefined();
|
||||||
|
expect(onDisk.httpPostEndpoints).toBeUndefined();
|
||||||
|
expect(onDisk.messageFormat).toBeUndefined();
|
||||||
|
expect(onDisk.reportSelfMessage).toBeUndefined();
|
||||||
|
expect(onDisk.networks.httpServers[0].messageFormat).toBe('string');
|
||||||
|
expect(onDisk.networks.httpServers[0].reportSelfMessage).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('round-trips per-adapter overrides through save/load', () => {
|
||||||
|
const uin = '10003';
|
||||||
|
const config = makeDefaultOneBotConfig();
|
||||||
|
config.networks.httpClients.push({
|
||||||
|
name: 'self-mirror',
|
||||||
|
url: 'http://127.0.0.1:9000',
|
||||||
|
messageFormat: 'string',
|
||||||
|
reportSelfMessage: true,
|
||||||
|
});
|
||||||
|
saveOneBotConfig(uin, config);
|
||||||
|
|
||||||
|
const reloaded = loadOneBotConfig(uin);
|
||||||
|
expect(reloaded.networks.httpClients).toHaveLength(1);
|
||||||
|
expect(reloaded.networks.httpClients[0].name).toBe('self-mirror');
|
||||||
|
expect(reloaded.networks.httpClients[0].messageFormat).toBe('string');
|
||||||
|
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('auto-generates names for legacy entries that lack one', () => {
|
||||||
|
const uin = '10004';
|
||||||
|
const dir = path.join(tempDir, 'config');
|
||||||
|
fs.mkdirSync(dir, { recursive: true });
|
||||||
|
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
|
||||||
|
httpServers: [
|
||||||
|
{ port: 3000 },
|
||||||
|
{ port: 3001 },
|
||||||
|
],
|
||||||
|
}), 'utf8');
|
||||||
|
|
||||||
|
const config = loadOneBotConfig(uin);
|
||||||
|
const names = config.networks.httpServers.map((n) => n.name);
|
||||||
|
expect(names).toHaveLength(2);
|
||||||
|
expect(new Set(names).size).toBe(2); // unique
|
||||||
|
expect(names.every((n) => n.length > 0)).toBe(true);
|
||||||
|
expect(config.networks.httpServers.every((n) => n.messageFormat === 'array')).toBe(true);
|
||||||
|
expect(config.networks.httpServers.every((n) => n.reportSelfMessage === false)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
@@ -0,0 +1,244 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import { EventConverter } from '../src/onebot/event-converter';
|
||||||
|
import {
|
||||||
|
buildDispatchPayload,
|
||||||
|
pickDispatchJson,
|
||||||
|
resolveReportOptions,
|
||||||
|
shapeEventForAdapter,
|
||||||
|
} from '../src/onebot/event-filter';
|
||||||
|
import type { FriendMessage, GroupMessage, TempMessage } from '../src/bridge/events';
|
||||||
|
|
||||||
|
const SELF_UIN = '10001';
|
||||||
|
const SELF_ID = 10001;
|
||||||
|
const PEER_UIN = 22222;
|
||||||
|
|
||||||
|
function makeFriendMessage(senderUin: number): FriendMessage {
|
||||||
|
return {
|
||||||
|
kind: 'friend_message',
|
||||||
|
time: 1700000000,
|
||||||
|
selfUin: SELF_ID,
|
||||||
|
senderUin,
|
||||||
|
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||||
|
msgSeq: 1,
|
||||||
|
msgId: 1,
|
||||||
|
elements: [{ type: 'text', text: 'hi' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeGroupMessage(senderUin: number): GroupMessage {
|
||||||
|
return {
|
||||||
|
kind: 'group_message',
|
||||||
|
time: 1700000000,
|
||||||
|
selfUin: SELF_ID,
|
||||||
|
groupId: 99999,
|
||||||
|
senderUin,
|
||||||
|
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||||
|
senderCard: '',
|
||||||
|
senderRole: 'member',
|
||||||
|
msgSeq: 1,
|
||||||
|
msgId: 1,
|
||||||
|
elements: [{ type: 'text', text: 'hi' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeTempMessage(senderUin: number): TempMessage {
|
||||||
|
return {
|
||||||
|
kind: 'temp_message',
|
||||||
|
time: 1700000000,
|
||||||
|
selfUin: SELF_ID,
|
||||||
|
senderUin,
|
||||||
|
groupId: 99999,
|
||||||
|
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
|
||||||
|
msgSeq: 1,
|
||||||
|
elements: [{ type: 'text', text: 'hi' }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('EventConverter post_type tagging', () => {
|
||||||
|
it('tags self friend_message as message_sent', async () => {
|
||||||
|
const conv = new EventConverter();
|
||||||
|
const result = await conv.convert(SELF_UIN, makeFriendMessage(SELF_ID));
|
||||||
|
expect(result).not.toBeNull();
|
||||||
|
expect(result!.post_type).toBe('message_sent');
|
||||||
|
expect(result!.message_type).toBe('private');
|
||||||
|
expect(result!.user_id).toBe(SELF_ID);
|
||||||
|
expect(result!.self_id).toBe(SELF_ID);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tags self group_message as message_sent', async () => {
|
||||||
|
const conv = new EventConverter();
|
||||||
|
const result = await conv.convert(SELF_UIN, makeGroupMessage(SELF_ID));
|
||||||
|
expect(result!.post_type).toBe('message_sent');
|
||||||
|
expect(result!.message_type).toBe('group');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('tags self temp_message as message_sent', async () => {
|
||||||
|
const conv = new EventConverter();
|
||||||
|
const result = await conv.convert(SELF_UIN, makeTempMessage(SELF_ID));
|
||||||
|
expect(result!.post_type).toBe('message_sent');
|
||||||
|
expect(result!.sub_type).toBe('group');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps incoming peer messages tagged as plain message', async () => {
|
||||||
|
const conv = new EventConverter();
|
||||||
|
const friend = await conv.convert(SELF_UIN, makeFriendMessage(PEER_UIN));
|
||||||
|
expect(friend!.post_type).toBe('message');
|
||||||
|
expect(friend!.user_id).toBe(PEER_UIN);
|
||||||
|
|
||||||
|
const group = await conv.convert(SELF_UIN, makeGroupMessage(PEER_UIN));
|
||||||
|
expect(group!.post_type).toBe('message');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('shapeEventForAdapter', () => {
|
||||||
|
const baseEvent = {
|
||||||
|
time: 1,
|
||||||
|
self_id: SELF_ID,
|
||||||
|
post_type: 'message_sent' as const,
|
||||||
|
message_type: 'private',
|
||||||
|
sub_type: 'friend',
|
||||||
|
message_id: 7,
|
||||||
|
user_id: SELF_ID,
|
||||||
|
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||||
|
raw_message: 'hello',
|
||||||
|
font: 0,
|
||||||
|
sender: { user_id: SELF_ID, nickname: 'me', sex: 'unknown', age: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
it('drops self message_sent when adapter has reportSelfMessage=false', () => {
|
||||||
|
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||||
|
expect(shapeEventForAdapter(baseEvent, opts)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps self message_sent when adapter has reportSelfMessage=true', () => {
|
||||||
|
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||||
|
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||||
|
expect(shaped).not.toBeNull();
|
||||||
|
expect(shaped!.post_type).toBe('message_sent');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('rewrites message to CQ string when format=string', () => {
|
||||||
|
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: true });
|
||||||
|
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||||
|
expect(shaped).not.toBeNull();
|
||||||
|
expect(shaped!.message).toBe('hello');
|
||||||
|
// raw_message is preserved untouched.
|
||||||
|
expect(shaped!.raw_message).toBe('hello');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps message as array when format=array (default)', () => {
|
||||||
|
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||||
|
const shaped = shapeEventForAdapter(baseEvent, opts);
|
||||||
|
expect(Array.isArray(shaped!.message)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('defaults partially-deserialized adapters to array format and no self report', () => {
|
||||||
|
const opts = resolveReportOptions({});
|
||||||
|
expect(opts.messageFormat).toBe('array');
|
||||||
|
expect(opts.reportSelfMessage).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('passes through non-message events unchanged', () => {
|
||||||
|
const noticeEvent = {
|
||||||
|
time: 1,
|
||||||
|
self_id: SELF_ID,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_increase',
|
||||||
|
group_id: 1,
|
||||||
|
user_id: 2,
|
||||||
|
};
|
||||||
|
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
|
||||||
|
expect(shapeEventForAdapter(noticeEvent, opts)).toBe(noticeEvent);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('buildDispatchPayload + pickDispatchJson', () => {
|
||||||
|
const messageEvent = {
|
||||||
|
time: 1,
|
||||||
|
self_id: SELF_ID,
|
||||||
|
post_type: 'message',
|
||||||
|
message_type: 'private',
|
||||||
|
sub_type: 'friend',
|
||||||
|
message_id: 7,
|
||||||
|
user_id: PEER_UIN,
|
||||||
|
message: [{ type: 'text', data: { text: 'hello' } }],
|
||||||
|
raw_message: 'hello',
|
||||||
|
font: 0,
|
||||||
|
sender: { user_id: PEER_UIN, nickname: 'peer', sex: 'unknown', age: 0 },
|
||||||
|
};
|
||||||
|
|
||||||
|
const selfMessageEvent = { ...messageEvent, post_type: 'message_sent', user_id: SELF_ID };
|
||||||
|
|
||||||
|
const noticeEvent = {
|
||||||
|
time: 1,
|
||||||
|
self_id: SELF_ID,
|
||||||
|
post_type: 'notice',
|
||||||
|
notice_type: 'group_increase',
|
||||||
|
group_id: 1,
|
||||||
|
user_id: 2,
|
||||||
|
};
|
||||||
|
|
||||||
|
it('builds at most two distinct JSON variants for a message event', () => {
|
||||||
|
const payload = buildDispatchPayload(messageEvent);
|
||||||
|
expect(payload.isSelfMessage).toBe(false);
|
||||||
|
|
||||||
|
const arr = JSON.parse(payload.arrayJson);
|
||||||
|
const str = JSON.parse(payload.stringJson);
|
||||||
|
expect(Array.isArray(arr.message)).toBe(true);
|
||||||
|
expect(typeof str.message).toBe('string');
|
||||||
|
expect(str.message).toBe('hello');
|
||||||
|
expect(str.raw_message).toBe('hello');
|
||||||
|
// every other field should be byte-identical
|
||||||
|
const { message: _arrMsg, ...arrRest } = arr;
|
||||||
|
const { message: _strMsg, ...strRest } = str;
|
||||||
|
expect(arrRest).toEqual(strRest);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('flags self messages and uses identical JSON for non-message events', () => {
|
||||||
|
const selfPayload = buildDispatchPayload(selfMessageEvent);
|
||||||
|
expect(selfPayload.isSelfMessage).toBe(true);
|
||||||
|
|
||||||
|
const noticePayload = buildDispatchPayload(noticeEvent);
|
||||||
|
expect(noticePayload.isSelfMessage).toBe(false);
|
||||||
|
// Non-message events do not need a separate string variant.
|
||||||
|
expect(noticePayload.arrayJson).toBe(noticePayload.stringJson);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('routes connections to the right pre-serialized variant in O(1)', () => {
|
||||||
|
const payload = buildDispatchPayload(messageEvent);
|
||||||
|
const arrayOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||||
|
const stringOpt = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
|
||||||
|
|
||||||
|
expect(pickDispatchJson(payload, arrayOpt)).toBe(payload.arrayJson);
|
||||||
|
expect(pickDispatchJson(payload, stringOpt)).toBe(payload.stringJson);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('drops self-message dispatches for adapters that opt out', () => {
|
||||||
|
const payload = buildDispatchPayload(selfMessageEvent);
|
||||||
|
const offOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
|
||||||
|
expect(pickDispatchJson(payload, offOpt)).toBeNull();
|
||||||
|
|
||||||
|
const onOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
|
||||||
|
const json = pickDispatchJson(payload, onOpt);
|
||||||
|
expect(json).not.toBeNull();
|
||||||
|
expect(JSON.parse(json!).post_type).toBe('message_sent');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('serializes only twice regardless of fan-out size', () => {
|
||||||
|
const payload = buildDispatchPayload(messageEvent);
|
||||||
|
// Mixed fleet of adapters with different formats / self-report options.
|
||||||
|
const adapters = Array.from({ length: 50 }, (_, i) => i % 2 === 0
|
||||||
|
? { messageFormat: 'array' as const, reportSelfMessage: false }
|
||||||
|
: { messageFormat: 'string' as const, reportSelfMessage: true },
|
||||||
|
);
|
||||||
|
const seen = new Set(
|
||||||
|
adapters
|
||||||
|
.map((opts) => pickDispatchJson(payload, opts))
|
||||||
|
.filter((j): j is string => j !== null),
|
||||||
|
);
|
||||||
|
// No matter the fan-out, only at most the two prebuilt strings appear.
|
||||||
|
expect(seen.size).toBeLessThanOrEqual(2);
|
||||||
|
expect(seen.has(payload.arrayJson)).toBe(true);
|
||||||
|
expect(seen.has(payload.stringJson)).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,5 +1,8 @@
|
|||||||
import { describe, it, expect } from 'vitest';
|
import { describe, it, expect } from 'vitest';
|
||||||
import { parseMessage } from '../src/onebot/message-parser';
|
import { parseMessage } from '../src/onebot/message-parser';
|
||||||
|
import { buildSendElems } from '../src/bridge/builders/element-builder';
|
||||||
|
import { MentionExtraSendSchema } from '../src/bridge/proto/action';
|
||||||
|
import { protoDecode } from '../src/protobuf/decode';
|
||||||
|
|
||||||
describe('parseMessage', () => {
|
describe('parseMessage', () => {
|
||||||
describe('plain text', () => {
|
describe('plain text', () => {
|
||||||
@@ -94,6 +97,53 @@ describe('parseMessage', () => {
|
|||||||
expect(result[0].targetUin).toBe(12345);
|
expect(result[0].targetUin).toBe(12345);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('uses at segment name for display text and preserves uid', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'at', data: { qq: '123456', name: 'User', uid: 'u_test_uid' } }] as any,
|
||||||
|
false,
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0]).toMatchObject({
|
||||||
|
type: 'at',
|
||||||
|
targetUin: 123456,
|
||||||
|
uid: 'u_test_uid',
|
||||||
|
text: '@User ',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves missing at uid through parse options', async () => {
|
||||||
|
const result = await parseMessage(
|
||||||
|
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
|
||||||
|
false,
|
||||||
|
{ resolveMentionUid: async (targetUin) => targetUin === 123456 ? 'u_resolved_uid' : null },
|
||||||
|
);
|
||||||
|
expect(result).toHaveLength(1);
|
||||||
|
expect(result[0]).toMatchObject({
|
||||||
|
type: 'at',
|
||||||
|
targetUin: 123456,
|
||||||
|
uid: 'u_resolved_uid',
|
||||||
|
text: '@User ',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it('encodes mention extra with resolved uid for QQ notification', async () => {
|
||||||
|
const elements = await parseMessage(
|
||||||
|
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
|
||||||
|
false,
|
||||||
|
{ resolveMentionUid: () => 'u_resolved_uid' },
|
||||||
|
);
|
||||||
|
const protoElems = await buildSendElems(elements);
|
||||||
|
const reserve = protoElems[0].text?.pbReserve;
|
||||||
|
expect(reserve).toBeInstanceOf(Uint8Array);
|
||||||
|
const extra = protoDecode(reserve as Uint8Array, MentionExtraSendSchema);
|
||||||
|
expect(extra).toMatchObject({
|
||||||
|
type: 2,
|
||||||
|
uin: 123456,
|
||||||
|
uid: 'u_resolved_uid',
|
||||||
|
});
|
||||||
|
expect(protoElems[0].text?.str).toBe('@User ');
|
||||||
|
});
|
||||||
|
|
||||||
it('parses multiple segments', async () => {
|
it('parses multiple segments', async () => {
|
||||||
const result = await parseMessage(
|
const result = await parseMessage(
|
||||||
[
|
[
|
||||||
|
|||||||
@@ -0,0 +1,190 @@
|
|||||||
|
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||||
|
import { MessageStore } from '../src/onebot/message-store';
|
||||||
|
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/onebot/message-id';
|
||||||
|
import fs from 'fs';
|
||||||
|
import path from 'path';
|
||||||
|
|
||||||
|
describe('MessageStore', () => {
|
||||||
|
const testDbPath = path.join('data', 'test', 'messages-test.db');
|
||||||
|
let store: MessageStore;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
// Clean up any existing test database
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(testDbPath);
|
||||||
|
} catch {
|
||||||
|
// Ignore if file doesn't exist
|
||||||
|
}
|
||||||
|
store = new MessageStore(testDbPath);
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
store.close();
|
||||||
|
// Clean up test database
|
||||||
|
try {
|
||||||
|
fs.unlinkSync(testDbPath);
|
||||||
|
} catch {
|
||||||
|
// Ignore cleanup errors
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('resolveReplySequence', () => {
|
||||||
|
it('resolves group message reply sequence', () => {
|
||||||
|
const groupId = 123456;
|
||||||
|
const sequence = 100;
|
||||||
|
const messageId = hashMessageIdInt32(sequence, groupId, GROUP_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
// Store a group message
|
||||||
|
store.storeMeta(messageId, {
|
||||||
|
isGroup: true,
|
||||||
|
targetId: groupId,
|
||||||
|
sequence,
|
||||||
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: 0,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Resolve the reply sequence
|
||||||
|
const resolved = store.resolveReplySequence(true, groupId, messageId);
|
||||||
|
expect(resolved).toBe(sequence);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('resolves private message reply sequence without session_id matching', () => {
|
||||||
|
// Simulate receiving a private message from user 111111
|
||||||
|
const senderUin = 111111;
|
||||||
|
const sequence = 200;
|
||||||
|
const messageId = hashMessageIdInt32(sequence, senderUin, PRIVATE_MESSAGE_EVENT);
|
||||||
|
|
||||||
|
// Store the received message (session_id is sender's UIN)
|
||||||
|
store.storeMeta(messageId, {
|
||||||
|
isGroup: false,
|
||||||
|
targetId: senderUin,
|
||||||
|
sequence,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: 0,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// When replying to this message, we send to the sender (who becomes the recipient)
|
||||||
|
// The key fix: resolveReplySequence should work even when sessionId doesn't match
|
||||||
|
const resolved = store.resolveReplySequence(false, senderUin, messageId);
|
||||||
|
expect(resolved).toBe(sequence);
|
||||||
|
|
||||||
|
// More importantly: it should also work when we pass a different sessionId
|
||||||
|
// (which was the bug - we were passing recipient UIN instead of sender UIN)
|
||||||
|
const differentUin = 999999;
|
||||||
|
const resolvedWithDifferentSession = store.resolveReplySequence(false, differentUin, messageId);
|
||||||
|
expect(resolvedWithDifferentSession).toBe(sequence);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for non-existent message', () => {
|
||||||
|
const resolved = store.resolveReplySequence(true, 123456, 999999);
|
||||||
|
expect(resolved).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for invalid messageId', () => {
|
||||||
|
const resolved = store.resolveReplySequence(true, 123456, 0);
|
||||||
|
expect(resolved).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for invalid sessionId', () => {
|
||||||
|
const messageId = hashMessageIdInt32(100, 123456, GROUP_MESSAGE_EVENT);
|
||||||
|
const resolved = store.resolveReplySequence(true, 0, messageId);
|
||||||
|
expect(resolved).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('distinguishes between group and private messages', () => {
|
||||||
|
const sessionId = 123456;
|
||||||
|
const sequence = 300;
|
||||||
|
|
||||||
|
// Store a group message
|
||||||
|
const groupMessageId = hashMessageIdInt32(sequence, sessionId, GROUP_MESSAGE_EVENT);
|
||||||
|
store.storeMeta(groupMessageId, {
|
||||||
|
isGroup: true,
|
||||||
|
targetId: sessionId,
|
||||||
|
sequence,
|
||||||
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: 0,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Store a private message with same sequence but different hash
|
||||||
|
const privateMessageId = hashMessageIdInt32(sequence, sessionId, PRIVATE_MESSAGE_EVENT);
|
||||||
|
store.storeMeta(privateMessageId, {
|
||||||
|
isGroup: false,
|
||||||
|
targetId: sessionId,
|
||||||
|
sequence,
|
||||||
|
eventName: PRIVATE_MESSAGE_EVENT,
|
||||||
|
clientSequence: 0,
|
||||||
|
random: 0,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Should resolve correctly based on isGroup flag
|
||||||
|
const groupResolved = store.resolveReplySequence(true, sessionId, groupMessageId);
|
||||||
|
expect(groupResolved).toBe(sequence);
|
||||||
|
|
||||||
|
const privateResolved = store.resolveReplySequence(false, sessionId, privateMessageId);
|
||||||
|
expect(privateResolved).toBe(sequence);
|
||||||
|
|
||||||
|
// Should not cross-resolve
|
||||||
|
const wrongGroupResolve = store.resolveReplySequence(true, sessionId, privateMessageId);
|
||||||
|
expect(wrongGroupResolve).toBeNull();
|
||||||
|
|
||||||
|
const wrongPrivateResolve = store.resolveReplySequence(false, sessionId, groupMessageId);
|
||||||
|
expect(wrongPrivateResolve).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('storeEvent and findEvent', () => {
|
||||||
|
it('stores and retrieves event data', () => {
|
||||||
|
const messageId = 12345;
|
||||||
|
const event = {
|
||||||
|
post_type: 'message',
|
||||||
|
message_type: 'group',
|
||||||
|
message_id: messageId,
|
||||||
|
group_id: 123456,
|
||||||
|
message: 'test message',
|
||||||
|
time: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
store.storeEvent(messageId, true, 123456, 100, GROUP_MESSAGE_EVENT, event);
|
||||||
|
|
||||||
|
const retrieved = store.findEvent(messageId);
|
||||||
|
expect(retrieved).toEqual(event);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for non-existent event', () => {
|
||||||
|
const retrieved = store.findEvent(999999);
|
||||||
|
expect(retrieved).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('storeMeta and findMeta', () => {
|
||||||
|
it('stores and retrieves message meta', () => {
|
||||||
|
const messageId = 54321;
|
||||||
|
const meta = {
|
||||||
|
isGroup: true,
|
||||||
|
targetId: 123456,
|
||||||
|
sequence: 100,
|
||||||
|
eventName: GROUP_MESSAGE_EVENT,
|
||||||
|
clientSequence: 1,
|
||||||
|
random: 12345,
|
||||||
|
timestamp: Date.now(),
|
||||||
|
};
|
||||||
|
|
||||||
|
store.storeMeta(messageId, meta);
|
||||||
|
|
||||||
|
const retrieved = store.findMeta(messageId);
|
||||||
|
expect(retrieved).toEqual(meta);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('returns null for non-existent meta', () => {
|
||||||
|
const retrieved = store.findMeta(999999);
|
||||||
|
expect(retrieved).toBeNull();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -8,6 +8,7 @@ import { ConfigPage } from '@/components/pages/config-page';
|
|||||||
import { LogsPage } from '@/components/pages/logs-page';
|
import { LogsPage } from '@/components/pages/logs-page';
|
||||||
import { SettingsPage } from '@/components/pages/settings-page';
|
import { SettingsPage } from '@/components/pages/settings-page';
|
||||||
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
|
import { ChangePasswordPage, type PasswordRule } from '@/components/pages/change-password-page';
|
||||||
|
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||||
import type { Page } from '@/components/layout/sidebar';
|
import type { Page } from '@/components/layout/sidebar';
|
||||||
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
|
import type { HookProcessInfo, OneBotConfig, QQInfo, SystemInfo } from '@/types';
|
||||||
|
|
||||||
@@ -41,6 +42,7 @@ function AppInner() {
|
|||||||
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
|
const [processUnloadingPid, setProcessUnloadingPid] = useState<number | null>(null);
|
||||||
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
|
const [processRefreshingPid, setProcessRefreshingPid] = useState<number | null>(null);
|
||||||
const [processActionStatus, setProcessActionStatus] = useState('');
|
const [processActionStatus, setProcessActionStatus] = useState('');
|
||||||
|
const [unloadFailedAlert, setUnloadFailedAlert] = useState<{ pid: number; error: string } | null>(null);
|
||||||
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
|
// Tracks PIDs with an in-flight load/unload/refresh request so the UI can
|
||||||
// collapse spam-clicks instead of firing a second concurrent request.
|
// collapse spam-clicks instead of firing a second concurrent request.
|
||||||
const inflightProcessOps = useRef(new Set<number>());
|
const inflightProcessOps = useRef(new Set<number>());
|
||||||
@@ -173,11 +175,22 @@ function AppInner() {
|
|||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const loaded = data?.config ?? data;
|
const loaded = data?.config ?? data;
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
|
const nets = loaded?.networks ?? {};
|
||||||
|
const legacyFormat = loaded?.messageFormat === 'string' ? 'string' : 'array';
|
||||||
|
const legacyReport = !!loaded?.reportSelfMessage;
|
||||||
|
const normalizeNetwork = <T extends Record<string, unknown>>(item: T) => ({
|
||||||
|
...item,
|
||||||
|
messageFormat: item.messageFormat === 'string' ? 'string' : legacyFormat,
|
||||||
|
reportSelfMessage:
|
||||||
|
typeof item.reportSelfMessage === 'boolean' ? item.reportSelfMessage : legacyReport,
|
||||||
|
});
|
||||||
setConfig({
|
setConfig({
|
||||||
httpServers: loaded?.httpServers || [],
|
networks: {
|
||||||
httpPostEndpoints: loaded?.httpPostEndpoints || [],
|
httpServers: Array.isArray(nets.httpServers) ? nets.httpServers.map(normalizeNetwork) : [],
|
||||||
wsServers: loaded?.wsServers || [],
|
httpClients: Array.isArray(nets.httpClients) ? nets.httpClients.map(normalizeNetwork) : [],
|
||||||
wsClients: loaded?.wsClients || [],
|
wsServers: Array.isArray(nets.wsServers) ? nets.wsServers.map(normalizeNetwork) : [],
|
||||||
|
wsClients: Array.isArray(nets.wsClients) ? nets.wsClients.map(normalizeNetwork) : [],
|
||||||
|
},
|
||||||
musicSignUrl: loaded?.musicSignUrl,
|
musicSignUrl: loaded?.musicSignUrl,
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
@@ -256,7 +269,15 @@ function AppInner() {
|
|||||||
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
|
const res = await fetchApi(`/api/processes/${pid}/unload`, { method: 'POST' });
|
||||||
const data = await res.json().catch(() => ({}));
|
const data = await res.json().catch(() => ({}));
|
||||||
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
|
if (!res.ok) throw new Error(data.message || data.error || '卸载失败');
|
||||||
|
|
||||||
|
// Check if unload actually failed (pipe still exists)
|
||||||
|
if (data.process?.status === 'connecting' && data.process?.error) {
|
||||||
|
setUnloadFailedAlert({ pid, error: data.process.error });
|
||||||
|
setProcessActionStatus(`进程 ${pid} 卸载失败`);
|
||||||
|
} else {
|
||||||
setProcessActionStatus(`已从进程 ${pid} 卸载`);
|
setProcessActionStatus(`已从进程 ${pid} 卸载`);
|
||||||
|
}
|
||||||
|
|
||||||
await refreshProcesses();
|
await refreshProcesses();
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
|
setProcessActionStatus(`卸载失败:${(e as Error).message}`);
|
||||||
@@ -376,6 +397,25 @@ function AppInner() {
|
|||||||
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
|
{active === 'settings' && <SettingsPage fetchApi={fetchApi} onLogout={handleLogout} />}
|
||||||
</MainLayout>
|
</MainLayout>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
<ConfirmDialog
|
||||||
|
open={!!unloadFailedAlert}
|
||||||
|
onOpenChange={(open) => !open && setUnloadFailedAlert(null)}
|
||||||
|
title="卸载失败"
|
||||||
|
description={
|
||||||
|
unloadFailedAlert ? (
|
||||||
|
<>
|
||||||
|
<p>进程 {unloadFailedAlert.pid} 的 SnowLuma DLL 卸载失败。</p>
|
||||||
|
<p className="mt-2 text-sm">{unloadFailedAlert.error}</p>
|
||||||
|
<p className="mt-2 text-sm text-muted-foreground">
|
||||||
|
系统将继续尝试重新连接该进程。如需彻底卸载,请重启 QQ 进程。
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
) : null
|
||||||
|
}
|
||||||
|
confirmText="知道了"
|
||||||
|
onConfirm={() => setUnloadFailedAlert(null)}
|
||||||
|
/>
|
||||||
</TooltipProvider>
|
</TooltipProvider>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -12,12 +12,12 @@ import { Skeleton } from '@/components/ui/skeleton';
|
|||||||
import { ConfirmDialog } from '@/components/confirm-dialog';
|
import { ConfirmDialog } from '@/components/confirm-dialog';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import type {
|
import type {
|
||||||
HttpPostEndpoint,
|
MessageFormat,
|
||||||
HttpServerEndpoint,
|
NetworkKind,
|
||||||
OneBotConfig,
|
OneBotConfig,
|
||||||
|
OneBotNetworks,
|
||||||
QQInfo,
|
QQInfo,
|
||||||
WsClientEndpoint,
|
WsRole,
|
||||||
WsServerEndpoint,
|
|
||||||
} from '@/types';
|
} from '@/types';
|
||||||
|
|
||||||
interface ConfigPageProps {
|
interface ConfigPageProps {
|
||||||
@@ -34,6 +34,12 @@ function qqAvatarUrl(uin: string) {
|
|||||||
return `/avatar/${encodeURIComponent(uin)}`;
|
return `/avatar/${encodeURIComponent(uin)}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function generateAccessToken(): string {
|
||||||
|
const bytes = new Uint8Array(32);
|
||||||
|
globalThis.crypto.getRandomValues(bytes);
|
||||||
|
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
|
||||||
|
}
|
||||||
|
|
||||||
function Field({
|
function Field({
|
||||||
label,
|
label,
|
||||||
value,
|
value,
|
||||||
@@ -92,30 +98,6 @@ function Section({ title, description, onAdd, children, count }: SectionProps) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function EndpointRow({ children, onRemove }: { children: React.ReactNode; onRemove?: () => void }) {
|
|
||||||
return (
|
|
||||||
<motion.div
|
|
||||||
initial={{ opacity: 0, y: 4 }}
|
|
||||||
animate={{ opacity: 1, y: 0 }}
|
|
||||||
transition={{ duration: 0.18 }}
|
|
||||||
className="flex flex-col gap-3 rounded-lg border bg-card/40 p-3 sm:flex-row sm:items-end"
|
|
||||||
>
|
|
||||||
<div className="flex flex-1 flex-col gap-3 sm:flex-row sm:items-end">{children}</div>
|
|
||||||
{onRemove && (
|
|
||||||
<Button
|
|
||||||
variant="ghost"
|
|
||||||
size="icon-sm"
|
|
||||||
onClick={onRemove}
|
|
||||||
aria-label="删除"
|
|
||||||
className="self-end text-muted-foreground hover:text-destructive"
|
|
||||||
>
|
|
||||||
<Trash2 className="size-4" />
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</motion.div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export function ConfigPage({
|
export function ConfigPage({
|
||||||
qqList,
|
qqList,
|
||||||
selectedUin,
|
selectedUin,
|
||||||
@@ -217,200 +199,218 @@ export function ConfigPage({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* HTTP Servers */}
|
|
||||||
<Section
|
<Section
|
||||||
title="HTTP 服务监听"
|
title="通用设置"
|
||||||
description="开放 HTTP API,OneBot 客户端可主动发起请求"
|
description="OneBot 共享功能配置"
|
||||||
count={config.httpServers.length}
|
|
||||||
onAdd={() => update({ ...config, httpServers: [...config.httpServers, { port: 3000, host: '0.0.0.0', path: '/' }] })}
|
|
||||||
>
|
|
||||||
{config.httpServers.length === 0 ? (
|
|
||||||
<EmptyHint label="暂无 HTTP 服务" />
|
|
||||||
) : (
|
|
||||||
config.httpServers.map((s, idx) => (
|
|
||||||
<EndpointRow
|
|
||||||
key={idx}
|
|
||||||
onRemove={() => update({ ...config, httpServers: config.httpServers.filter((_, i) => i !== idx) })}
|
|
||||||
>
|
>
|
||||||
<Field
|
<Field
|
||||||
label="端口"
|
label="音乐签名服务 URL"
|
||||||
type="number"
|
|
||||||
value={s.port}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
httpServers: config.httpServers.map((it, i) => (i === idx ? { ...it, port: Number(v) || undefined } : it)) as HttpServerEndpoint[],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="sm:w-32"
|
|
||||||
/>
|
|
||||||
<Field
|
|
||||||
label="授权 Token"
|
|
||||||
placeholder="不填则无密码"
|
|
||||||
value={s.accessToken}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
httpServers: config.httpServers.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
</EndpointRow>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
{/* HTTP Post */}
|
|
||||||
<Section
|
|
||||||
title="HTTP Post 推送"
|
|
||||||
description="向远端 URL 主动推送事件"
|
|
||||||
count={config.httpPostEndpoints.length}
|
|
||||||
onAdd={() => update({ ...config, httpPostEndpoints: [...config.httpPostEndpoints, { url: 'http://127.0.0.1:5700' }] })}
|
|
||||||
>
|
|
||||||
{config.httpPostEndpoints.length === 0 ? (
|
|
||||||
<EmptyHint label="暂无 HTTP 推送目标" />
|
|
||||||
) : (
|
|
||||||
config.httpPostEndpoints.map((s, idx) => (
|
|
||||||
<EndpointRow
|
|
||||||
key={idx}
|
|
||||||
onRemove={() =>
|
|
||||||
update({ ...config, httpPostEndpoints: config.httpPostEndpoints.filter((_, i) => i !== idx) })
|
|
||||||
}
|
|
||||||
>
|
|
||||||
<Field
|
|
||||||
label="目标 URL"
|
|
||||||
type="url"
|
|
||||||
placeholder="http://..."
|
|
||||||
value={s.url}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
httpPostEndpoints: config.httpPostEndpoints.map((it, i) => (i === idx ? { ...it, url: v } : it)) as HttpPostEndpoint[],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
<Field
|
|
||||||
label="授权 Token"
|
|
||||||
placeholder="可选"
|
|
||||||
value={s.accessToken}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
httpPostEndpoints: config.httpPostEndpoints.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="sm:w-64"
|
|
||||||
/>
|
|
||||||
</EndpointRow>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
{/* WS Servers */}
|
|
||||||
<Section
|
|
||||||
title="WebSocket 服务监听"
|
|
||||||
description="开放 WS 服务,客户端可建立持久连接"
|
|
||||||
count={config.wsServers.length}
|
|
||||||
onAdd={() => update({ ...config, wsServers: [...config.wsServers, { port: 3001, host: '0.0.0.0', path: '/' }] })}
|
|
||||||
>
|
|
||||||
{config.wsServers.length === 0 ? (
|
|
||||||
<EmptyHint label="暂无 WS 服务" />
|
|
||||||
) : (
|
|
||||||
config.wsServers.map((s, idx) => (
|
|
||||||
<EndpointRow
|
|
||||||
key={idx}
|
|
||||||
onRemove={() => update({ ...config, wsServers: config.wsServers.filter((_, i) => i !== idx) })}
|
|
||||||
>
|
|
||||||
<Field
|
|
||||||
label="端口"
|
|
||||||
type="number"
|
|
||||||
value={s.port}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
wsServers: config.wsServers.map((it, i) => (i === idx ? { ...it, port: Number(v) || undefined } : it)) as WsServerEndpoint[],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="sm:w-32"
|
|
||||||
/>
|
|
||||||
<Field
|
|
||||||
label="授权 Token"
|
|
||||||
placeholder="不填则无密码"
|
|
||||||
value={s.accessToken}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
wsServers: config.wsServers.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
</EndpointRow>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
{/* WS Clients */}
|
|
||||||
<Section
|
|
||||||
title="WebSocket 反向连出"
|
|
||||||
description="主动连接到外部 WS 服务器(reverse-ws)"
|
|
||||||
count={config.wsClients.length}
|
|
||||||
onAdd={() =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
wsClients: [...config.wsClients, { url: 'ws://127.0.0.1:8080/ws', reconnectIntervalMs: 5000 }],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
>
|
|
||||||
{config.wsClients.length === 0 ? (
|
|
||||||
<EmptyHint label="暂无反向 WS 客户端" />
|
|
||||||
) : (
|
|
||||||
config.wsClients.map((c, idx) => (
|
|
||||||
<EndpointRow
|
|
||||||
key={idx}
|
|
||||||
onRemove={() => update({ ...config, wsClients: config.wsClients.filter((_, i) => i !== idx) })}
|
|
||||||
>
|
|
||||||
<Field
|
|
||||||
label="目标 URL"
|
|
||||||
type="url"
|
|
||||||
placeholder="ws://..."
|
|
||||||
value={c.url}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
wsClients: config.wsClients.map((it, i) => (i === idx ? { ...it, url: v } : it)) as WsClientEndpoint[],
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="flex-1"
|
|
||||||
/>
|
|
||||||
<Field
|
|
||||||
label="授权 Token"
|
|
||||||
placeholder="可选"
|
|
||||||
value={c.accessToken}
|
|
||||||
onChange={(v) =>
|
|
||||||
update({
|
|
||||||
...config,
|
|
||||||
wsClients: config.wsClients.map((it, i) => (i === idx ? { ...it, accessToken: v || undefined } : it)),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
className="sm:w-64"
|
|
||||||
/>
|
|
||||||
</EndpointRow>
|
|
||||||
))
|
|
||||||
)}
|
|
||||||
</Section>
|
|
||||||
|
|
||||||
<Section title="音乐签名 URL" description="用于生成音乐卡片签名(可选)">
|
|
||||||
<Field
|
|
||||||
label="签名服务地址"
|
|
||||||
type="url"
|
type="url"
|
||||||
placeholder="留空则不启用"
|
placeholder="留空则不启用"
|
||||||
value={config.musicSignUrl}
|
value={config.musicSignUrl}
|
||||||
onChange={(v) => update({ ...config, musicSignUrl: v || undefined })}
|
onChange={(v) => update({ ...config, musicSignUrl: v || undefined })}
|
||||||
/>
|
/>
|
||||||
</Section>
|
</Section>
|
||||||
|
|
||||||
|
{/* HTTP Servers */}
|
||||||
|
<NetworkSection
|
||||||
|
title="HTTP API 服务"
|
||||||
|
description="本地监听 HTTP 端口,OneBot 客户端发起请求"
|
||||||
|
kind="httpServers"
|
||||||
|
networks={config.networks.httpServers}
|
||||||
|
onChange={(arr) => updateNetworks(config, update, 'httpServers', arr)}
|
||||||
|
renderFields={(item, patch) => (
|
||||||
|
<>
|
||||||
|
<Field
|
||||||
|
label="主机"
|
||||||
|
placeholder="0.0.0.0"
|
||||||
|
value={item.host}
|
||||||
|
onChange={(v) => patch({ host: v || undefined })}
|
||||||
|
className="sm:w-40"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="端口"
|
||||||
|
type="number"
|
||||||
|
value={item.port}
|
||||||
|
onChange={(v) => patch({ port: Number(v) || 0 })}
|
||||||
|
className="sm:w-28"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="路径"
|
||||||
|
placeholder="/"
|
||||||
|
value={item.path}
|
||||||
|
onChange={(v) => patch({ path: v || undefined })}
|
||||||
|
className="sm:w-32"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="授权 Token"
|
||||||
|
placeholder="不填则无密码"
|
||||||
|
value={item.accessToken}
|
||||||
|
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
defaultEntry={(suffix) => ({
|
||||||
|
name: `http-${suffix}`,
|
||||||
|
host: '0.0.0.0',
|
||||||
|
port: 3000,
|
||||||
|
path: '/',
|
||||||
|
accessToken: generateAccessToken(),
|
||||||
|
messageFormat: 'array',
|
||||||
|
reportSelfMessage: false,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* HTTP Clients (POST push) */}
|
||||||
|
<NetworkSection
|
||||||
|
title="HTTP 推送客户端"
|
||||||
|
description="主动向远端 URL POST 推送事件"
|
||||||
|
kind="httpClients"
|
||||||
|
networks={config.networks.httpClients}
|
||||||
|
onChange={(arr) => updateNetworks(config, update, 'httpClients', arr)}
|
||||||
|
renderFields={(item, patch) => (
|
||||||
|
<>
|
||||||
|
<Field
|
||||||
|
label="目标 URL"
|
||||||
|
type="url"
|
||||||
|
placeholder="http://..."
|
||||||
|
value={item.url}
|
||||||
|
onChange={(v) => patch({ url: v })}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="授权 Token"
|
||||||
|
placeholder="可选"
|
||||||
|
value={item.accessToken}
|
||||||
|
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||||
|
className="sm:w-56"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="超时 (ms)"
|
||||||
|
type="number"
|
||||||
|
placeholder="5000"
|
||||||
|
value={item.timeoutMs}
|
||||||
|
onChange={(v) => patch({ timeoutMs: Number(v) || undefined })}
|
||||||
|
className="sm:w-32"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
defaultEntry={(suffix) => ({
|
||||||
|
name: `httppost-${suffix}`,
|
||||||
|
url: 'http://127.0.0.1:5700',
|
||||||
|
messageFormat: 'array',
|
||||||
|
reportSelfMessage: false,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* WebSocket Servers */}
|
||||||
|
<NetworkSection
|
||||||
|
title="WebSocket 服务"
|
||||||
|
description="本地监听 WebSocket 端口,客户端建立持久连接"
|
||||||
|
kind="wsServers"
|
||||||
|
networks={config.networks.wsServers}
|
||||||
|
onChange={(arr) => updateNetworks(config, update, 'wsServers', arr)}
|
||||||
|
renderFields={(item, patch) => (
|
||||||
|
<>
|
||||||
|
<Field
|
||||||
|
label="主机"
|
||||||
|
placeholder="0.0.0.0"
|
||||||
|
value={item.host}
|
||||||
|
onChange={(v) => patch({ host: v || undefined })}
|
||||||
|
className="sm:w-40"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="端口"
|
||||||
|
type="number"
|
||||||
|
value={item.port}
|
||||||
|
onChange={(v) => patch({ port: Number(v) || 0 })}
|
||||||
|
className="sm:w-28"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="路径"
|
||||||
|
placeholder="/"
|
||||||
|
value={item.path}
|
||||||
|
onChange={(v) => patch({ path: v || undefined })}
|
||||||
|
className="sm:w-32"
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="角色"
|
||||||
|
value={item.role ?? 'universal'}
|
||||||
|
options={WS_ROLE_OPTIONS}
|
||||||
|
onChange={(v) => patch({ role: v })}
|
||||||
|
className="sm:w-32"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="授权 Token"
|
||||||
|
placeholder="不填则无密码"
|
||||||
|
value={item.accessToken}
|
||||||
|
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
defaultEntry={(suffix) => ({
|
||||||
|
name: `ws-${suffix}`,
|
||||||
|
host: '0.0.0.0',
|
||||||
|
port: 3001,
|
||||||
|
path: '/',
|
||||||
|
role: 'universal' as WsRole,
|
||||||
|
accessToken: generateAccessToken(),
|
||||||
|
messageFormat: 'array',
|
||||||
|
reportSelfMessage: false,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{/* WebSocket Clients (reverse) */}
|
||||||
|
<NetworkSection
|
||||||
|
title="WebSocket 反向客户端"
|
||||||
|
description="主动连接到外部 WebSocket 服务器(reverse-ws)"
|
||||||
|
kind="wsClients"
|
||||||
|
networks={config.networks.wsClients}
|
||||||
|
onChange={(arr) => updateNetworks(config, update, 'wsClients', arr)}
|
||||||
|
renderFields={(item, patch) => (
|
||||||
|
<>
|
||||||
|
<Field
|
||||||
|
label="目标 URL"
|
||||||
|
type="url"
|
||||||
|
placeholder="ws://..."
|
||||||
|
value={item.url}
|
||||||
|
onChange={(v) => patch({ url: v })}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<SelectField
|
||||||
|
label="角色"
|
||||||
|
value={item.role ?? 'universal'}
|
||||||
|
options={WS_ROLE_OPTIONS}
|
||||||
|
onChange={(v) => patch({ role: v })}
|
||||||
|
className="sm:w-32"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="重连间隔 (ms)"
|
||||||
|
type="number"
|
||||||
|
value={item.reconnectIntervalMs}
|
||||||
|
onChange={(v) => patch({ reconnectIntervalMs: Number(v) || undefined })}
|
||||||
|
className="sm:w-36"
|
||||||
|
/>
|
||||||
|
<Field
|
||||||
|
label="授权 Token"
|
||||||
|
placeholder="可选"
|
||||||
|
value={item.accessToken}
|
||||||
|
onChange={(v) => patch({ accessToken: v || undefined })}
|
||||||
|
className="sm:w-56"
|
||||||
|
/>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
defaultEntry={(suffix) => ({
|
||||||
|
name: `wsclient-${suffix}`,
|
||||||
|
url: 'ws://127.0.0.1:8080/ws',
|
||||||
|
role: 'universal' as WsRole,
|
||||||
|
reconnectIntervalMs: 5000,
|
||||||
|
messageFormat: 'array',
|
||||||
|
reportSelfMessage: false,
|
||||||
|
})}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -432,3 +432,296 @@ function EmptyHint({ label }: { label: string }) {
|
|||||||
<div className="rounded-md border border-dashed py-6 text-center text-xs text-muted-foreground">{label}</div>
|
<div className="rounded-md border border-dashed py-6 text-center text-xs text-muted-foreground">{label}</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface ToggleFieldProps {
|
||||||
|
label: string;
|
||||||
|
description?: string;
|
||||||
|
value: boolean;
|
||||||
|
onChange: (v: boolean) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToggleField({ label, description, value, onChange }: ToggleFieldProps) {
|
||||||
|
return (
|
||||||
|
<div className="flex items-start justify-between gap-3 rounded-lg border bg-card/40 p-3">
|
||||||
|
<div className="min-w-0 flex-1">
|
||||||
|
<Label className="text-sm">{label}</Label>
|
||||||
|
{description && (
|
||||||
|
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">{description}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="switch"
|
||||||
|
aria-checked={value}
|
||||||
|
aria-label={label}
|
||||||
|
onClick={() => onChange(!value)}
|
||||||
|
className={cn(
|
||||||
|
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||||
|
value
|
||||||
|
? 'border-primary bg-primary'
|
||||||
|
: 'border-input bg-muted',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<motion.span
|
||||||
|
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||||
|
animate={{ x: value ? 22 : 4 }}
|
||||||
|
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface SegmentedOption<T extends string> {
|
||||||
|
value: T;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
function SegmentedField<T extends string>({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
options,
|
||||||
|
onChange,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: T;
|
||||||
|
options: ReadonlyArray<SegmentedOption<T>>;
|
||||||
|
onChange: (v: T) => void;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className={cn('flex flex-col gap-1.5', className)}>
|
||||||
|
<Label>{label}</Label>
|
||||||
|
<div className="flex flex-wrap gap-1 rounded-md border bg-muted/30 p-1">
|
||||||
|
{options.map((opt) => {
|
||||||
|
const active = value === opt.value;
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={opt.value}
|
||||||
|
type="button"
|
||||||
|
onClick={() => onChange(opt.value)}
|
||||||
|
className={cn(
|
||||||
|
'flex-1 rounded px-2.5 py-1 text-xs transition-colors cursor-pointer',
|
||||||
|
active
|
||||||
|
? 'bg-primary text-primary-foreground'
|
||||||
|
: 'text-muted-foreground hover:bg-accent/50',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{opt.label}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SelectField<T extends string>({
|
||||||
|
label,
|
||||||
|
value,
|
||||||
|
options,
|
||||||
|
onChange,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
label: string;
|
||||||
|
value: T;
|
||||||
|
options: ReadonlyArray<SegmentedOption<T>>;
|
||||||
|
onChange: (v: T) => void;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
return (
|
||||||
|
<div className={cn('flex flex-col gap-1.5', className)}>
|
||||||
|
<Label>{label}</Label>
|
||||||
|
<select
|
||||||
|
value={value}
|
||||||
|
onChange={(e) => onChange(e.target.value as T)}
|
||||||
|
className="h-9 rounded-md border bg-background px-2 text-sm shadow-xs"
|
||||||
|
>
|
||||||
|
{options.map((opt) => (
|
||||||
|
<option key={opt.value} value={opt.value}>
|
||||||
|
{opt.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ADAPTER_FORMAT_OPTIONS: ReadonlyArray<SegmentedOption<MessageFormat>> = [
|
||||||
|
{ value: 'array', label: '数组' },
|
||||||
|
{ value: 'string', label: 'CQ 码' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const ADAPTER_REPORT_OPTIONS: ReadonlyArray<SegmentedOption<'on' | 'off'>> = [
|
||||||
|
{ value: 'on', label: '开启' },
|
||||||
|
{ value: 'off', label: '关闭' },
|
||||||
|
];
|
||||||
|
|
||||||
|
const WS_ROLE_OPTIONS: ReadonlyArray<SegmentedOption<WsRole>> = [
|
||||||
|
{ value: 'universal', label: 'universal' },
|
||||||
|
{ value: 'event', label: 'event' },
|
||||||
|
{ value: 'api', label: 'api' },
|
||||||
|
];
|
||||||
|
|
||||||
|
interface BaseAdapter {
|
||||||
|
name: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
accessToken?: string;
|
||||||
|
messageFormat: MessageFormat;
|
||||||
|
reportSelfMessage: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface NetworkSectionProps<T extends BaseAdapter> {
|
||||||
|
title: string;
|
||||||
|
description?: string;
|
||||||
|
kind: NetworkKind;
|
||||||
|
networks: T[];
|
||||||
|
onChange: (next: T[]) => void;
|
||||||
|
renderFields: (item: T, patch: (changes: Partial<T>) => void) => React.ReactNode;
|
||||||
|
defaultEntry: (suffix: number) => T;
|
||||||
|
}
|
||||||
|
|
||||||
|
function NetworkSection<T extends BaseAdapter>({
|
||||||
|
title,
|
||||||
|
description,
|
||||||
|
networks,
|
||||||
|
onChange,
|
||||||
|
renderFields,
|
||||||
|
defaultEntry,
|
||||||
|
}: NetworkSectionProps<T>) {
|
||||||
|
const handleAdd = () => {
|
||||||
|
const used = new Set(networks.map((n) => n.name));
|
||||||
|
let suffix = networks.length + 1;
|
||||||
|
let entry = defaultEntry(suffix);
|
||||||
|
while (used.has(entry.name)) {
|
||||||
|
suffix += 1;
|
||||||
|
entry = defaultEntry(suffix);
|
||||||
|
}
|
||||||
|
onChange([...networks, entry]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const patchAt = (idx: number, changes: Partial<T>) => {
|
||||||
|
onChange(networks.map((it, i) => (i === idx ? { ...it, ...changes } : it)));
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeAt = (idx: number) => {
|
||||||
|
onChange(networks.filter((_, i) => i !== idx));
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Section title={title} description={description} count={networks.length} onAdd={handleAdd}>
|
||||||
|
{networks.length === 0 ? (
|
||||||
|
<EmptyHint label="暂无适配器,点击右上角『添加』新建" />
|
||||||
|
) : (
|
||||||
|
networks.map((item, idx) => (
|
||||||
|
<AdapterRow
|
||||||
|
key={`${item.name}-${idx}`}
|
||||||
|
item={item}
|
||||||
|
otherNames={networks.filter((_, i) => i !== idx).map((n) => n.name)}
|
||||||
|
onPatch={(changes) => patchAt(idx, changes)}
|
||||||
|
onRemove={() => removeAt(idx)}
|
||||||
|
renderFields={renderFields}
|
||||||
|
/>
|
||||||
|
))
|
||||||
|
)}
|
||||||
|
</Section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AdapterRowProps<T extends BaseAdapter> {
|
||||||
|
item: T;
|
||||||
|
otherNames: string[];
|
||||||
|
onPatch: (changes: Partial<T>) => void;
|
||||||
|
onRemove: () => void;
|
||||||
|
renderFields: (item: T, patch: (changes: Partial<T>) => void) => React.ReactNode;
|
||||||
|
}
|
||||||
|
|
||||||
|
function AdapterRow<T extends BaseAdapter>({
|
||||||
|
item,
|
||||||
|
otherNames,
|
||||||
|
onPatch,
|
||||||
|
onRemove,
|
||||||
|
renderFields,
|
||||||
|
}: AdapterRowProps<T>) {
|
||||||
|
const enabled = item.enabled !== false;
|
||||||
|
const duplicateName = !!item.name && otherNames.includes(item.name);
|
||||||
|
const blankName = !item.name?.trim();
|
||||||
|
|
||||||
|
const formatValue: MessageFormat = item.messageFormat ?? 'array';
|
||||||
|
const reportValue: 'on' | 'off' = item.reportSelfMessage ? 'on' : 'off';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<motion.div
|
||||||
|
initial={{ opacity: 0, y: 4 }}
|
||||||
|
animate={{ opacity: 1, y: 0 }}
|
||||||
|
transition={{ duration: 0.18 }}
|
||||||
|
className={cn(
|
||||||
|
'flex flex-col gap-3 rounded-lg border bg-card/40 p-3',
|
||||||
|
!enabled && 'opacity-60',
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<div className="flex flex-wrap items-end gap-3">
|
||||||
|
<Field
|
||||||
|
label="名称"
|
||||||
|
placeholder="自定义"
|
||||||
|
value={item.name}
|
||||||
|
onChange={(v) => onPatch({ name: v } as Partial<T>)}
|
||||||
|
className="sm:w-44"
|
||||||
|
/>
|
||||||
|
<ToggleField
|
||||||
|
label="启用"
|
||||||
|
value={enabled}
|
||||||
|
onChange={(v) => onPatch({ enabled: v ? undefined : false } as Partial<T>)}
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="ghost"
|
||||||
|
size="icon-sm"
|
||||||
|
onClick={onRemove}
|
||||||
|
aria-label="删除"
|
||||||
|
className="ml-auto self-center text-muted-foreground hover:text-destructive"
|
||||||
|
>
|
||||||
|
<Trash2 className="size-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
{(blankName || duplicateName) && (
|
||||||
|
<p className="text-[11px] text-destructive">
|
||||||
|
{blankName ? '请填写名称' : '名称与其它适配器重复'}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-end gap-3">{renderFields(item, onPatch)}</div>
|
||||||
|
|
||||||
|
<div className="grid gap-3 border-t pt-3 sm:grid-cols-2">
|
||||||
|
<SegmentedField
|
||||||
|
label="消息格式"
|
||||||
|
value={formatValue}
|
||||||
|
options={ADAPTER_FORMAT_OPTIONS}
|
||||||
|
onChange={(v) => onPatch({ messageFormat: v } as Partial<T>)}
|
||||||
|
/>
|
||||||
|
<SegmentedField
|
||||||
|
label="上报自身消息"
|
||||||
|
value={reportValue}
|
||||||
|
options={ADAPTER_REPORT_OPTIONS}
|
||||||
|
onChange={(v) =>
|
||||||
|
onPatch({
|
||||||
|
reportSelfMessage: v === 'on',
|
||||||
|
} as Partial<T>)
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</motion.div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateNetworks<K extends NetworkKind>(
|
||||||
|
config: OneBotConfig,
|
||||||
|
update: (next: OneBotConfig) => void,
|
||||||
|
kind: K,
|
||||||
|
next: OneBotNetworks[K],
|
||||||
|
): void {
|
||||||
|
update({
|
||||||
|
...config,
|
||||||
|
networks: { ...config.networks, [kind]: next },
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -5,7 +5,6 @@ import {
|
|||||||
AlertCircle,
|
AlertCircle,
|
||||||
CheckCircle2,
|
CheckCircle2,
|
||||||
Cpu,
|
Cpu,
|
||||||
HardDrive,
|
|
||||||
Loader2,
|
Loader2,
|
||||||
MemoryStick,
|
MemoryStick,
|
||||||
MonitorCog,
|
MonitorCog,
|
||||||
@@ -224,28 +223,39 @@ export function OverviewPage({
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* GPU */}
|
{/* Runtime */}
|
||||||
<div className="rounded-lg border bg-card/40 p-4">
|
<div className="rounded-lg border bg-card/40 p-4">
|
||||||
<div className="mb-2 flex items-center gap-2">
|
<div className="mb-2 flex items-center justify-between">
|
||||||
<HardDrive className="size-4 text-primary" />
|
<div className="flex items-center gap-2">
|
||||||
<span className="text-sm font-semibold">显示适配器</span>
|
<Server className="size-4 text-primary" />
|
||||||
|
<span className="text-sm font-semibold">运行进程</span>
|
||||||
|
</div>
|
||||||
|
<span className="text-sm font-semibold tabular-nums text-primary">
|
||||||
|
{systemInfo ? `PID ${systemInfo.runtime.pid}` : '—'}
|
||||||
|
</span>
|
||||||
</div>
|
</div>
|
||||||
{!systemInfo ? (
|
{!systemInfo ? (
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Skeleton className="h-4 w-3/4" />
|
<Skeleton className="h-4 w-3/4" />
|
||||||
<Skeleton className="h-4 w-1/2" />
|
<Skeleton className="h-4 w-1/2" />
|
||||||
</div>
|
</div>
|
||||||
) : systemInfo.gpus.length === 0 ? (
|
|
||||||
<p className="text-xs text-muted-foreground">未检测到 GPU 信息</p>
|
|
||||||
) : (
|
) : (
|
||||||
<ul className="space-y-1.5">
|
<div className="space-y-1.5 text-xs">
|
||||||
{systemInfo.gpus.map((g, i) => (
|
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
|
||||||
<li key={i} className="rounded-md bg-background/60 px-2 py-1.5 text-xs">
|
<span className="text-muted-foreground">RSS</span>
|
||||||
<div className="truncate font-medium" title={g.name}>{g.name}</div>
|
<span className="font-medium tabular-nums">{formatBytes(systemInfo.runtime.rss)}</span>
|
||||||
{g.vendor && <div className="text-[10px] text-muted-foreground">{g.vendor}</div>}
|
</div>
|
||||||
</li>
|
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
|
||||||
))}
|
<span className="text-muted-foreground">堆内存</span>
|
||||||
</ul>
|
<span className="font-medium tabular-nums">
|
||||||
|
{formatBytes(systemInfo.runtime.heapUsed)} / {formatBytes(systemInfo.runtime.heapTotal)}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center justify-between rounded-md bg-background/60 px-2 py-1.5">
|
||||||
|
<span className="text-muted-foreground">外部内存</span>
|
||||||
|
<span className="font-medium tabular-nums">{formatBytes(systemInfo.runtime.external)}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
|
|||||||
+46
-30
@@ -19,46 +19,55 @@ export interface HookProcessInfo {
|
|||||||
method: string;
|
method: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HttpServerEndpoint {
|
export type MessageFormat = 'array' | 'string';
|
||||||
name?: string;
|
export type WsRole = 'api' | 'event' | 'universal';
|
||||||
|
|
||||||
|
interface NetworkBase {
|
||||||
|
name: string;
|
||||||
|
enabled?: boolean;
|
||||||
|
accessToken?: string;
|
||||||
|
messageFormat: MessageFormat;
|
||||||
|
reportSelfMessage: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface HttpServerNetwork extends NetworkBase {
|
||||||
host?: string;
|
host?: string;
|
||||||
port?: number;
|
port: number;
|
||||||
path?: string;
|
path?: string;
|
||||||
accessToken?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface WsServerEndpoint {
|
export interface HttpClientNetwork extends NetworkBase {
|
||||||
name?: string;
|
url: string;
|
||||||
host?: string;
|
|
||||||
port?: number;
|
|
||||||
path?: string;
|
|
||||||
role?: string;
|
|
||||||
accessToken?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface WsClientEndpoint {
|
|
||||||
name?: string;
|
|
||||||
url?: string;
|
|
||||||
role?: string;
|
|
||||||
reconnectIntervalMs?: number;
|
|
||||||
accessToken?: string;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface HttpPostEndpoint {
|
|
||||||
name?: string;
|
|
||||||
url?: string;
|
|
||||||
accessToken?: string;
|
|
||||||
timeoutMs?: number;
|
timeoutMs?: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface WsServerNetwork extends NetworkBase {
|
||||||
|
host?: string;
|
||||||
|
port: number;
|
||||||
|
path?: string;
|
||||||
|
role?: WsRole;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WsClientNetwork extends NetworkBase {
|
||||||
|
url: string;
|
||||||
|
role?: WsRole;
|
||||||
|
reconnectIntervalMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface OneBotNetworks {
|
||||||
|
httpServers: HttpServerNetwork[];
|
||||||
|
httpClients: HttpClientNetwork[];
|
||||||
|
wsServers: WsServerNetwork[];
|
||||||
|
wsClients: WsClientNetwork[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface OneBotConfig {
|
export interface OneBotConfig {
|
||||||
httpServers: HttpServerEndpoint[];
|
networks: OneBotNetworks;
|
||||||
httpPostEndpoints: HttpPostEndpoint[];
|
|
||||||
wsServers: WsServerEndpoint[];
|
|
||||||
wsClients: WsClientEndpoint[];
|
|
||||||
musicSignUrl?: string;
|
musicSignUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export type NetworkKind = keyof OneBotNetworks;
|
||||||
|
|
||||||
export interface SystemInfo {
|
export interface SystemInfo {
|
||||||
hostname: string;
|
hostname: string;
|
||||||
platform: string;
|
platform: string;
|
||||||
@@ -81,7 +90,14 @@ export interface SystemInfo {
|
|||||||
used: number;
|
used: number;
|
||||||
usagePercent: number;
|
usagePercent: number;
|
||||||
};
|
};
|
||||||
gpus: { name: string; vendor: string }[];
|
runtime: {
|
||||||
|
pid: number;
|
||||||
|
rss: number;
|
||||||
|
heapTotal: number;
|
||||||
|
heapUsed: number;
|
||||||
|
external: number;
|
||||||
|
arrayBuffers: number;
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface LogEntry {
|
export interface LogEntry {
|
||||||
|
|||||||
Generated
+3
@@ -20,6 +20,9 @@ importers:
|
|||||||
|
|
||||||
.:
|
.:
|
||||||
devDependencies:
|
devDependencies:
|
||||||
|
cross-env:
|
||||||
|
specifier: ^10.1.0
|
||||||
|
version: 10.1.0
|
||||||
typescript:
|
typescript:
|
||||||
specifier: 'catalog:'
|
specifier: 'catalog:'
|
||||||
version: 6.0.2
|
version: 6.0.2
|
||||||
|
|||||||
Reference in new issue
Block a user