Merge pull request #109 from SnowLuma/dev
chore: promote dev → main (dfb6aa5)
This commit is contained in:
60 files changed
+2932
-182
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
|
||||
@@ -45,10 +45,12 @@
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.12.2",
|
||||
"typescript": "catalog:"
|
||||
"typescript": "catalog:",
|
||||
"vitest": "^4.1.4"
|
||||
}
|
||||
}
|
||||
+106
-48
@@ -7,71 +7,102 @@ export interface RuntimeConfig {
|
||||
* the HookManager. Also overridable at runtime via SNOWLUMA_HOOK_AUTOLOAD.
|
||||
* Defaults to false; the Docker image flips it on in supervisord.conf. */
|
||||
hookAutoLoad?: boolean;
|
||||
/** WebUI listener bind address. '0.0.0.0' = all interfaces (default),
|
||||
* '127.0.0.1' = localhost-only. Listener-level: change needs a restart. */
|
||||
webuiHost?: string;
|
||||
/** WebUI TLS. Cert/key live in config/cert.pem + config/key.pem; this
|
||||
* only flips serving on/off. Listener-level: change needs a restart. */
|
||||
webuiTls?: { enabled?: boolean };
|
||||
/** Raw trust-proxy directive (same domain as SNOWLUMA_WEBUI_TRUST_PROXY),
|
||||
* consumed by the WebUI's client-ip resolver. '' = trust nobody. */
|
||||
trustProxy?: string;
|
||||
}
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const RUNTIME_CONFIG_PATH = path.join(CONFIG_DIR, 'runtime.json');
|
||||
|
||||
const DEFAULT_RUNTIME_CONFIG: RuntimeConfig = {
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
};
|
||||
const DEFAULT_WEBUI_PORT = 5099;
|
||||
const DEFAULT_WEBUI_HOST = '0.0.0.0';
|
||||
|
||||
/**
|
||||
* Pure on-disk-object → typed config normalization (defaults + validation,
|
||||
* no fs / no env). Exported for testing; `loadRuntimeConfig` wraps it.
|
||||
*/
|
||||
export function normalizeRuntimeConfig(parsed: unknown): RuntimeConfig {
|
||||
const obj = isObject(parsed) ? parsed : {};
|
||||
return {
|
||||
webuiPort: normalizePort(obj.webuiPort ?? DEFAULT_WEBUI_PORT, DEFAULT_WEBUI_PORT),
|
||||
hookAutoLoad: normalizeBool(obj.hookAutoLoad, false),
|
||||
webuiHost: normalizeHost(obj.webuiHost),
|
||||
webuiTls: { enabled: isObject(obj.webuiTls) ? normalizeBool(obj.webuiTls.enabled, false) : false },
|
||||
trustProxy: typeof obj.trustProxy === 'string' ? obj.trustProxy : '',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Pure SNOWLUMA_* env → override patch (no fs). Env wins over runtime.json
|
||||
* (a trusted launcher like SnowLumaDesktop pins these per-launch without
|
||||
* rewriting the file). Absent vars produce no key.
|
||||
*/
|
||||
export function resolveRuntimeEnvOverrides(env: NodeJS.ProcessEnv): Partial<RuntimeConfig> {
|
||||
const out: Partial<RuntimeConfig> = {};
|
||||
|
||||
const port = parsePortString(env.SNOWLUMA_WEBUI_PORT);
|
||||
if (port !== undefined) out.webuiPort = port;
|
||||
|
||||
const host = env.SNOWLUMA_WEBUI_HOST;
|
||||
if (typeof host === 'string' && host.trim()) out.webuiHost = host.trim();
|
||||
|
||||
// Present-but-"0"/"off" is a deliberate override (trust nobody), distinct
|
||||
// from "absent" — so gate on key presence, not truthiness.
|
||||
const tp = env.SNOWLUMA_WEBUI_TRUST_PROXY;
|
||||
if (typeof tp === 'string') out.trustProxy = tp;
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
export function loadRuntimeConfig(): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
|
||||
const loaded = tryLoadRuntimeConfig();
|
||||
let normalized: RuntimeConfig;
|
||||
if (!loaded) {
|
||||
saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG);
|
||||
normalized = { ...DEFAULT_RUNTIME_CONFIG };
|
||||
} else {
|
||||
normalized = {
|
||||
webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false),
|
||||
};
|
||||
if (
|
||||
normalized.webuiPort !== loaded.webuiPort
|
||||
|| normalized.hookAutoLoad !== loaded.hookAutoLoad
|
||||
) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
const parsed = tryLoadRuntimeConfig();
|
||||
const normalized = normalizeRuntimeConfig(parsed ?? {});
|
||||
|
||||
// Persist when the file is absent or when normalization changed/backfilled
|
||||
// anything (e.g. an older runtime.json lacking webuiHost/webuiTls).
|
||||
if (parsed === null || !sameRuntimeConfig(parsed, normalized)) {
|
||||
saveRuntimeConfig(normalized);
|
||||
}
|
||||
|
||||
// SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without
|
||||
// rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop)
|
||||
// pick a free port per-launch while CLI/Docker users continue to drive
|
||||
// it from runtime.json.
|
||||
const envPort = envPortOverride();
|
||||
if (envPort !== undefined) {
|
||||
normalized = { ...normalized, webuiPort: envPort };
|
||||
}
|
||||
|
||||
return normalized;
|
||||
// Env overrides apply in-memory only — never written back to disk.
|
||||
return { ...normalized, ...resolveRuntimeEnvOverrides(process.env) };
|
||||
}
|
||||
|
||||
function envPortOverride(): number | undefined {
|
||||
const raw = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
if (!raw || typeof raw !== 'string') return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
/**
|
||||
* Read the persisted config (normalized, no env overrides, no write). For the
|
||||
* settings panel's GET — shows what's actually saved/editable on disk.
|
||||
*/
|
||||
export function readRuntimeConfig(): RuntimeConfig {
|
||||
return normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): RuntimeConfig | null {
|
||||
/**
|
||||
* Persist a partial update. Merges onto the ON-DISK config (not the env-merged
|
||||
* runtime view) so an env override (e.g. SNOWLUMA_WEBUI_PORT) is never baked
|
||||
* into runtime.json. Returns the new persisted config (without env overrides).
|
||||
*/
|
||||
export function updateRuntimeConfig(patch: Partial<RuntimeConfig>): RuntimeConfig {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
const onDisk = normalizeRuntimeConfig(tryLoadRuntimeConfig() ?? {});
|
||||
const next = normalizeRuntimeConfig({ ...onDisk, ...patch });
|
||||
saveRuntimeConfig(next);
|
||||
return next;
|
||||
}
|
||||
|
||||
function tryLoadRuntimeConfig(): Record<string, unknown> | null {
|
||||
if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null;
|
||||
|
||||
try {
|
||||
const raw = fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8');
|
||||
const parsed = JSON.parse(raw) as unknown;
|
||||
if (!isObject(parsed)) return null;
|
||||
|
||||
return {
|
||||
webuiPort: normalizePort(parsed.webuiPort ?? 5099, 5099),
|
||||
hookAutoLoad: normalizeBool(parsed.hookAutoLoad, false),
|
||||
};
|
||||
const parsed = JSON.parse(fs.readFileSync(RUNTIME_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isObject(parsed) ? parsed : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -81,6 +112,33 @@ function saveRuntimeConfig(config: RuntimeConfig): void {
|
||||
fs.writeFileSync(RUNTIME_CONFIG_PATH, JSON.stringify(config, null, 2), 'utf8');
|
||||
}
|
||||
|
||||
/** True when the raw on-disk object already matches the normalized config
|
||||
* on every known field (so we can skip a needless rewrite). */
|
||||
function sameRuntimeConfig(parsed: Record<string, unknown>, n: RuntimeConfig): boolean {
|
||||
const parsedTls = isObject(parsed.webuiTls) ? parsed.webuiTls.enabled : undefined;
|
||||
return (
|
||||
parsed.webuiPort === n.webuiPort
|
||||
&& parsed.hookAutoLoad === n.hookAutoLoad
|
||||
&& parsed.webuiHost === n.webuiHost
|
||||
&& parsedTls === n.webuiTls?.enabled
|
||||
&& parsed.trustProxy === n.trustProxy
|
||||
);
|
||||
}
|
||||
|
||||
function parsePortString(raw: unknown): number | undefined {
|
||||
if (typeof raw !== 'string' || !raw.trim()) return undefined;
|
||||
const n = Number(raw.trim());
|
||||
if (!Number.isFinite(n)) return undefined;
|
||||
const port = Math.trunc(n);
|
||||
if (port <= 0 || port > 65535) return undefined;
|
||||
return port;
|
||||
}
|
||||
|
||||
function normalizeHost(value: unknown): string {
|
||||
if (typeof value === 'string' && value.trim()) return value.trim();
|
||||
return DEFAULT_WEBUI_HOST;
|
||||
}
|
||||
|
||||
function normalizePort(value: unknown, fallback: number): number {
|
||||
if (typeof value === 'number' && Number.isFinite(value)) {
|
||||
const n = Math.trunc(value);
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import { normalizeRuntimeConfig, resolveRuntimeEnvOverrides } from '../src/runtime';
|
||||
|
||||
describe('normalizeRuntimeConfig', () => {
|
||||
it('applies all defaults for an empty object', () => {
|
||||
expect(normalizeRuntimeConfig({})).toEqual({
|
||||
webuiPort: 5099,
|
||||
hookAutoLoad: false,
|
||||
webuiHost: '0.0.0.0',
|
||||
webuiTls: { enabled: false },
|
||||
trustProxy: '',
|
||||
});
|
||||
});
|
||||
|
||||
it('passes through valid values', () => {
|
||||
expect(normalizeRuntimeConfig({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
})).toEqual({
|
||||
webuiPort: 8080,
|
||||
hookAutoLoad: true,
|
||||
webuiHost: '127.0.0.1',
|
||||
webuiTls: { enabled: true },
|
||||
trustProxy: '1',
|
||||
});
|
||||
});
|
||||
|
||||
it('falls back on invalid types', () => {
|
||||
const out = normalizeRuntimeConfig({
|
||||
webuiPort: 0, // out of range → default
|
||||
webuiHost: 123, // non-string → default
|
||||
webuiTls: 'yes', // non-object → default
|
||||
trustProxy: 5, // non-string → default
|
||||
});
|
||||
expect(out.webuiPort).toBe(5099);
|
||||
expect(out.webuiHost).toBe('0.0.0.0');
|
||||
expect(out.webuiTls).toEqual({ enabled: false });
|
||||
expect(out.trustProxy).toBe('');
|
||||
});
|
||||
|
||||
it('coerces webuiTls.enabled loosely and trims a blank host to default', () => {
|
||||
expect(normalizeRuntimeConfig({ webuiTls: { enabled: 1 } }).webuiTls).toEqual({ enabled: true });
|
||||
expect(normalizeRuntimeConfig({ webuiHost: ' ' }).webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
|
||||
it('rejects a non-object input back to full defaults', () => {
|
||||
expect(normalizeRuntimeConfig(null).webuiPort).toBe(5099);
|
||||
expect(normalizeRuntimeConfig('nope').webuiHost).toBe('0.0.0.0');
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRuntimeEnvOverrides', () => {
|
||||
it('returns empty when no SNOWLUMA_* vars are set', () => {
|
||||
expect(resolveRuntimeEnvOverrides({})).toEqual({});
|
||||
});
|
||||
|
||||
it('parses port / host / trustProxy from env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({
|
||||
SNOWLUMA_WEBUI_PORT: '6700',
|
||||
SNOWLUMA_WEBUI_HOST: '127.0.0.1',
|
||||
SNOWLUMA_WEBUI_TRUST_PROXY: '1',
|
||||
})).toEqual({ webuiPort: 6700, webuiHost: '127.0.0.1', trustProxy: '1' });
|
||||
});
|
||||
|
||||
it('ignores an out-of-range / non-numeric port env', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: '0' })).toEqual({});
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_PORT: 'abc' })).toEqual({});
|
||||
});
|
||||
|
||||
it('treats trustProxy="0"/"off" as a real override (not absent)', () => {
|
||||
expect(resolveRuntimeEnvOverrides({ SNOWLUMA_WEBUI_TRUST_PROXY: '0' })).toEqual({ trustProxy: '0' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('updateRuntimeConfig (fs)', () => {
|
||||
let prevCwd: string;
|
||||
let dir: string;
|
||||
let prevPortEnv: string | undefined;
|
||||
beforeEach(async () => {
|
||||
const fs = await import('fs'); const os = await import('os'); const path = await import('path');
|
||||
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-rt-'));
|
||||
prevCwd = process.cwd();
|
||||
process.chdir(dir);
|
||||
prevPortEnv = process.env.SNOWLUMA_WEBUI_PORT;
|
||||
delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
});
|
||||
afterEach(async () => {
|
||||
const fs = await import('fs');
|
||||
process.chdir(prevCwd);
|
||||
if (prevPortEnv === undefined) delete process.env.SNOWLUMA_WEBUI_PORT;
|
||||
else process.env.SNOWLUMA_WEBUI_PORT = prevPortEnv;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('merges a patch over on-disk values and persists normalized', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
const out = updateRuntimeConfig({ webuiHost: '127.0.0.1', webuiTls: { enabled: true } });
|
||||
expect(out.webuiHost).toBe('127.0.0.1');
|
||||
expect(out.webuiTls).toEqual({ enabled: true });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiHost).toBe('127.0.0.1');
|
||||
expect(onDisk.webuiTls).toEqual({ enabled: true });
|
||||
});
|
||||
|
||||
it('does NOT bake an env-overridden port into the persisted file', async () => {
|
||||
const { updateRuntimeConfig } = await import('../src/runtime');
|
||||
const fs = await import('fs'); const path = await import('path');
|
||||
process.env.SNOWLUMA_WEBUI_PORT = '9999';
|
||||
updateRuntimeConfig({ webuiHost: '127.0.0.1' });
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join('config', 'runtime.json'), 'utf8'));
|
||||
expect(onDisk.webuiPort).toBe(5099); // default on-disk, NOT the env 9999
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,10 @@
|
||||
// Vitest config for @snowluma/common. Pure-TS package (no proton), so a
|
||||
// plain node-environment runner over tests/ is enough.
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
test: {
|
||||
include: ['tests/**/*.test.ts'],
|
||||
environment: 'node',
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -21,6 +21,7 @@ import { GetPrivateVideoUrl } from '@snowluma/protocol/oidb-services/group-file/
|
||||
import { ListGroupFilesPage } from '@snowluma/protocol/oidb-services/group-file/list-group-files-page';
|
||||
import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move-group-file';
|
||||
import { PublishGroupFile } from '@snowluma/protocol/oidb-services/group-file/publish-group-file';
|
||||
import { RenameGroupFile } from '@snowluma/protocol/oidb-services/group-file/rename-group-file';
|
||||
import { RenameGroupFolder } from '@snowluma/protocol/oidb-services/group-file/rename-group-folder';
|
||||
import { UploadGroupFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-group-file-request';
|
||||
import { UploadPrivateFileRequest } from '@snowluma/protocol/oidb-services/group-file/upload-private-file-request';
|
||||
@@ -604,6 +605,10 @@ export class GroupFileApi {
|
||||
return MoveGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, targetDirectory });
|
||||
}
|
||||
|
||||
rename(groupId: number, fileId: string, parentDirectory: string, newFileName: string): Promise<void> {
|
||||
return RenameGroupFile.invoke(this.ctx, { groupId, fileId, parentDirectory, newFileName });
|
||||
}
|
||||
|
||||
// ─────────────── folders ───────────────
|
||||
|
||||
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc
|
||||
import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign';
|
||||
import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh';
|
||||
import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key';
|
||||
import { ImageOcr, type OcrResult } from '@snowluma/protocol/oidb-services/misc/image-ocr';
|
||||
|
||||
export class MiscApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
@@ -18,6 +19,10 @@ export class MiscApi {
|
||||
return TranslateEnToZh.invoke(this.ctx, { words });
|
||||
}
|
||||
|
||||
ocrImage(imageUrl: string): Promise<OcrResult> {
|
||||
return ImageOcr.invoke(this.ctx, { imageUrl });
|
||||
}
|
||||
|
||||
async getMiniAppArk(type: string, title: string, desc: string, picUrl: string, jumpUrl: string): Promise<JsonObject> {
|
||||
let appid = '1109937557'; // default: bilibili
|
||||
let iconUrl = 'http://miniapp.gtimg.cn/public/appicon/51f90239b78a2e4994c11215f4c4ba15_200.jpg';
|
||||
|
||||
@@ -48,7 +48,11 @@ async function main() {
|
||||
) {
|
||||
try {
|
||||
const { initWebUI } = await import('./webui/server');
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager);
|
||||
await initWebUI(runtimeConfig.webuiPort || 5099, oneBotManager, hookManager, notificationManager, {
|
||||
host: runtimeConfig.webuiHost,
|
||||
tlsEnabled: runtimeConfig.webuiTls?.enabled,
|
||||
trustProxy: runtimeConfig.trustProxy,
|
||||
});
|
||||
} catch (err) {
|
||||
log.error('Failed to start WebUI: ', err);
|
||||
}
|
||||
|
||||
@@ -48,9 +48,13 @@ export interface NotificationsConfig {
|
||||
channels: NotificationChannel[];
|
||||
}
|
||||
|
||||
/** A neutral plaintext starting point; the WebUI ships per-vendor presets
|
||||
* (钉钉/Discord/…) as frontend constants the operator can drop in. */
|
||||
export const DEFAULT_BODY_TEMPLATE = '{nickname}({uin}) {event} @ {time}';
|
||||
/** Default body template — Server酱-style JSON ({title}/{desp}). The WebUI
|
||||
* ships additional per-vendor presets (钉钉/Discord/…) as frontend constants
|
||||
* the operator can drop in. */
|
||||
export const DEFAULT_BODY_TEMPLATE = `{
|
||||
"title": "账号状态通知:{event}",
|
||||
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
|
||||
}`;
|
||||
|
||||
export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
return {
|
||||
@@ -67,12 +71,25 @@ export function defaultNotificationsConfig(): NotificationsConfig {
|
||||
* A key present in `vars` is replaced by its value; an unknown `{key}` is left
|
||||
* untouched (原样) so a typo'd placeholder is visible rather than silently
|
||||
* blanked. Pure + total (a non-string template yields '').
|
||||
*
|
||||
* **JSON safety**: When the template is valid JSON (parseable by JSON.parse),
|
||||
* values are escaped to prevent breaking the JSON structure — backslashes
|
||||
* become `\\` and double-quotes become `\"`.
|
||||
*/
|
||||
export function renderTemplate(template: string, vars: Record<string, string>): string {
|
||||
if (typeof template !== 'string') return '';
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) =>
|
||||
Object.prototype.hasOwnProperty.call(vars, key) ? vars[key] : match,
|
||||
);
|
||||
let isJson = false;
|
||||
try {
|
||||
JSON.parse(template);
|
||||
isJson = true;
|
||||
} catch {
|
||||
// not JSON — plain text mode
|
||||
}
|
||||
return template.replace(/\{(\w+)\}/g, (match, key: string) => {
|
||||
if (!Object.prototype.hasOwnProperty.call(vars, key)) return match;
|
||||
const val = vars[key];
|
||||
return isJson ? val.replace(/\\/g, '\\\\').replace(/"/g, '\\"') : val;
|
||||
});
|
||||
}
|
||||
|
||||
// ─── Normalization helpers (replicated from ui-config conventions) ──────────
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// WebUI config backup/restore (Wave A2). Format: a zero-dep JSON bundle
|
||||
// { version, app, createdAt, files: { "<name>": { encoding, data } } }
|
||||
// over an explicit allowlist (never a whole-dir sweep) so a stray/unknown file
|
||||
// can't leak and an import can't path-traverse.
|
||||
//
|
||||
// Credentials are gated by a toggle on both export and import. The credential
|
||||
// set is: webui.json (password hash), key.pem (TLS private key), AND every
|
||||
// OneBot config (onebot.json + per-account onebot_<uin>.json) — those carry the
|
||||
// OneBot access token, so a no-credentials backup must NOT include them.
|
||||
// cert.pem is public so it always travels.
|
||||
//
|
||||
// Pure functions here (read/list/decode); the fs glue (atomic two-phase write,
|
||||
// snapshot) lives in server.ts. Restore is restart-to-apply, like A1.
|
||||
|
||||
export const BACKUP_VERSION = 1;
|
||||
export const BACKUP_APP = 'snowluma';
|
||||
|
||||
export interface BackupFileSpec {
|
||||
/** Path relative to the config dir; also the bundle key. */
|
||||
name: string;
|
||||
binary: boolean;
|
||||
/** Sensitive (private key / password hash / access token) — credential-gated. */
|
||||
credential: boolean;
|
||||
}
|
||||
|
||||
/** Static allowlist. Per-account `onebot_<uin>.json` are matched by pattern. */
|
||||
export const BACKUP_FILES: readonly BackupFileSpec[] = [
|
||||
{ name: 'runtime.json', binary: false, credential: false },
|
||||
{ name: 'ui.json', binary: false, credential: false },
|
||||
{ name: 'notifications.json', binary: false, credential: false },
|
||||
{ name: 'cert.pem', binary: false, credential: false },
|
||||
{ name: 'ui-assets/background', binary: true, credential: false },
|
||||
{ name: 'webui.json', binary: false, credential: true },
|
||||
{ name: 'key.pem', binary: false, credential: true },
|
||||
// OneBot config carries the access token → credential.
|
||||
{ name: 'onebot.json', binary: false, credential: true },
|
||||
];
|
||||
|
||||
const SPEC_BY_NAME = new Map(BACKUP_FILES.map((f) => [f.name, f]));
|
||||
const PER_UIN_ONEBOT = /^onebot_\d+\.json$/;
|
||||
|
||||
/** Resolve a file name (static or per-uin onebot pattern) to its spec, or null. */
|
||||
export function specFor(name: string): BackupFileSpec | null {
|
||||
const s = SPEC_BY_NAME.get(name);
|
||||
if (s) return s;
|
||||
if (PER_UIN_ONEBOT.test(name)) return { name, binary: false, credential: true };
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface BackupEntry { encoding: 'utf8' | 'base64'; data: string }
|
||||
export interface Backup {
|
||||
version: number;
|
||||
app: string;
|
||||
createdAt?: string;
|
||||
files: Record<string, BackupEntry>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assemble a bundle from the allowlist plus any per-account onebot files.
|
||||
* `readFile` returns null for missing.
|
||||
*/
|
||||
export function buildBackup(
|
||||
readFile: (name: string) => Buffer | null,
|
||||
perUinOnebotNames: readonly string[],
|
||||
opts: { includeCredentials: boolean },
|
||||
createdAt: string,
|
||||
): Backup {
|
||||
const files: Record<string, BackupEntry> = {};
|
||||
const all: BackupFileSpec[] = [
|
||||
...BACKUP_FILES,
|
||||
...perUinOnebotNames.filter((n) => PER_UIN_ONEBOT.test(n)).map((n) => ({ name: n, binary: false, credential: true })),
|
||||
];
|
||||
for (const spec of all) {
|
||||
if (spec.credential && !opts.includeCredentials) continue;
|
||||
const buf = readFile(spec.name);
|
||||
if (!buf) continue;
|
||||
files[spec.name] = spec.binary
|
||||
? { encoding: 'base64', data: buf.toString('base64') }
|
||||
: { encoding: 'utf8', data: buf.toString('utf8') };
|
||||
}
|
||||
return { version: BACKUP_VERSION, app: BACKUP_APP, createdAt, files };
|
||||
}
|
||||
|
||||
/** Validate a parsed bundle wholesale — any defect rejects the whole import. */
|
||||
export function validateBackup(parsed: unknown): { ok: true; backup: Backup } | { ok: false; error: string } {
|
||||
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
|
||||
return { ok: false, error: 'backup must be an object' };
|
||||
}
|
||||
const b = parsed as Record<string, unknown>;
|
||||
if (b.app !== BACKUP_APP) return { ok: false, error: 'not a SnowLuma backup' };
|
||||
if (b.version !== BACKUP_VERSION) return { ok: false, error: `unsupported backup version ${String(b.version)}` };
|
||||
if (typeof b.files !== 'object' || b.files === null || Array.isArray(b.files)) {
|
||||
return { ok: false, error: 'backup.files must be an object' };
|
||||
}
|
||||
const files = b.files as Record<string, unknown>;
|
||||
for (const [name, entry] of Object.entries(files)) {
|
||||
if (!specFor(name)) return { ok: false, error: `unknown file in backup: ${name}` };
|
||||
if (typeof entry !== 'object' || entry === null) return { ok: false, error: `malformed entry: ${name}` };
|
||||
const e = entry as Record<string, unknown>;
|
||||
if (e.encoding !== 'utf8' && e.encoding !== 'base64') return { ok: false, error: `bad encoding for ${name}` };
|
||||
if (typeof e.data !== 'string') return { ok: false, error: `bad data for ${name}` };
|
||||
}
|
||||
return { ok: true, backup: { version: BACKUP_VERSION, app: BACKUP_APP, createdAt: typeof b.createdAt === 'string' ? b.createdAt : undefined, files: files as Record<string, BackupEntry> } };
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide what a (validated) bundle would restore: decode each non-skipped file
|
||||
* to bytes. Pure — the caller (server.ts) does the atomic two-phase fs write so
|
||||
* a mid-restore failure can't leave a half-applied live config. Credential
|
||||
* files are skipped unless `restoreCredentials`.
|
||||
*/
|
||||
export function planRestore(
|
||||
backup: Backup,
|
||||
opts: { restoreCredentials: boolean },
|
||||
): { restore: Array<{ name: string; data: Buffer }>; skipped: string[] } {
|
||||
const restore: Array<{ name: string; data: Buffer }> = [];
|
||||
const skipped: string[] = [];
|
||||
for (const [name, entry] of Object.entries(backup.files)) {
|
||||
const spec = specFor(name);
|
||||
if (!spec) { skipped.push(name); continue; } // validated, but be defensive
|
||||
if (spec.credential && !opts.restoreCredentials) { skipped.push(name); continue; }
|
||||
restore.push({ name, data: Buffer.from(entry.data, entry.encoding) });
|
||||
}
|
||||
return { restore, skipped };
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// SSE frame pusher for the debug stream (Wave A3). Drops frames under
|
||||
// backpressure (consumer slow → desiredSize <= 0) instead of buffering
|
||||
// unbounded into memory, and coalesces the drop count into a {kind:'dropped'}
|
||||
// marker emitted just before the next delivered frame. Extracted from the route
|
||||
// handler so this (easy-to-get-wrong) logic is unit-tested.
|
||||
|
||||
export interface FramePusherOptions {
|
||||
/** The stream controller's current desiredSize (null = no backpressure info). */
|
||||
desiredSize: () => number | null;
|
||||
/** Deliver an encoded SSE chunk (the caller maps this to the controller). */
|
||||
enqueue: (chunk: Uint8Array) => void;
|
||||
encode?: (s: string) => Uint8Array;
|
||||
}
|
||||
|
||||
/** Returns a `push(payload)` that frames + delivers with backpressure dropping. */
|
||||
export function createFramePusher(opts: FramePusherOptions): (payload: unknown) => void {
|
||||
const encode = opts.encode ?? ((s: string) => new TextEncoder().encode(s));
|
||||
let dropped = 0;
|
||||
return (payload: unknown): void => {
|
||||
const d = opts.desiredSize();
|
||||
if (d !== null && d <= 0) { dropped += 1; return; }
|
||||
if (dropped > 0) {
|
||||
opts.enqueue(encode(`data: ${JSON.stringify({ kind: 'dropped', count: dropped })}\n\n`));
|
||||
dropped = 0;
|
||||
}
|
||||
opts.enqueue(encode(`data: ${JSON.stringify(payload)}\n\n`));
|
||||
};
|
||||
}
|
||||
@@ -4,14 +4,21 @@ import type { HookManager, HookProcessInfo } from '@snowluma/bridge';
|
||||
import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
|
||||
import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config';
|
||||
import type { OneBotManager } from '@snowluma/onebot/manager';
|
||||
import type { OneBotConfig } from '@snowluma/onebot/types';
|
||||
import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types';
|
||||
import { readRuntimeConfig, updateRuntimeConfig, resolveRuntimeEnvOverrides } from '@snowluma/common/runtime';
|
||||
import { randomBytes } from 'crypto';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'fs';
|
||||
import { createServer as createHttpsServer } from 'https';
|
||||
import { Hono, type Context } from 'hono';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
|
||||
import { resolveTlsContext, validateTlsPair } from './tls';
|
||||
import { coerceSettingsPatch } from './system-settings';
|
||||
import { buildBackup, planRestore, validateBackup } from './backup';
|
||||
import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs';
|
||||
import { createFramePusher } from './debug-stream';
|
||||
import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip';
|
||||
import { findAvailablePort } from './port';
|
||||
import {
|
||||
@@ -60,6 +67,7 @@ const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
// into access logs / Referer / browser history.
|
||||
const TOKEN_QUERY_ALLOWLIST = new Set([
|
||||
'/api/logs/stream',
|
||||
'/api/debug/stream',
|
||||
]);
|
||||
|
||||
// uin = QQ number; 5–12 digits. Used to construct config file paths,
|
||||
@@ -78,14 +86,6 @@ function purgeExpiredTokens() {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the client IP for per-IP rate limiting. Default is the TCP
|
||||
* socket peer (cannot be spoofed by the client). Operators behind a
|
||||
* reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env
|
||||
* var; see `./client-ip.ts` for the accepted values.
|
||||
*/
|
||||
const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
|
||||
async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> {
|
||||
const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, {
|
||||
@@ -105,7 +105,19 @@ export async function initWebUI(
|
||||
oneBotManager: OneBotManager,
|
||||
hookManager?: HookManager,
|
||||
notificationManager?: NotificationManager,
|
||||
listener: { host?: string; tlsEnabled?: boolean; trustProxy?: string } = {},
|
||||
): Promise<{ port: number }> {
|
||||
// Resolve the client IP for per-IP rate limiting from the configured
|
||||
// trust-proxy directive (runtime.json `trustProxy`, env-overridable via
|
||||
// SNOWLUMA_WEBUI_TRUST_PROXY which loadRuntimeConfig already merged in).
|
||||
// Default ('') = trust the TCP socket peer only (cannot be spoofed).
|
||||
const trustProxyMode = parseTrustProxy(listener.trustProxy);
|
||||
const getClientIp = makeClientIpResolver(trustProxyMode);
|
||||
|
||||
// Actual bound port (set just before serve; findAvailablePort may bump it).
|
||||
// Read by GET /api/system/settings so the panel shows what's really live.
|
||||
let boundPort = desiredPort;
|
||||
|
||||
const auth = WebuiAuth.load();
|
||||
const initialPassword = auth.takeInitialPassword();
|
||||
if (auth.isDevMode()) {
|
||||
@@ -395,6 +407,252 @@ export async function initWebUI(
|
||||
});
|
||||
});
|
||||
|
||||
// ── System settings (WebUI listener) — Wave A1 ──
|
||||
// Listener-level changes (port/host/TLS) are persisted but apply only on the
|
||||
// next restart (no supervisor → no self-restart). The panel surfaces which
|
||||
// fields are currently overridden by env so edits that won't take effect are
|
||||
// visible.
|
||||
const SYSTEM_CERT_PATH = path.join('config', 'cert.pem');
|
||||
const SYSTEM_KEY_PATH = path.join('config', 'key.pem');
|
||||
const hasCert = (): boolean => existsSync(SYSTEM_CERT_PATH) && existsSync(SYSTEM_KEY_PATH);
|
||||
|
||||
app.get('/api/system/settings', (c) => {
|
||||
const disk = readRuntimeConfig();
|
||||
const envOverrides = Object.keys(resolveRuntimeEnvOverrides(process.env));
|
||||
return c.json({
|
||||
settings: {
|
||||
webuiPort: disk.webuiPort,
|
||||
webuiHost: disk.webuiHost,
|
||||
tlsEnabled: disk.webuiTls?.enabled ?? false,
|
||||
trustProxy: disk.trustProxy ?? '',
|
||||
},
|
||||
hasCert: hasCert(),
|
||||
envOverrides, // field names currently pinned by SNOWLUMA_* env vars
|
||||
listeningPort: boundPort,
|
||||
restartRequiredToApply: true,
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/system/settings', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const coerced = coerceSettingsPatch(body);
|
||||
if (!coerced.ok) return c.json({ success: false, message: coerced.error }, 400);
|
||||
// Enabling TLS without a usable cert would brick HTTPS on restart — block it.
|
||||
if (coerced.patch.webuiTls?.enabled && !resolveTlsContext('config').ok) {
|
||||
return c.json({ success: false, message: '启用 TLS 前请先上传有效的证书与私钥' }, 400);
|
||||
}
|
||||
const saved = updateRuntimeConfig(coerced.patch);
|
||||
return c.json({
|
||||
success: true,
|
||||
settings: {
|
||||
webuiPort: saved.webuiPort,
|
||||
webuiHost: saved.webuiHost,
|
||||
tlsEnabled: saved.webuiTls?.enabled ?? false,
|
||||
trustProxy: saved.trustProxy ?? '',
|
||||
},
|
||||
restartRequiredToApply: true,
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/api/system/tls/cert', async (c) => {
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const cert = (body as { cert?: unknown }).cert;
|
||||
const key = (body as { key?: unknown }).key;
|
||||
if (typeof cert !== 'string' || typeof key !== 'string') {
|
||||
return c.json({ success: false, message: 'cert 和 key 必须为 PEM 字符串' }, 400);
|
||||
}
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) return c.json({ success: false, message: valid.reason }, 400);
|
||||
try {
|
||||
mkdirSync('config', { recursive: true });
|
||||
writeFileSync(SYSTEM_CERT_PATH, cert.endsWith('\n') ? cert : cert + '\n', 'utf8');
|
||||
// Private key must not be world-readable (mirrors auth.ts's webui.json
|
||||
// 0600). writeFileSync's mode is ignored for an existing file, so chmod
|
||||
// explicitly afterwards.
|
||||
writeFileSync(SYSTEM_KEY_PATH, key.endsWith('\n') ? key : key + '\n', { encoding: 'utf8', mode: 0o600 });
|
||||
// Best-effort (mirrors auth.ts): the key is already written 0600 above, so
|
||||
// a rare chmod failure must not fail the request.
|
||||
try { chmodSync(SYSTEM_KEY_PATH, 0o600); } catch { /* best-effort */ }
|
||||
} catch (err) {
|
||||
log.warn('write cert/key failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '写入证书失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
return c.json({ success: true, restartRequiredToApply: true });
|
||||
});
|
||||
|
||||
app.delete('/api/system/tls/cert', (c) => {
|
||||
try {
|
||||
rmSync(SYSTEM_CERT_PATH, { force: true });
|
||||
rmSync(SYSTEM_KEY_PATH, { force: true });
|
||||
} catch (err) {
|
||||
log.warn('remove cert/key failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '删除证书失败' }, 500);
|
||||
}
|
||||
return c.json({ success: true });
|
||||
});
|
||||
|
||||
// ── Config backup / restore (Wave A2) ──
|
||||
const cfgPath = (name: string) => path.join('config', name);
|
||||
const readCfg = (name: string): Buffer | null => {
|
||||
const p = cfgPath(name);
|
||||
return existsSync(p) ? readFileSync(p) : null;
|
||||
};
|
||||
|
||||
const listPerUinOnebot = (): string[] => {
|
||||
try {
|
||||
return existsSync('config') ? readdirSync('config').filter((n) => /^onebot_\d+\.json$/.test(n)) : [];
|
||||
} catch { return []; }
|
||||
};
|
||||
|
||||
app.get('/api/system/backup/export', (c) => {
|
||||
const includeCredentials = c.req.query('credentials') === '1';
|
||||
const ts = new Date().toISOString();
|
||||
const bundle = buildBackup(readCfg, listPerUinOnebot(), { includeCredentials }, ts);
|
||||
c.header('Content-Disposition', `attachment; filename="snowluma-backup-${ts.replace(/[:.]/g, '-')}.json"`);
|
||||
// Bundle may carry the TLS private key / password hash — never cache it.
|
||||
c.header('Cache-Control', 'no-store, max-age=0');
|
||||
c.header('Pragma', 'no-cache');
|
||||
return c.json(bundle);
|
||||
});
|
||||
|
||||
app.post('/api/system/backup/import', async (c) => {
|
||||
const declaredLen = Number(c.req.header('content-length'));
|
||||
if (Number.isFinite(declaredLen) && declaredLen > 32 * 1024 * 1024) {
|
||||
return c.json({ success: false, message: '备份文件过大' }, 413);
|
||||
}
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
if (typeof body !== 'object' || body === null) {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const { backup, restoreCredentials } = body as { backup?: unknown; restoreCredentials?: unknown };
|
||||
const v = validateBackup(backup);
|
||||
if (!v.ok) return c.json({ success: false, message: v.error }, 400);
|
||||
|
||||
const plan = planRestore(v.backup, { restoreCredentials: restoreCredentials === true });
|
||||
// Snapshot the current (about-to-be-overwritten) config so a restore is
|
||||
// recoverable; one timestamped dir per import.
|
||||
const snapDir = path.join('config', `.restore-backup-${new Date().toISOString().replace(/[:.]/g, '-')}`);
|
||||
// Two-phase write for near-atomicity: stage every file as a .tmp first, then
|
||||
// rename them all. A failure during staging touches no live file; rename
|
||||
// almost never fails, shrinking the half-applied window to near zero.
|
||||
const staged: Array<{ tmp: string; dest: string; name: string }> = [];
|
||||
try {
|
||||
for (const { name } of plan.restore) {
|
||||
const src = cfgPath(name);
|
||||
if (!existsSync(src)) continue;
|
||||
const snap = path.join(snapDir, name);
|
||||
mkdirSync(path.dirname(snap), { recursive: true });
|
||||
copyFileSync(src, snap);
|
||||
}
|
||||
for (const { name, data } of plan.restore) {
|
||||
const dest = cfgPath(name);
|
||||
mkdirSync(path.dirname(dest), { recursive: true });
|
||||
const tmp = dest + '.restore.tmp';
|
||||
writeFileSync(tmp, data, name === 'key.pem' ? { mode: 0o600 } : undefined);
|
||||
staged.push({ tmp, dest, name });
|
||||
}
|
||||
for (const { tmp, dest, name } of staged) {
|
||||
renameSync(tmp, dest);
|
||||
if (name === 'key.pem') { try { chmodSync(dest, 0o600); } catch { /* best-effort */ } }
|
||||
}
|
||||
return c.json({
|
||||
success: true,
|
||||
restored: plan.restore.map((r) => r.name),
|
||||
skipped: plan.skipped,
|
||||
snapshotDir: snapDir,
|
||||
restartRequiredToApply: true,
|
||||
});
|
||||
} catch (err) {
|
||||
// Clean up any staged .tmp not yet renamed (staging-phase failure leaves
|
||||
// the live config untouched; a rare rename-phase failure may be partial,
|
||||
// recoverable from the snapshot dir).
|
||||
for (const { tmp } of staged) { try { if (existsSync(tmp)) rmSync(tmp, { force: true }); } catch { /* ignore */ } }
|
||||
log.warn('backup import failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '恢复失败;若为写入阶段失败则当前配置未改动,否则可从 config/.restore-backup-* 快照恢复' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ── Debug tools (Wave A3) ──
|
||||
// Action schemas for the tester form (declarative actions only; legacy ones
|
||||
// are invoked freeform).
|
||||
app.get('/api/debug/actions', (c) =>
|
||||
c.json({ actions: collectActionDocs(), categories: collectCategories() }));
|
||||
|
||||
// Manually invoke an action against one account. Real side effects — gated by
|
||||
// the same /api/* auth.
|
||||
app.post('/api/debug/invoke', async (c) => {
|
||||
let body: unknown;
|
||||
try { body = await c.req.json(); } catch { return c.json({ status: 'failed', message: '请求格式错误' }, 400); }
|
||||
const { uin, action, params } = (body ?? {}) as { uin?: unknown; action?: unknown; params?: unknown };
|
||||
if (typeof uin !== 'string' || !UIN_REGEX.test(uin)) return c.json({ status: 'failed', message: '无效的账号' }, 400);
|
||||
if (typeof action !== 'string' || !action) return c.json({ status: 'failed', message: 'action 必填' }, 400);
|
||||
if (params !== undefined && (typeof params !== 'object' || params === null || Array.isArray(params))) {
|
||||
return c.json({ status: 'failed', message: 'params 必须是对象' }, 400);
|
||||
}
|
||||
const inst = oneBotManager.getInstance(uin);
|
||||
if (!inst) return c.json({ status: 'failed', message: '账号不在线' }, 404);
|
||||
const result = await inst.invokeAction(action, (params ?? {}) as OneBotJsonObject);
|
||||
return c.json(result);
|
||||
});
|
||||
|
||||
// Live merged SSE of OneBot events + action calls across all accounts. Taps
|
||||
// are attached only while a client is connected (on-demand). A slow client is
|
||||
// dropped (not back-pressured onto the bot) with a periodic drop marker.
|
||||
app.get('/api/debug/stream', (c) => {
|
||||
const stream = new ReadableStream({
|
||||
start(controller) {
|
||||
const encoder = new TextEncoder();
|
||||
let closed = false;
|
||||
const offs: Array<() => void> = [];
|
||||
let heartbeat: NodeJS.Timeout | undefined;
|
||||
const teardown = () => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (heartbeat) clearInterval(heartbeat);
|
||||
for (const off of offs) { try { off(); } catch { /* ignore */ } }
|
||||
try { controller.close(); } catch { /* ignore */ }
|
||||
};
|
||||
const raw = (chunk: Uint8Array) => {
|
||||
if (closed) return;
|
||||
try { controller.enqueue(chunk); } catch { teardown(); }
|
||||
};
|
||||
// Drop-under-backpressure framing (unit-tested in debug-stream.ts).
|
||||
const pushFrame = createFramePusher({
|
||||
desiredSize: () => controller.desiredSize,
|
||||
enqueue: raw,
|
||||
encode: (s) => encoder.encode(s),
|
||||
});
|
||||
const send = (payload: unknown) => { if (!closed) pushFrame(payload); };
|
||||
send({ kind: 'ready' });
|
||||
for (const inst of oneBotManager.getInstances()) {
|
||||
const uin = inst.uin;
|
||||
offs.push(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event })));
|
||||
offs.push(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec })));
|
||||
}
|
||||
heartbeat = setInterval(() => raw(encoder.encode(': heartbeat\n\n')), 15000);
|
||||
c.req.raw.signal.addEventListener('abort', teardown);
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' },
|
||||
});
|
||||
});
|
||||
|
||||
app.get('/api/qq-list', (c) => {
|
||||
const instances = oneBotManager.getInstances();
|
||||
const list = instances.map((inst) => ({ uin: inst.uin, nickname: inst.nickname }));
|
||||
@@ -708,10 +966,27 @@ export async function initWebUI(
|
||||
if (finalPort !== desiredPort) {
|
||||
log.warn('port %d is in use, using %d instead', desiredPort, finalPort);
|
||||
}
|
||||
boundPort = finalPort;
|
||||
|
||||
const host = listener.host || '0.0.0.0';
|
||||
|
||||
// TLS: only when explicitly enabled AND the on-disk cert/key load. A bad
|
||||
// or missing cert must never brick the WebUI — fall back to HTTP + warn.
|
||||
let tlsServe: { createServer: typeof createHttpsServer; serverOptions: { cert: Buffer; key: Buffer } } | undefined;
|
||||
let scheme = 'http';
|
||||
if (listener.tlsEnabled) {
|
||||
const tls = resolveTlsContext('config');
|
||||
if (tls.ok && tls.cert && tls.key) {
|
||||
tlsServe = { createServer: createHttpsServer, serverOptions: { cert: tls.cert, key: tls.key } };
|
||||
scheme = 'https';
|
||||
} else {
|
||||
log.warn('TLS enabled but cert/key unusable (%s) — serving over HTTP instead', tls.reason);
|
||||
}
|
||||
}
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
serve({ fetch: app.fetch, port: finalPort }, (info) => {
|
||||
log.info(`listening http://localhost:${info.port}`);
|
||||
serve({ fetch: app.fetch, port: finalPort, hostname: host, ...(tlsServe ?? {}) }, (info) => {
|
||||
log.info(`listening ${scheme}://${host}:${info.port}`);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// Pure validator for the POST /api/system/settings body. Rejects clearly-bad
|
||||
// input with a message (→ 400) rather than silently normalizing it, then hands
|
||||
// a clean patch to updateRuntimeConfig. Wire field `tlsEnabled` maps to the
|
||||
// nested `webuiTls.enabled`.
|
||||
|
||||
import type { RuntimeConfig } from '@snowluma/common/runtime';
|
||||
|
||||
export type SettingsPatch = Partial<Pick<RuntimeConfig, 'webuiPort' | 'webuiHost' | 'webuiTls' | 'trustProxy'>>;
|
||||
|
||||
export type CoerceResult =
|
||||
| { ok: true; patch: SettingsPatch }
|
||||
| { ok: false; error: string };
|
||||
|
||||
function isObject(v: unknown): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
}
|
||||
|
||||
export function coerceSettingsPatch(body: unknown): CoerceResult {
|
||||
if (!isObject(body)) return { ok: false, error: 'body must be an object' };
|
||||
const patch: SettingsPatch = {};
|
||||
|
||||
if ('webuiPort' in body) {
|
||||
const p = body.webuiPort;
|
||||
if (typeof p !== 'number' || !Number.isInteger(p) || p <= 0 || p > 65535) {
|
||||
return { ok: false, error: 'webuiPort must be an integer in 1..65535' };
|
||||
}
|
||||
patch.webuiPort = p;
|
||||
}
|
||||
|
||||
if ('webuiHost' in body) {
|
||||
if (typeof body.webuiHost !== 'string' || !body.webuiHost.trim()) {
|
||||
return { ok: false, error: 'webuiHost must be a non-empty string' };
|
||||
}
|
||||
patch.webuiHost = body.webuiHost.trim();
|
||||
}
|
||||
|
||||
if ('tlsEnabled' in body) {
|
||||
if (typeof body.tlsEnabled !== 'boolean') {
|
||||
return { ok: false, error: 'tlsEnabled must be a boolean' };
|
||||
}
|
||||
patch.webuiTls = { enabled: body.tlsEnabled };
|
||||
}
|
||||
|
||||
if ('trustProxy' in body) {
|
||||
if (typeof body.trustProxy !== 'string') {
|
||||
return { ok: false, error: 'trustProxy must be a string' };
|
||||
}
|
||||
patch.trustProxy = body.trustProxy;
|
||||
}
|
||||
|
||||
return { ok: true, patch };
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// WebUI TLS helpers. Cert/key live as config/cert.pem + config/key.pem
|
||||
// (NapCat-aligned, self-contained, travels in A2 backups). Two pure-ish
|
||||
// helpers: validate a pasted pair (save path) and resolve the on-disk pair
|
||||
// (boot path). Validation is `tls.createSecureContext` — it parses the PEM
|
||||
// and checks the key matches the cert; expiry is NOT checked here.
|
||||
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import tls from 'tls';
|
||||
|
||||
export interface TlsValidation {
|
||||
ok: boolean;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
export interface TlsResolution {
|
||||
ok: boolean;
|
||||
cert?: Buffer;
|
||||
key?: Buffer;
|
||||
reason?: string;
|
||||
}
|
||||
|
||||
function errMsg(e: unknown): string {
|
||||
return e instanceof Error ? e.message : String(e);
|
||||
}
|
||||
|
||||
/** Parse-validate a cert/key pair (used by the save endpoint before writing). */
|
||||
export function validateTlsPair(cert: string | Buffer, key: string | Buffer): TlsValidation {
|
||||
if (!cert || !cert.toString().trim()) return { ok: false, reason: 'certificate is empty' };
|
||||
if (!key || !key.toString().trim()) return { ok: false, reason: 'private key is empty' };
|
||||
try {
|
||||
tls.createSecureContext({ cert, key });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `invalid cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
}
|
||||
|
||||
/** Load + validate config/cert.pem + config/key.pem from `configDir`. */
|
||||
export function resolveTlsContext(configDir: string): TlsResolution {
|
||||
const certPath = path.join(configDir, 'cert.pem');
|
||||
const keyPath = path.join(configDir, 'key.pem');
|
||||
if (!fs.existsSync(certPath) || !fs.existsSync(keyPath)) {
|
||||
return { ok: false, reason: 'cert.pem or key.pem missing in config dir' };
|
||||
}
|
||||
let cert: Buffer;
|
||||
let key: Buffer;
|
||||
try {
|
||||
cert = fs.readFileSync(certPath);
|
||||
key = fs.readFileSync(keyPath);
|
||||
} catch (e) {
|
||||
return { ok: false, reason: `failed to read cert/key: ${errMsg(e)}` };
|
||||
}
|
||||
const valid = validateTlsPair(cert, key);
|
||||
if (!valid.ok) return { ok: false, reason: valid.reason };
|
||||
return { ok: true, cert, key };
|
||||
}
|
||||
@@ -47,6 +47,15 @@ describe('renderTemplate — mechanical {key} substitution', () => {
|
||||
// to a recursive/loop replace would break this while passing every other test.
|
||||
expect(renderTemplate('{a}', { a: '{b}', b: 'NESTED' })).toBe('{b}');
|
||||
});
|
||||
|
||||
it('escapes backslashes and quotes when template is JSON-like', () => {
|
||||
const tmpl = '{"text": "{val}"}';
|
||||
expect(renderTemplate(tmpl, { val: 'a"b\\c' })).toBe('{"text": "a\\"b\\\\c"}');
|
||||
});
|
||||
|
||||
it('does NOT escape when template is plain text', () => {
|
||||
expect(renderTemplate('{val}', { val: 'a"b\\c' })).toBe('a"b\\c');
|
||||
});
|
||||
});
|
||||
|
||||
describe('normalizeNotificationsConfig — total normalize', () => {
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { BACKUP_FILES, specFor, buildBackup, validateBackup, planRestore } from '../src/webui/backup';
|
||||
|
||||
const TS = '2026-06-18T00:00:00.000Z';
|
||||
|
||||
function reader(map: Record<string, Buffer>) {
|
||||
return (name: string): Buffer | null => map[name] ?? null;
|
||||
}
|
||||
|
||||
describe('buildBackup', () => {
|
||||
it('includes present non-credential files and skips missing ones', () => {
|
||||
const b = buildBackup(reader({
|
||||
'runtime.json': Buffer.from('{"webuiPort":5099}'),
|
||||
'ui.json': Buffer.from('{}'),
|
||||
}), [], { includeCredentials: false }, TS);
|
||||
expect(b.version).toBe(1);
|
||||
expect(b.app).toBe('snowluma');
|
||||
expect(b.createdAt).toBe(TS);
|
||||
expect(Object.keys(b.files).sort()).toEqual(['runtime.json', 'ui.json']);
|
||||
expect(b.files['runtime.json']).toEqual({ encoding: 'utf8', data: '{"webuiPort":5099}' });
|
||||
});
|
||||
|
||||
it('treats all OneBot config (global + per-uin), webui.json, key.pem as credentials', () => {
|
||||
const map = {
|
||||
'runtime.json': Buffer.from('{}'),
|
||||
'webui.json': Buffer.from('{"hash":"x"}'),
|
||||
'key.pem': Buffer.from('KEY'),
|
||||
'cert.pem': Buffer.from('CERT'),
|
||||
'onebot.json': Buffer.from('{"accessToken":"t"}'),
|
||||
'onebot_12345.json': Buffer.from('{"accessToken":"t2"}'),
|
||||
};
|
||||
const perUin = ['onebot_12345.json'];
|
||||
const without = buildBackup(reader(map), perUin, { includeCredentials: false }, TS);
|
||||
// only public files survive a no-credentials export
|
||||
expect(Object.keys(without.files).sort()).toEqual(['cert.pem', 'runtime.json']);
|
||||
const withCreds = buildBackup(reader(map), perUin, { includeCredentials: true }, TS);
|
||||
expect(Object.keys(withCreds.files).sort()).toEqual(
|
||||
['cert.pem', 'key.pem', 'onebot.json', 'onebot_12345.json', 'runtime.json', 'webui.json'],
|
||||
);
|
||||
});
|
||||
|
||||
it('base64-encodes binary files (background image)', () => {
|
||||
const png = Buffer.from([0x89, 0x50, 0x4e, 0x47]);
|
||||
const b = buildBackup(reader({ 'ui-assets/background': png }), [], { includeCredentials: false }, TS);
|
||||
expect(b.files['ui-assets/background']).toEqual({ encoding: 'base64', data: png.toString('base64') });
|
||||
});
|
||||
});
|
||||
|
||||
describe('specFor', () => {
|
||||
it('resolves static names and per-uin onebot pattern; rejects others', () => {
|
||||
expect(specFor('runtime.json')?.credential).toBe(false);
|
||||
expect(specFor('onebot.json')?.credential).toBe(true);
|
||||
expect(specFor('onebot_98765.json')).toEqual({ name: 'onebot_98765.json', binary: false, credential: true });
|
||||
expect(specFor('onebot_.json')).toBeNull();
|
||||
expect(specFor('../evil')).toBeNull();
|
||||
expect(specFor('onebot_12.json.bak')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateBackup', () => {
|
||||
const good = { version: 1, app: 'snowluma', files: { 'runtime.json': { encoding: 'utf8', data: '{}' } } };
|
||||
|
||||
it('accepts a well-formed bundle (incl. per-uin onebot)', () => {
|
||||
expect(validateBackup(good).ok).toBe(true);
|
||||
expect(validateBackup({ ...good, files: { 'onebot_42.json': { encoding: 'utf8', data: '{}' } } }).ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a non-object / wrong app / wrong version', () => {
|
||||
expect(validateBackup(null).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, app: 'other' }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, version: 999 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an unknown / path-traversal filename', () => {
|
||||
expect(validateBackup({ ...good, files: { '../evil': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, files: { 'unknown.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, files: { 'onebot_../x.json': { encoding: 'utf8', data: 'x' } } }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a malformed entry', () => {
|
||||
expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'rot13', data: 'x' } } }).ok).toBe(false);
|
||||
expect(validateBackup({ ...good, files: { 'runtime.json': { encoding: 'utf8' } } }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('planRestore', () => {
|
||||
it('decodes restored files to bytes (utf8 + base64)', () => {
|
||||
const png = Buffer.from([1, 2, 3, 4]);
|
||||
const backup = {
|
||||
version: 1, app: 'snowluma',
|
||||
files: {
|
||||
'runtime.json': { encoding: 'utf8' as const, data: '{"a":1}' },
|
||||
'ui-assets/background': { encoding: 'base64' as const, data: png.toString('base64') },
|
||||
},
|
||||
};
|
||||
const { restore, skipped } = planRestore(backup, { restoreCredentials: false });
|
||||
expect(skipped).toEqual([]);
|
||||
const byName = Object.fromEntries(restore.map((r) => [r.name, r.data]));
|
||||
expect(byName['runtime.json'].toString()).toBe('{"a":1}');
|
||||
expect(byName['ui-assets/background'].equals(png)).toBe(true);
|
||||
});
|
||||
|
||||
it('skips all credential files unless restoreCredentials', () => {
|
||||
const backup = {
|
||||
version: 1, app: 'snowluma',
|
||||
files: {
|
||||
'runtime.json': { encoding: 'utf8' as const, data: '{}' },
|
||||
'webui.json': { encoding: 'utf8' as const, data: '{"hash":"x"}' },
|
||||
'key.pem': { encoding: 'utf8' as const, data: 'KEY' },
|
||||
'onebot.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' },
|
||||
'onebot_7.json': { encoding: 'utf8' as const, data: '{"accessToken":"t"}' },
|
||||
},
|
||||
};
|
||||
const skip = planRestore(backup, { restoreCredentials: false });
|
||||
expect(skip.restore.map((r) => r.name)).toEqual(['runtime.json']);
|
||||
expect(skip.skipped.sort()).toEqual(['key.pem', 'onebot.json', 'onebot_7.json', 'webui.json']);
|
||||
const keep = planRestore(backup, { restoreCredentials: true });
|
||||
expect(keep.restore.map((r) => r.name).sort()).toEqual(
|
||||
['key.pem', 'onebot.json', 'onebot_7.json', 'runtime.json', 'webui.json'],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('BACKUP_FILES marks webui.json / key.pem / onebot.json as credentials, cert.pem public', () => {
|
||||
const creds = BACKUP_FILES.filter((f) => f.credential).map((f) => f.name).sort();
|
||||
expect(creds).toEqual(['key.pem', 'onebot.json', 'webui.json']);
|
||||
expect(specFor('cert.pem')?.credential).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { createFramePusher } from '../src/webui/debug-stream';
|
||||
|
||||
function harness(sizes: number[]) {
|
||||
// desiredSize() returns the next scripted value each call.
|
||||
let i = 0;
|
||||
const frames: string[] = [];
|
||||
const push = createFramePusher({
|
||||
desiredSize: () => (i < sizes.length ? sizes[i++] : sizes[sizes.length - 1] ?? 1),
|
||||
enqueue: (chunk) => { frames.push(Buffer.from(chunk).toString()); },
|
||||
encode: (s) => Buffer.from(s),
|
||||
});
|
||||
return { push, frames };
|
||||
}
|
||||
|
||||
describe('createFramePusher', () => {
|
||||
it('enqueues an SSE data frame when there is headroom', () => {
|
||||
const { push, frames } = harness([1]);
|
||||
push({ kind: 'event', x: 1 });
|
||||
expect(frames).toEqual([`data: ${JSON.stringify({ kind: 'event', x: 1 })}\n\n`]);
|
||||
});
|
||||
|
||||
it('drops under backpressure (desiredSize <= 0) without enqueuing', () => {
|
||||
const { push, frames } = harness([0, -3]);
|
||||
push({ a: 1 });
|
||||
push({ a: 2 });
|
||||
expect(frames).toEqual([]);
|
||||
});
|
||||
|
||||
it('emits a coalesced dropped marker before the next delivered frame', () => {
|
||||
const { push, frames } = harness([0, 0, 5]); // drop, drop, then headroom
|
||||
push({ a: 1 });
|
||||
push({ a: 2 });
|
||||
push({ a: 3 });
|
||||
expect(frames).toEqual([
|
||||
`data: ${JSON.stringify({ kind: 'dropped', count: 2 })}\n\n`,
|
||||
`data: ${JSON.stringify({ a: 3 })}\n\n`,
|
||||
]);
|
||||
});
|
||||
|
||||
it('treats null desiredSize as always-deliver (no backpressure signal)', () => {
|
||||
let i = 0;
|
||||
const frames: string[] = [];
|
||||
const push = createFramePusher({
|
||||
desiredSize: () => (i++ === 0 ? null : 1),
|
||||
enqueue: (chunk) => { frames.push(Buffer.from(chunk).toString()); },
|
||||
encode: (s) => Buffer.from(s),
|
||||
});
|
||||
push({ a: 1 });
|
||||
expect(frames).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,39 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { coerceSettingsPatch } from '../src/webui/system-settings';
|
||||
|
||||
describe('coerceSettingsPatch', () => {
|
||||
it('accepts a full valid body and maps tlsEnabled → webuiTls.enabled', () => {
|
||||
const r = coerceSettingsPatch({ webuiPort: 8080, webuiHost: '127.0.0.1', tlsEnabled: true, trustProxy: '1' });
|
||||
expect(r).toEqual({ ok: true, patch: { webuiPort: 8080, webuiHost: '127.0.0.1', webuiTls: { enabled: true }, trustProxy: '1' } });
|
||||
});
|
||||
|
||||
it('only includes provided keys (partial patch)', () => {
|
||||
const r = coerceSettingsPatch({ webuiHost: '0.0.0.0' });
|
||||
expect(r).toEqual({ ok: true, patch: { webuiHost: '0.0.0.0' } });
|
||||
});
|
||||
|
||||
it('rejects a non-object body', () => {
|
||||
expect(coerceSettingsPatch(null).ok).toBe(false);
|
||||
expect(coerceSettingsPatch('x').ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an out-of-range or non-integer port', () => {
|
||||
expect(coerceSettingsPatch({ webuiPort: 0 }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ webuiPort: 70000 }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ webuiPort: 12.5 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an empty/blank host', () => {
|
||||
expect(coerceSettingsPatch({ webuiHost: ' ' }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ webuiHost: 123 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a non-boolean tlsEnabled and non-string trustProxy', () => {
|
||||
expect(coerceSettingsPatch({ tlsEnabled: 'yes' }).ok).toBe(false);
|
||||
expect(coerceSettingsPatch({ trustProxy: 1 }).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts an empty-string trustProxy (trust nobody)', () => {
|
||||
expect(coerceSettingsPatch({ trustProxy: '' })).toEqual({ ok: true, patch: { trustProxy: '' } });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import { validateTlsPair, resolveTlsContext } from '../src/webui/tls';
|
||||
|
||||
// A throwaway self-signed pair (openssl, CN=snowluma-test). createSecureContext
|
||||
// only parses — expiry is irrelevant — so this stays valid for the test forever.
|
||||
const CERT = `-----BEGIN CERTIFICATE-----
|
||||
MIIDETCCAfmgAwIBAgIUNiu66PmcO6Do6cUaB92UKD8j3qYwDQYJKoZIhvcNAQEL
|
||||
BQAwGDEWMBQGA1UEAwwNc25vd2x1bWEtdGVzdDAeFw0yNjA2MTgwNjIwMTZaFw0z
|
||||
NjA2MTUwNjIwMTZaMBgxFjAUBgNVBAMMDXNub3dsdW1hLXRlc3QwggEiMA0GCSqG
|
||||
SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCm0sVJhqlG75gOFJVsUJOfR+oqvb9eSq4t
|
||||
k5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll2ANSjusmWN4hzpaOBBdX
|
||||
bP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23LsMsij8T4nLk4eHiOkeRfi
|
||||
uLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/KmcNtq7JrX7F7qYnYsJKLZZ
|
||||
aZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5dcZuI+KwixVKZgapG5n5R
|
||||
ghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WVhvrD6pphAgMBAAGjUzBR
|
||||
MB0GA1UdDgQWBBRW/HP12nj9fYMYNxa3jyqmnUigvTAfBgNVHSMEGDAWgBRW/HP1
|
||||
2nj9fYMYNxa3jyqmnUigvTAPBgNVHRMBAf8EBTADAQH/MA0GCSqGSIb3DQEBCwUA
|
||||
A4IBAQCijzVQ/jHNoqu6stvkkigUv2lTKrd1EHcTZLfzwQkmNv/hfY2EMobO/Qxs
|
||||
FhmITreKFALJ/dUwTt0UTO00LV9whEgr2of4x8wwjZ9wRstY6uyRYBP85QC8+8mZ
|
||||
zWlcf611HugrmpOWjWfEVmmxdI1m26YWTn52nZFPnJqDWg2+RlLJWl55lVotbXEZ
|
||||
Fvas4Vcf2KOk0QwBQKvpt0BISeTIQhbT4GnducxSxyoXGeBQOjQNYb/vTpMn4F9U
|
||||
IAxSsfs9WVoHKXOabK8GV89BCxWoRk4UaSahTq/2Vnbgt86tWibt3lA4y49+XhA2
|
||||
6z7n9HgJAUKqhsDrYvZmM7/VZ2d5
|
||||
-----END CERTIFICATE-----
|
||||
`;
|
||||
const KEY = `-----BEGIN PRIVATE KEY-----
|
||||
MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCm0sVJhqlG75gO
|
||||
FJVsUJOfR+oqvb9eSq4tk5QItuwXr85E2mrzuKFnSzVVbi3VqqyN8t4otL11mGll
|
||||
2ANSjusmWN4hzpaOBBdXbP4UNX/YA7oHId+QKbVicxJgxDE18aPTwaWullyw23Ls
|
||||
Msij8T4nLk4eHiOkeRfiuLinG1COe3gUGkCK4uyyMT4Vz+y+5Oj9dvoXYL/A/Kmc
|
||||
Ntq7JrX7F7qYnYsJKLZZaZeFyIGSE8ihb0k53iyJ3agWY+rMUD+p5J7pgIZzBd5d
|
||||
cZuI+KwixVKZgapG5n5RghrnN2ZAQFz13yTRXYmDYy42m4Ue73hMmmt1xVXyf+WV
|
||||
hvrD6pphAgMBAAECggEAJ13+u4qhIMHCnrQBzPU42PImEt8DLXOvJcc5PFM6ZJ6S
|
||||
rRHkAk60HAWV+OqOu2jS3o6NGYsJWJpWaPewVQev+zUmelDfm3TgsztfvBIh8K50
|
||||
dGFsef81tB1WnWo++K1kzUBZ4ljOV9f5hz62tWVlFubo/Vd8bsA6wEB6Jskd2fls
|
||||
ZOO0hJCb/M6IIwe3cWw4sb/YFTTLMUnVHM0aJfnQ/QH+uraRwecJMv118d0YBYVG
|
||||
DsNmYqrv9TYNBh4P9mKv6/0x8zaKsJZVLAMwHztILHItOXBfxCbSDivGWVUGiDq2
|
||||
NxEuBOgxzOelxEYzUzf7B6sjHoEeIL5wIKQbwUbmfwKBgQDZRLhucrMZPw7ous1t
|
||||
igkO32p1ku7FRxm0/JAskc66oX61KLIYbZFM9N7nTXAEs8ZGhzUkdSgxNcdHWIdK
|
||||
RI+6pd2FhhcKU1feEohlOHvZTXXEMhm61phWnN391GZXfwMKSpscqsu9kIix2jtw
|
||||
4YrzKLx82EDDHcLfBh9AtArKywKBgQDEj+7UJp5wuqz9hj+gogXeq4Buv9be1u4u
|
||||
HCJZMZzLCwVjvoqYw0n1afXP3057v8hQPGsBaxzQpOg7i1lYGGfuZ9T6T8fFrtqw
|
||||
m/LJLHhMQxeyCEQi1/EoNewvVGSwBJkLOuOs8T2WmMXmOgdHbEYdzkKtT71jst6y
|
||||
TeJ15hVuAwKBgBMK4t9LTkc4L6ZWOQsQvhp/mmUTq7m+sZIbUMeXP/c7kE9wcauS
|
||||
btm/3ImJT/gZiZdE4nN/kTY+8GhgafsoZzCEuRWq2vocs+bS2QGGIdS55Uh826R0
|
||||
ioWM2igVJaMljq6oO1AX6COFN3XfGraaDgOh3mNS0NpJEXtangKdxRRhAoGAP9SF
|
||||
t/r6hJz6RDHuQ5mZ0l9bC5vciOy+19ZnCRPlWMIxc9ySYV05jSplmqVndSQoRnX4
|
||||
QbOo3dBPYda0orj6Nx8cuFRkCTvo5GUgCFgakJlQ/o1UowQA2g/4rL35HHfBwzXS
|
||||
bXzBhUADM+owJu9wLYmneWRlmhSh4MEOAz8+QkUCgYAw0fA1Im2/ftrA2Z2IENTi
|
||||
U4cLXqeUeGJfXjIBklUmXhc4qrd/9V9eEHjackI/JI7Qhp/QfPWMXLudlSrppnNJ
|
||||
+s3dVevEKosiZbf4qtTtlmR/IifuTKjK5O94KlBT+evxNsL4Hv0b0oTsVNnEfOOl
|
||||
OUsvSYNSnfvl87tyLIxYLA==
|
||||
-----END PRIVATE KEY-----
|
||||
`;
|
||||
|
||||
describe('validateTlsPair', () => {
|
||||
it('accepts a matching cert/key pair', () => {
|
||||
expect(validateTlsPair(CERT, KEY)).toEqual({ ok: true });
|
||||
});
|
||||
|
||||
it('rejects garbage PEM with a reason', () => {
|
||||
const r = validateTlsPair('not a cert', 'not a key');
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.reason).toBeTruthy();
|
||||
});
|
||||
|
||||
it('rejects an empty cert', () => {
|
||||
expect(validateTlsPair('', KEY).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveTlsContext', () => {
|
||||
let dir: string;
|
||||
beforeEach(() => { dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sl-tls-')); });
|
||||
afterEach(() => { fs.rmSync(dir, { recursive: true, force: true }); });
|
||||
|
||||
it('loads cert.pem + key.pem when both present and valid', () => {
|
||||
fs.writeFileSync(path.join(dir, 'cert.pem'), CERT);
|
||||
fs.writeFileSync(path.join(dir, 'key.pem'), KEY);
|
||||
const r = resolveTlsContext(dir);
|
||||
expect(r.ok).toBe(true);
|
||||
expect(r.cert?.toString()).toContain('BEGIN CERTIFICATE');
|
||||
expect(r.key?.toString()).toContain('PRIVATE KEY');
|
||||
});
|
||||
|
||||
it('fails (with reason) when files are missing', () => {
|
||||
const r = resolveTlsContext(dir);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.reason).toMatch(/missing/i);
|
||||
});
|
||||
|
||||
it('fails when the on-disk PEM is invalid', () => {
|
||||
fs.writeFileSync(path.join(dir, 'cert.pem'), 'garbage');
|
||||
fs.writeFileSync(path.join(dir, 'key.pem'), 'garbage');
|
||||
const r = resolveTlsContext(dir);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.reason).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/mcp",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -563,9 +563,12 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// _mark_all_as_read — no-op。NapCat 靠单次内核 IPC markAllMsgAsRead() 实现,
|
||||
// SnowLuma 无等价单包 SSO cmd;遍历所有会话逐个发已读报告是风控高危群发,
|
||||
// 故暂不真正执行(留待 RE 出"一键全读"cmd)。返回 ok 以兼容启动时盲调的客户端。
|
||||
defineAction({
|
||||
name: '_mark_all_as_read',
|
||||
summary: '标记全部已读',
|
||||
summary: '标记全部已读(no-op,待 RE 全读 cmd)',
|
||||
params: {},
|
||||
run: async () => {
|
||||
return okResponse();
|
||||
@@ -705,15 +708,23 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// get_group_shut_list 依赖尚未封装的 oidb。
|
||||
// 这里遵循 NapCat 约定返回空列表,避免调用方出错。
|
||||
defineAction({
|
||||
// get_group_shut_list — SnowLuma 无独立"禁言列表"cmd,按成员列表的
|
||||
// shutUpTime 字段(绝对到期时间戳,秒)派生:保留仍在禁言中的成员。
|
||||
// 走带 TTL 缓存的 fetchGroupMemberList(风控友好,0xfe7 高频会触发腾讯封号),
|
||||
// 与 NapCat 文档返回形状 {user_id,nickname,shut_up_time} 对齐。
|
||||
// 取舍:NapCat 此接口实时,本实现复用成员缓存,故结果最长有 ~60s 延迟——
|
||||
// 刚下/解的禁言可能在该窗口内未反映,属可接受的低频运维查询取舍。
|
||||
groupAction({
|
||||
name: 'get_group_shut_list',
|
||||
summary: '获取群禁言列表(占位)',
|
||||
summary: '获取群禁言列表',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: async () => {
|
||||
return okResponse([]);
|
||||
run: async (p, ctx) => {
|
||||
const members = await ctx.bridge.apis.contacts.fetchGroupMemberList(p.group_id);
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const list = members
|
||||
.filter((m) => (m.shutUpTime ?? 0) > nowSec)
|
||||
.map((m) => ({ user_id: m.uin, nickname: m.nickname, shut_up_time: m.shutUpTime }));
|
||||
return okResponse(list);
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -849,10 +860,13 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// NapCat 似乎也用不了,暂时不处理。
|
||||
// get_online_clients — 在线设备列表。NapCat 也拿不到(注册监听后 sleep 500ms
|
||||
// 直接返回空),且其返回是裸数组 [],偏离 OneBot v11 / go-cqhttp 规范。
|
||||
// SnowLuma 暂无对应单包 SSO cmd,返回 OneBot v11 标准空壳 { clients: [] }
|
||||
// ——刻意采用规范形状而非 NapCat 的裸 [],故对照 NapCat 客户端此处不严格 parity。
|
||||
defineAction({
|
||||
name: 'get_online_clients',
|
||||
summary: '获取在线客户端(占位)',
|
||||
summary: '获取在线客户端(占位,OneBot v11 形状)',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: async () => {
|
||||
@@ -860,13 +874,21 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// _get_model_show — NapCat 纯内核无 packet wire,其实现是硬编码 mock
|
||||
// (无视入参,model_show 恒返回字面量 'napcat')。SnowLuma 同样无对应单包
|
||||
// SSO cmd,故只复用 NapCat 的*外层形状*:data 为数组 [{ variants: {...} }]、
|
||||
// need_pay 恒 false;但刻意不照搬其固定字面量——回显请求的 model(缺省
|
||||
// 'snowluma'),对调用方更有信息量。属有意的行为分歧,仅形状对齐。
|
||||
defineAction({
|
||||
name: '_get_model_show',
|
||||
summary: '获取机型展示(占位)',
|
||||
summary: '获取机型展示(兼容 mock)',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: async () => {
|
||||
return okResponse({ variants: [] });
|
||||
params: {
|
||||
model: f.string().default(''),
|
||||
},
|
||||
run: async (p) => {
|
||||
const modelShow = p.model || 'snowluma';
|
||||
return okResponse([{ variants: { model_show: modelShow, need_pay: false } }]);
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1018,27 +1040,36 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
defineAction({
|
||||
name: 'rename_group_file',
|
||||
summary: '重命名群文件(未实现)',
|
||||
params: {},
|
||||
run: async () => {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
},
|
||||
}),
|
||||
|
||||
// get_file — 统一文件信息入口。SnowLuma 按 file_id 解析媒体缓存:
|
||||
// 先图片、后语音(两者已带 url 重签与 file_size/file_name)。
|
||||
// 局限:群文件/普通文件的 file_id 无法在此解析——OneBot `get_file` 单参
|
||||
// 签名不含 group_id,而 SnowLuma 群文件下载需要 group 上下文(用
|
||||
// get_group_file_url / get_private_file_url)。故此处仅覆盖图片/语音,
|
||||
// 不为群文件伪造结果。
|
||||
// 注意:缓存双 miss 时无法在此区分"传入的是群文件 file_id"与"图片/语音
|
||||
// 确实未缓存(如进程重启丢失)"——run() 不解析 id 形态。故错误信息保持
|
||||
// 中性:先陈述"未命中缓存"的事实,再把群文件改用别的接口作为指引,
|
||||
// 而非武断断言"不支持"。(summary 仅进离线文档,调用方运行时只看到 wording。)
|
||||
defineAction({
|
||||
name: 'get_file',
|
||||
summary: '获取文件(未实现)',
|
||||
summary: '获取文件信息(仅图片/语音缓存;群文件请用 get_group_file_url)',
|
||||
readOnly: true,
|
||||
params: {
|
||||
file_id: f.string().default(''),
|
||||
file: f.string().default(''),
|
||||
},
|
||||
run: async (p) => {
|
||||
const fileId = p.file_id || p.file;
|
||||
run: async (p, ctx) => {
|
||||
const fileId = p.file || p.file_id;
|
||||
if (!fileId) return failedResponse(RETCODE.BAD_REQUEST, 'file_id is required');
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented');
|
||||
const image = await ctx.getImageInfo(fileId);
|
||||
if (image) return okResponse(image);
|
||||
const record = await ctx.getRecordInfo(fileId);
|
||||
if (record) return okResponse(record);
|
||||
return failedResponse(
|
||||
RETCODE.ACTION_FAILED,
|
||||
'file_id not found in the image/voice cache. get_file only resolves cached '
|
||||
+ 'image/voice ids; for group/normal files use get_group_file_url or get_private_file_url',
|
||||
);
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -1195,12 +1226,70 @@ export const actions = [
|
||||
: failedResponse(RETCODE.ACTION_FAILED, 'not implemented'),
|
||||
}),
|
||||
|
||||
// get_rkey_server — 把下载 rkey 列表(type 10=私聊 / 20=群聊,同 0x9067 来源)
|
||||
// 收敛成 NapCat 的 server 形状。expired_time = now + 在场 rkey ttl 的最小值。
|
||||
defineAction({
|
||||
name: ['ocr_image', '.ocr_image'],
|
||||
summary: 'OCR 图片(未实现)',
|
||||
name: 'get_rkey_server',
|
||||
summary: '获取 rkey 服务器信息',
|
||||
readOnly: true,
|
||||
params: {},
|
||||
run: () => failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'),
|
||||
run: async (_p, ctx) => {
|
||||
if (!ctx.getDownloadRKeys) return failedResponse(RETCODE.ACTION_FAILED, 'not implemented');
|
||||
const rkeys = await ctx.getDownloadRKeys();
|
||||
const pick = (type: number) =>
|
||||
rkeys.find((r) => (r as { type?: number }).type === type) as
|
||||
{ rkey?: string; ttl?: number } | undefined;
|
||||
const priv = pick(10);
|
||||
const group = pick(20);
|
||||
// No rkey at all → fail rather than hand back an "expired_time = now,
|
||||
// no keys" shell that a caching caller would misread as a valid-but-empty
|
||||
// (already-expired) result.
|
||||
if (!priv?.rkey && !group?.rkey) {
|
||||
return failedResponse(RETCODE.ACTION_FAILED, 'no download rkey available');
|
||||
}
|
||||
const ttls = [priv?.ttl, group?.ttl].filter((t): t is number => typeof t === 'number' && t > 0);
|
||||
const minTtl = ttls.length ? Math.min(...ttls) : 0;
|
||||
const data: JsonObject = {
|
||||
expired_time: Math.floor(Date.now() / 1000) + minTtl,
|
||||
name: 'SnowLuma',
|
||||
};
|
||||
if (priv?.rkey) data.private_rkey = priv.rkey;
|
||||
if (group?.rkey) data.group_rkey = group.rkey;
|
||||
return okResponse(data);
|
||||
},
|
||||
}),
|
||||
|
||||
// ocr_image — 服务端 OCR via OIDB 0xE07_0(port 自 Lagrange/NapCat proto)。
|
||||
// 该 cmd 接收图片 URL(服务端拉取),故 image 支持:http(s) URL 直用,或
|
||||
// 已缓存图片的 file_id(经 getImageInfo 解析出 URL)。base64/本地文件需先
|
||||
// 上传换 URL,本实现不覆盖(NapCat 走的是 Windows-only 内核 OCR,不可移植)。
|
||||
defineAction({
|
||||
name: ['ocr_image', '.ocr_image'],
|
||||
summary: 'OCR 图片(服务端,需图片 URL 或已缓存的图片 file_id)',
|
||||
readOnly: true,
|
||||
params: { image: f.string({ allowEmpty: false }) },
|
||||
run: async (p, ctx) => {
|
||||
// A passed-in http(s) URL is used verbatim (NOT re-signed) — if it is a
|
||||
// stale CDN URL with an expired rkey the server fetch fails and surfaces
|
||||
// the server's retCode. The file_id path below re-signs via getImageInfo.
|
||||
let url = /^https?:\/\//i.test(p.image) ? p.image : '';
|
||||
if (!url) {
|
||||
const info = await ctx.getImageInfo(p.image);
|
||||
const resolved = info && typeof info.url === 'string' ? info.url : '';
|
||||
if (resolved) url = resolved;
|
||||
}
|
||||
if (!url) {
|
||||
return failedResponse(
|
||||
RETCODE.ACTION_FAILED,
|
||||
'ocr_image needs an http(s) image url or a cached image file_id; '
|
||||
+ 'base64/local-file input is not supported',
|
||||
);
|
||||
}
|
||||
const result = await ctx.bridge.apis.misc.ocrImage(url);
|
||||
// OcrResult is plain JSON data; the interface just lacks an index
|
||||
// signature, so coerce for the JsonValue-typed response.
|
||||
return okResponse(result as unknown as JsonObject);
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
|
||||
@@ -100,6 +100,24 @@ export const actions = [
|
||||
},
|
||||
}),
|
||||
|
||||
// rename_group_file — 0x6D6_4。NapCat 入参:file_id + current_parent_directory
|
||||
// (文件当前所在目录)+ new_name。SnowLuma 的 file_id 即原始 fileId,无需 UUID 解码。
|
||||
groupAction({
|
||||
name: 'rename_group_file',
|
||||
summary: '重命名群文件',
|
||||
params: {
|
||||
file_id: f.string({ allowEmpty: false }),
|
||||
current_parent_directory: f.string().default('/'),
|
||||
new_name: f.string({ allowEmpty: false }),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
await ctx.bridge.apis.groupFile.rename(p.group_id, p.file_id, p.current_parent_directory || '/', p.new_name);
|
||||
// {ok:true} 刻意对齐 NapCat RenameGroupFile 的返回体,偏离 SnowLuma 同类
|
||||
// 文件写操作(move/delete 返回空 data)——为 NapCat 客户端 drop-in 兼容。
|
||||
return okResponse({ ok: true });
|
||||
},
|
||||
}),
|
||||
|
||||
groupAction({
|
||||
name: 'create_group_file_folder',
|
||||
summary: '创建群文件夹',
|
||||
|
||||
@@ -81,9 +81,27 @@ export interface ApiActionContext {
|
||||
|
||||
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
/** A handled-action record handed to debug observers. */
|
||||
export interface ActionRecord {
|
||||
action: string;
|
||||
params: JsonObject;
|
||||
response: import('./types').ApiResponse;
|
||||
ms: number;
|
||||
}
|
||||
export type ActionObserver = (rec: ActionRecord) => void;
|
||||
|
||||
export class ApiHandler {
|
||||
private readonly handlers = new Map<string, ActionHandler>();
|
||||
private readonly log: Logger;
|
||||
/** Debug-stream taps — notified after every handled action. Attached
|
||||
* on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly observers = new Set<ActionObserver>();
|
||||
|
||||
/** Observe handled actions (debug). Returns an unsubscribe. */
|
||||
setObserver(cb: ActionObserver): () => void {
|
||||
this.observers.add(cb);
|
||||
return () => { this.observers.delete(cb); };
|
||||
}
|
||||
|
||||
constructor(context: ApiActionContext, uin?: number) {
|
||||
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
|
||||
@@ -132,10 +150,10 @@ export class ApiHandler {
|
||||
this.log.trace(() => [`${action} ⇐ %s`, renderParamsVerbose(params)]);
|
||||
|
||||
const startedAt = Date.now();
|
||||
let response: import('./types').ApiResponse;
|
||||
try {
|
||||
const response = await handler(params);
|
||||
response = await handler(params);
|
||||
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
|
||||
return response;
|
||||
} catch (error) {
|
||||
// Action failures are almost always param-shape problems coming
|
||||
// from the OneBot client; warn (not error) is the right level so
|
||||
@@ -145,7 +163,23 @@ export class ApiHandler {
|
||||
error instanceof Error ? error.message : String(error),
|
||||
error instanceof Error ? (error.stack ?? '') : '');
|
||||
const message = error instanceof Error ? error.message : 'internal error';
|
||||
return failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
response = failedResponse(RETCODE.INTERNAL_ERROR, message);
|
||||
}
|
||||
this.notifyObservers(action, params, response, Date.now() - startedAt);
|
||||
return response;
|
||||
}
|
||||
|
||||
private notifyObservers(
|
||||
action: string,
|
||||
params: JsonObject,
|
||||
response: import('./types').ApiResponse,
|
||||
ms: number,
|
||||
): void {
|
||||
if (!this.observers.size) return;
|
||||
for (const cb of this.observers) {
|
||||
try { cb({ action, params, response, ms }); } catch (err) {
|
||||
this.log.warn('action observer error: %s', err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import { createLogger, type Logger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/protocol/format';
|
||||
import path from 'path';
|
||||
import { ApiHandler } from './api-handler';
|
||||
import { ApiHandler, type ActionObserver } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
type NetworkAdapterContext,
|
||||
} from './network';
|
||||
import { ReactionStore } from './reaction-store';
|
||||
import type { JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types';
|
||||
|
||||
const moduleLog = createLogger('Event');
|
||||
|
||||
@@ -59,6 +59,20 @@ export class OneBotInstance {
|
||||
return this.networkManager.describeStatuses();
|
||||
}
|
||||
|
||||
// ── Debug taps (WebUI debug stream / tester) ──
|
||||
/** Tap every emitted OneBot event for this account. Returns an unsubscribe. */
|
||||
subscribeDebugEvents(cb: (event: JsonObject) => void): () => void {
|
||||
return this.networkManager.subscribeDebug(cb);
|
||||
}
|
||||
/** Observe every handled action for this account. Returns an unsubscribe. */
|
||||
observeActions(cb: ActionObserver): () => void {
|
||||
return this.apiHandler.setObserver(cb);
|
||||
}
|
||||
/** Invoke an OneBot action against this account (debug tester). */
|
||||
invokeAction(action: string, params: JsonObject): Promise<ApiResponse> {
|
||||
return this.apiHandler.handle(action, params);
|
||||
}
|
||||
|
||||
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
|
||||
this.uin = uin;
|
||||
this.bridge = bridge;
|
||||
|
||||
@@ -9,6 +9,14 @@ type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
|
||||
|
||||
export class OneBotNetworkManager {
|
||||
private readonly adapters = new Map<string, AnyAdapter>();
|
||||
/** Debug-stream taps — notified for every emitted event regardless of adapter
|
||||
* state. Attached on-demand (ref-counted) by the WebUI debug stream. */
|
||||
private readonly debugSubscribers = new Set<(event: JsonObject) => void>();
|
||||
|
||||
subscribeDebug(cb: (event: JsonObject) => void): () => void {
|
||||
this.debugSubscribers.add(cb);
|
||||
return () => { this.debugSubscribers.delete(cb); };
|
||||
}
|
||||
|
||||
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
|
||||
const existing = this.adapters.get(adapter.name);
|
||||
@@ -75,6 +83,14 @@ export class OneBotNetworkManager {
|
||||
}
|
||||
|
||||
async emitEvent(event: JsonObject): Promise<void> {
|
||||
// Notify debug taps first — before the adapter check — so the debug stream
|
||||
// sees every event even when no adapter is connected. Never let a tap throw
|
||||
// into the dispatch path.
|
||||
if (this.debugSubscribers.size) {
|
||||
for (const cb of this.debugSubscribers) {
|
||||
try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); }
|
||||
}
|
||||
}
|
||||
if (!this.hasActiveAdapters()) return;
|
||||
const payload = buildDispatchPayload(event);
|
||||
const tasks: Promise<unknown>[] = [];
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { OneBotNetworkManager } from '../src/network/network-manager';
|
||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||
|
||||
// ApiHandler's register* only define handlers (closures) at construction — they
|
||||
// don't touch ctx — so a throwing proxy is a safe minimal context.
|
||||
function fakeCtx(): ApiActionContext {
|
||||
return new Proxy({} as ApiActionContext, {
|
||||
get(_t, prop) { throw new Error(`ctx.${String(prop)} not stubbed`); },
|
||||
});
|
||||
}
|
||||
|
||||
describe('OneBotNetworkManager.subscribeDebug', () => {
|
||||
it('notifies debug subscribers on emitEvent even with no active adapters', async () => {
|
||||
const nm = new OneBotNetworkManager();
|
||||
const seen: unknown[] = [];
|
||||
nm.subscribeDebug((e) => seen.push(e));
|
||||
await nm.emitEvent({ post_type: 'meta_event', x: 1 });
|
||||
expect(seen).toEqual([{ post_type: 'meta_event', x: 1 }]);
|
||||
});
|
||||
|
||||
it('stops notifying after unsubscribe', async () => {
|
||||
const nm = new OneBotNetworkManager();
|
||||
const cb = vi.fn();
|
||||
const off = nm.subscribeDebug(cb);
|
||||
await nm.emitEvent({ a: 1 });
|
||||
off();
|
||||
await nm.emitEvent({ a: 2 });
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
expect(cb).toHaveBeenCalledWith({ a: 1 });
|
||||
});
|
||||
|
||||
it('a throwing subscriber does not break emitEvent', async () => {
|
||||
const nm = new OneBotNetworkManager();
|
||||
nm.subscribeDebug(() => { throw new Error('boom'); });
|
||||
await expect(nm.emitEvent({ a: 1 })).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('ApiHandler.setObserver', () => {
|
||||
it('fires after a successful action with {action, params, response, ms}', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' }));
|
||||
const recs: Array<{ action: string; response: { status: string } }> = [];
|
||||
h.setObserver((r) => recs.push(r as any));
|
||||
const res = await h.handle('ping', { x: 1 });
|
||||
expect(res).toMatchObject({ status: 'ok', data: 'pong' });
|
||||
expect(recs).toHaveLength(1);
|
||||
expect(recs[0]).toMatchObject({ action: 'ping', params: { x: 1 }, response: { status: 'ok' } });
|
||||
expect(typeof (recs[0] as any).ms).toBe('number');
|
||||
});
|
||||
|
||||
it('fires on a thrown action with the failure response', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('boom', async () => { throw new Error('kaboom'); });
|
||||
const recs: any[] = [];
|
||||
h.setObserver((r) => recs.push(r));
|
||||
await h.handle('boom', {});
|
||||
expect(recs).toHaveLength(1);
|
||||
expect(recs[0].response.status).toBe('failed');
|
||||
});
|
||||
|
||||
it('unsubscribe stops observation', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 }));
|
||||
const cb = vi.fn();
|
||||
const off = h.setObserver(cb);
|
||||
await h.handle('ping', {});
|
||||
off();
|
||||
await h.handle('ping', {});
|
||||
expect(cb).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('a throwing observer does not break handle', async () => {
|
||||
const h = new ApiHandler(fakeCtx());
|
||||
h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 }));
|
||||
h.setObserver(() => { throw new Error('observer boom'); });
|
||||
await expect(h.handle('ping', {})).resolves.toMatchObject({ status: 'ok' });
|
||||
});
|
||||
});
|
||||
@@ -350,12 +350,6 @@ describe('extended-actions / get_group_ignore_add_request', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('extended-actions / get_group_shut_list', () => {
|
||||
it('returns empty list (oidb not yet wrapped)', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {});
|
||||
expect(res).toEqual({ status: 'ok', retcode: 0, data: [] });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tier 1: delete_group_folder alias ───
|
||||
|
||||
@@ -620,3 +614,231 @@ describe('extended-actions / set_group_portrait', () => {
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'highway 500' });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Wave 1: get_group_shut_list ───
|
||||
|
||||
describe('extended-actions / get_group_shut_list', () => {
|
||||
it('returns only currently-muted members in NapCat shape', async () => {
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const fetchGroupMemberList = vi.fn(async () => [
|
||||
{ uin: 111, uid: 'u1', nickname: 'muted', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: nowSec + 3600 },
|
||||
{ uin: 222, uid: 'u2', nickname: 'free', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0 },
|
||||
{ uin: 333, uid: 'u3', nickname: 'expired', card: '', role: 'member', level: 1, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: nowSec - 3600 },
|
||||
]);
|
||||
const bridge = fakeBridge({ fetchGroupMemberList: fetchGroupMemberList as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_shut_list', { group_id: 12345 });
|
||||
expect(res.status).toBe('ok');
|
||||
expect(fetchGroupMemberList).toHaveBeenCalledWith(12345);
|
||||
expect(res.data).toEqual([
|
||||
{ user_id: 111, nickname: 'muted', shut_up_time: nowSec + 3600 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects missing group_id', async () => {
|
||||
const bridge = fakeBridge({ fetchGroupMemberList: vi.fn() as any });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_shut_list', {});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Wave 1: get_file (compose image→record cache) ───
|
||||
|
||||
describe('extended-actions / get_file', () => {
|
||||
const imageInfo = { file: 'a.jpg', url: 'http://x/a.jpg', file_size: '12', file_name: 'a.jpg' };
|
||||
const recordInfo = { file: 'b.amr', url: 'http://x/b.amr', file_size: '34', file_name: 'b.amr' };
|
||||
|
||||
it('resolves an image file_id via the image cache', async () => {
|
||||
const getImageInfo = vi.fn(async () => imageInfo);
|
||||
const getRecordInfo = vi.fn(async () => null);
|
||||
const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'a.jpg' });
|
||||
expect(res).toMatchObject({ status: 'ok', data: imageInfo });
|
||||
expect(getRecordInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('falls back to the record cache when not an image', async () => {
|
||||
const getImageInfo = vi.fn(async () => null);
|
||||
const getRecordInfo = vi.fn(async () => recordInfo);
|
||||
const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file: 'b.amr' });
|
||||
expect(res).toMatchObject({ status: 'ok', data: recordInfo });
|
||||
});
|
||||
|
||||
it('fails with a neutral cache-miss message that points to the group-file path', async () => {
|
||||
// A double cache miss is runtime-indistinguishable between "a group-file
|
||||
// file_id was passed (unsupported here)" and "the image/voice really isn't
|
||||
// cached" — run() does not parse the id's shape. So the error must stay
|
||||
// neutral: state the cache miss, then offer the group-file path as
|
||||
// guidance, without asserting "unsupported".
|
||||
const getImageInfo = vi.fn(async () => null);
|
||||
const getRecordInfo = vi.fn(async () => null);
|
||||
const res = await makeHandler(fakeCtx(fakeBridge(), { getImageInfo, getRecordInfo })).handle('get_file', { file_id: 'nope' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
const wording = (res as { wording?: string }).wording ?? '';
|
||||
expect(wording).toMatch(/not found in the image\/voice cache/);
|
||||
expect(wording).toMatch(/get_group_file_url/);
|
||||
expect(wording).not.toMatch(/unsupported/);
|
||||
});
|
||||
|
||||
it('rejects when neither file nor file_id is given', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_file', {});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Wave 2: rename_group_file (0x6D6_4) ───
|
||||
|
||||
describe('extended-actions / rename_group_file', () => {
|
||||
it('renames a group file via apis.groupFile.rename', async () => {
|
||||
const rename = vi.fn(async () => undefined);
|
||||
const bridge = fakeBridge({ apis: { groupFile: { rename } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', {
|
||||
group_id: 12345, file_id: '/abc', current_parent_directory: '/', new_name: 'new.txt',
|
||||
});
|
||||
expect(res.status).toBe('ok');
|
||||
expect(rename).toHaveBeenCalledWith(12345, '/abc', '/', 'new.txt');
|
||||
});
|
||||
|
||||
it('rejects missing required params', async () => {
|
||||
const rename = vi.fn();
|
||||
const bridge = fakeBridge({ apis: { groupFile: { rename } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', { group_id: 12345, file_id: '/abc' });
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(rename).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('surfaces oidb errors (handler maps a thrown error to INTERNAL_ERROR, as its sibling file ops do)', async () => {
|
||||
const rename = vi.fn(async () => { throw new Error('rename rejected'); });
|
||||
const bridge = fakeBridge({ apis: { groupFile: { rename } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('rename_group_file', {
|
||||
group_id: 1, file_id: '/a', current_parent_directory: '/', new_name: 'x',
|
||||
});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1200, wording: 'rename rejected' });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Wave 2: get_rkey_server ───
|
||||
|
||||
describe('extended-actions / get_rkey_server', () => {
|
||||
it('reshapes download rkeys into the NapCat server shape (private=10, group=20)', async () => {
|
||||
const nowSec = Math.floor(Date.now() / 1000);
|
||||
const getDownloadRKeys = vi.fn(async () => [
|
||||
{ rkey: '&rkey=PRIV', type: 10, ttl: 3600, create_time: 100 },
|
||||
{ rkey: '&rkey=GRP', type: 20, ttl: 7200, create_time: 200 },
|
||||
]);
|
||||
const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {});
|
||||
expect(res.status).toBe('ok');
|
||||
const d = res.data as { private_rkey?: string; group_rkey?: string; expired_time: number; name: string };
|
||||
expect(d.private_rkey).toBe('&rkey=PRIV');
|
||||
expect(d.group_rkey).toBe('&rkey=GRP');
|
||||
expect(d.name).toBe('SnowLuma');
|
||||
// expiry = now + min(ttl) = now + 3600 (allow a 1s clock tick)
|
||||
expect(d.expired_time).toBeGreaterThanOrEqual(nowSec + 3600);
|
||||
expect(d.expired_time).toBeLessThanOrEqual(nowSec + 3601);
|
||||
});
|
||||
|
||||
it('leaves a missing scope undefined', async () => {
|
||||
const getDownloadRKeys = vi.fn(async () => [
|
||||
{ rkey: '&rkey=PRIV', type: 10, ttl: 3600, create_time: 100 },
|
||||
]);
|
||||
const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {});
|
||||
const d = res.data as { private_rkey?: string; group_rkey?: string };
|
||||
expect(d.private_rkey).toBe('&rkey=PRIV');
|
||||
expect(d.group_rkey).toBeUndefined();
|
||||
});
|
||||
|
||||
it('fails (not an expired empty shell) when no rkey is available', async () => {
|
||||
const getDownloadRKeys = vi.fn(async () => []);
|
||||
const res = await makeHandler(fakeCtx(fakeBridge(), { getDownloadRKeys })).handle('get_rkey_server', {});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Wave 3: ocr_image / .ocr_image (OIDB 0xE07_0) ───
|
||||
|
||||
describe('extended-actions / ocr_image', () => {
|
||||
const ocrResult = { texts: [{ text: 'hello', confidence: 99, coordinates: [{ x: 1, y: 2 }] }], language: 'en' };
|
||||
|
||||
it('OCRs an http(s) image URL directly', async () => {
|
||||
const ocrImage = vi.fn(async () => ocrResult);
|
||||
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', { image: 'https://x/a.jpg' });
|
||||
expect(res).toMatchObject({ status: 'ok', data: ocrResult });
|
||||
expect(ocrImage).toHaveBeenCalledWith('https://x/a.jpg');
|
||||
});
|
||||
|
||||
it('resolves a cached image file_id to a url via getImageInfo', async () => {
|
||||
const ocrImage = vi.fn(async () => ocrResult);
|
||||
const getImageInfo = vi.fn(async () => ({ url: 'https://cdn/resolved.jpg' }));
|
||||
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
|
||||
const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'abc.jpg' });
|
||||
expect(res.status).toBe('ok');
|
||||
expect(ocrImage).toHaveBeenCalledWith('https://cdn/resolved.jpg');
|
||||
});
|
||||
|
||||
it('.ocr_image shares the same handler', async () => {
|
||||
const ocrImage = vi.fn(async () => ocrResult);
|
||||
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('.ocr_image', { image: 'http://x/a.jpg' });
|
||||
expect(res.status).toBe('ok');
|
||||
});
|
||||
|
||||
it('fails when the id cannot be resolved to a url', async () => {
|
||||
const ocrImage = vi.fn();
|
||||
const getImageInfo = vi.fn(async () => null);
|
||||
const bridge = fakeBridge({ apis: { misc: { ocrImage } } });
|
||||
const res = await makeHandler(fakeCtx(bridge, { getImageInfo })).handle('ocr_image', { image: 'unknown' });
|
||||
expect(res.status).toBe('failed');
|
||||
expect(ocrImage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects missing image', async () => {
|
||||
const bridge = fakeBridge({ apis: { misc: { ocrImage: vi.fn() } } });
|
||||
const res = await makeHandler(fakeCtx(bridge)).handle('ocr_image', {});
|
||||
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
});
|
||||
});
|
||||
|
||||
// ─── TierB Phase 1: compat stubs (model_show / online_clients / mark_all_as_read) ───
|
||||
// These are kernel-only in NapCat (mock/no-op), so SnowLuma ships honest
|
||||
// compat shapes rather than RE-ing a wire that doesn't exist. We pin the
|
||||
// response *shape* of each. NOTE two deliberate divergences from NapCat:
|
||||
// • _get_model_show reuses NapCat's array/variants shape but ECHOES the
|
||||
// requested model instead of NapCat's hardcoded 'napcat'.
|
||||
// • get_online_clients returns the OneBot-v11/go-cqhttp { clients: [] }
|
||||
// envelope, NOT NapCat's (non-standard) bare []. A strict-NapCat client
|
||||
// would expect an array here; we intentionally follow the spec instead.
|
||||
|
||||
describe('extended-actions / TierB compat stubs', () => {
|
||||
it('_get_model_show returns the napcat-shaped variants array, echoing the model', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('_get_model_show', { model: 'MyPhone' });
|
||||
expect(res.status).toBe('ok');
|
||||
// NapCat shape: data = [{ variants: { model_show, need_pay } }]
|
||||
expect(Array.isArray(res.data)).toBe(true);
|
||||
expect(res.data).toHaveLength(1);
|
||||
expect((res.data as any)[0].variants).toMatchObject({ model_show: 'MyPhone', need_pay: false });
|
||||
});
|
||||
|
||||
it('_get_model_show defaults model_show to snowluma when model is absent or empty', async () => {
|
||||
for (const params of [{}, { model: '' }]) {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('_get_model_show', params);
|
||||
expect(res.status).toBe('ok');
|
||||
expect((res.data as any)[0].variants.model_show).toBe('snowluma');
|
||||
expect((res.data as any)[0].variants.need_pay).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('_set_model_show is an accepted no-op', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('_set_model_show', { model: 'x', model_show: 'y' });
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: null });
|
||||
});
|
||||
|
||||
it('get_online_clients returns the OneBot-standard {clients:[]} envelope', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_online_clients', {});
|
||||
expect(res.status).toBe('ok');
|
||||
expect(res.data).toMatchObject({ clients: [] });
|
||||
});
|
||||
|
||||
it('_mark_all_as_read is an accepted no-op', async () => {
|
||||
const res = await makeHandler(fakeCtx(fakeBridge())).handle('_mark_all_as_read', {});
|
||||
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
@@ -70,6 +70,10 @@
|
||||
"./oidb-actions/media": {
|
||||
"types": "./src/oidb-actions/media.ts",
|
||||
"default": "./src/oidb-actions/media.ts"
|
||||
},
|
||||
"./oidb-actions/ocr": {
|
||||
"types": "./src/oidb-actions/ocr.ts",
|
||||
"default": "./src/oidb-actions/ocr.ts"
|
||||
}
|
||||
},
|
||||
"scripts": {
|
||||
|
||||
@@ -84,10 +84,18 @@ export interface OidbGroupFileMoveReq {
|
||||
parentDirectory?: pb<5, string>;
|
||||
targetDirectory?: pb<6, string>;
|
||||
}
|
||||
export interface OidbGroupFileRenameReq {
|
||||
groupUin?: pb<1, uint_32>;
|
||||
busId?: pb<3, uint_32>;
|
||||
fileId?: pb<4, string>;
|
||||
parentFolder?: pb<5, string>;
|
||||
newFileName?: pb<6, string>;
|
||||
}
|
||||
export interface OidbGroupFileReq {
|
||||
file?: pb<1, OidbGroupFileUploadReq>;
|
||||
download?: pb<3, OidbGroupFileDownloadReq>;
|
||||
delete?: pb<4, OidbGroupFileDeleteReq>;
|
||||
rename?: pb<5, OidbGroupFileRenameReq>;
|
||||
move?: pb<6, OidbGroupFileMoveReq>;
|
||||
}
|
||||
export interface OidbGroupFileUploadResp {
|
||||
@@ -121,6 +129,7 @@ export interface OidbGroupFileResp {
|
||||
upload?: pb<1, OidbGroupFileUploadResp>;
|
||||
download?: pb<3, OidbGroupFileDownloadResp>;
|
||||
delete?: pb<4, OidbGroupFileRetResp>;
|
||||
rename?: pb<5, OidbGroupFileRetResp>;
|
||||
move?: pb<6, OidbGroupFileRetResp>;
|
||||
}
|
||||
export interface OidbGroupSendFileInfo {
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// OIDB 0xE07_0 — server-side image OCR. Field tags verified against
|
||||
// NapCat's Oidb.0xE07 proto AND Lagrange.Core's OidbSvcTrpcTcp.0xE07_0
|
||||
// (the two agree; NapCat's transformer builds with cmd 0xEB7, which is a
|
||||
// typo — the proto name + Lagrange + the `OidbSvcTrpcTcp.0xe07_0` wire
|
||||
// name are authoritative). Request takes an image URL (server fetches it).
|
||||
|
||||
import type { pb, pb_repeated, int_32, uint_32, bool } from '@snowluma/proton';
|
||||
|
||||
export interface OcrReqBody {
|
||||
imageUrl?: pb<1, string>;
|
||||
languageType?: pb<2, uint_32>;
|
||||
scene?: pb<3, uint_32>;
|
||||
originMd5?: pb<10, string>;
|
||||
afterCompressMd5?: pb<11, string>;
|
||||
afterCompressFileSize?: pb<12, string>;
|
||||
afterCompressWeight?: pb<13, string>;
|
||||
afterCompressHeight?: pb<14, string>;
|
||||
isCut?: pb<15, bool>;
|
||||
}
|
||||
export interface ImageOcrReq {
|
||||
version?: pb<1, uint_32>;
|
||||
client?: pb<2, uint_32>;
|
||||
entrance?: pb<3, uint_32>;
|
||||
ocrReqBody?: pb<10, OcrReqBody>;
|
||||
}
|
||||
|
||||
export interface OcrCoordinate {
|
||||
x?: pb<1, int_32>;
|
||||
y?: pb<2, int_32>;
|
||||
}
|
||||
export interface OcrPolygon {
|
||||
coordinates?: pb_repeated<1, OcrCoordinate>;
|
||||
}
|
||||
export interface OcrTextDetection {
|
||||
detectedText?: pb<1, string>;
|
||||
confidence?: pb<2, uint_32>;
|
||||
polygon?: pb<3, OcrPolygon>;
|
||||
advancedInfo?: pb<4, string>;
|
||||
}
|
||||
export interface OcrRspBody {
|
||||
textDetections?: pb_repeated<1, OcrTextDetection>;
|
||||
language?: pb<2, string>;
|
||||
requestId?: pb<3, string>;
|
||||
}
|
||||
export interface ImageOcrResp {
|
||||
retCode?: pb<1, int_32>;
|
||||
errMsg?: pb<2, string>;
|
||||
wording?: pb<3, string>;
|
||||
ocrRspBody?: pb<10, OcrRspBody>;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
@@ -99,6 +99,10 @@
|
||||
"types": "./src/oidb-services/misc/translate-en-to-zh.ts",
|
||||
"default": "./src/oidb-services/misc/translate-en-to-zh.ts"
|
||||
},
|
||||
"./oidb-services/misc/image-ocr": {
|
||||
"types": "./src/oidb-services/misc/image-ocr.ts",
|
||||
"default": "./src/oidb-services/misc/image-ocr.ts"
|
||||
},
|
||||
"./oidb-services/misc/click-inline-keyboard-button": {
|
||||
"types": "./src/oidb-services/misc/click-inline-keyboard-button.ts",
|
||||
"default": "./src/oidb-services/misc/click-inline-keyboard-button.ts"
|
||||
@@ -263,6 +267,10 @@
|
||||
"types": "./src/oidb-services/group-file/move-group-file.ts",
|
||||
"default": "./src/oidb-services/group-file/move-group-file.ts"
|
||||
},
|
||||
"./oidb-services/group-file/rename-group-file": {
|
||||
"types": "./src/oidb-services/group-file/rename-group-file.ts",
|
||||
"default": "./src/oidb-services/group-file/rename-group-file.ts"
|
||||
},
|
||||
"./oidb-services/group-file/create-group-folder": {
|
||||
"types": "./src/oidb-services/group-file/create-group-folder.ts",
|
||||
"default": "./src/oidb-services/group-file/create-group-folder.ts"
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
// 0x6D6_4 — rename a group file (not a folder; that is 0x6D7_2). The
|
||||
// rename slot lives on the shared `OidbGroupFileReq` envelope at field 5.
|
||||
// Wire fields verified against NapCat's Oidb.0x6D6 transformer
|
||||
// (busId=102, parentFolder = the file's CURRENT parent directory).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type {
|
||||
OidbGroupFileReq, OidbGroupFileResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/group-file';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
import { ensureRetCodeZero } from '../shared';
|
||||
|
||||
export namespace RenameGroupFile {
|
||||
export const command = 0x6D6;
|
||||
export const subCommand = 4;
|
||||
export const uinForm = true;
|
||||
|
||||
export interface Params {
|
||||
groupId: number; fileId: string;
|
||||
parentDirectory: string; newFileName: string;
|
||||
}
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileReq => ({
|
||||
rename: {
|
||||
groupUin: p.groupId,
|
||||
busId: 102,
|
||||
fileId: p.fileId,
|
||||
parentFolder: p.parentDirectory,
|
||||
newFileName: p.newFileName,
|
||||
},
|
||||
});
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: OidbGroupFileResp): void => {
|
||||
const result = body.rename;
|
||||
if (!result) throw new Error('group file rename response missing');
|
||||
ensureRetCodeZero('group file rename', result.retCode, result.retMsg, result.clientWording);
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<OidbGroupFileReq>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<OidbGroupFileReq>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileResp> =>
|
||||
protobuf_decode<OidbBase<OidbGroupFileResp>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<void> =>
|
||||
invokeOidb(deps, RenameGroupFile, params);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
// 0xE07_0 — server-side image OCR. Sends an image URL; the server fetches
|
||||
// it and returns detected text + bounding-box polygons. Cmd/sub verified
|
||||
// against Lagrange.Core ([Service("OidbSvcTrpcTcp.0xe07_0")]) and NapCat's
|
||||
// Oidb.0xE07 proto (NapCat's transformer cmd 0xEB7 is a typo). uinForm is
|
||||
// false (NapCat build(..., false, false); Lagrange sends no uid).
|
||||
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr';
|
||||
import { invokeOidb, type OidbSender } from '../../oidb-service';
|
||||
import { ensureRetCodeZero } from '../shared';
|
||||
|
||||
/** One detected text run with its bounding-box vertices. */
|
||||
export interface OcrText {
|
||||
text: string;
|
||||
confidence: number;
|
||||
coordinates: Array<{ x: number; y: number }>;
|
||||
}
|
||||
export interface OcrResult {
|
||||
texts: OcrText[];
|
||||
language: string;
|
||||
}
|
||||
|
||||
export namespace ImageOcr {
|
||||
export const command = 0xE07;
|
||||
export const subCommand = 0;
|
||||
|
||||
export interface Params { imageUrl: string; }
|
||||
export type Deps = OidbSender;
|
||||
|
||||
export const serialize = (_ctx: Deps, p: Params): ImageOcrReq => ({
|
||||
version: 1,
|
||||
client: 0,
|
||||
entrance: 1,
|
||||
ocrReqBody: {
|
||||
imageUrl: p.imageUrl,
|
||||
originMd5: '',
|
||||
afterCompressMd5: '',
|
||||
afterCompressFileSize: '',
|
||||
afterCompressWeight: '',
|
||||
afterCompressHeight: '',
|
||||
isCut: false,
|
||||
},
|
||||
});
|
||||
|
||||
export const deserialize = (_ctx: Deps, body: ImageOcrResp): OcrResult => {
|
||||
ensureRetCodeZero('image ocr', body.retCode, body.errMsg, body.wording);
|
||||
const rsp = body.ocrRspBody;
|
||||
const texts: OcrText[] = (rsp?.textDetections ?? []).map((d) => ({
|
||||
text: d.detectedText ?? '',
|
||||
confidence: d.confidence ?? 0,
|
||||
coordinates: (d.polygon?.coordinates ?? []).map((c) => ({ x: c.x ?? 0, y: c.y ?? 0 })),
|
||||
}));
|
||||
return { texts, language: rsp?.language ?? '' };
|
||||
};
|
||||
|
||||
export const encode = (env: OidbBase<ImageOcrReq>): Uint8Array =>
|
||||
protobuf_encode<OidbBase<ImageOcrReq>>(env);
|
||||
|
||||
export const decode = (bytes: Uint8Array): OidbBase<ImageOcrResp> =>
|
||||
protobuf_decode<OidbBase<ImageOcrResp>>(bytes);
|
||||
|
||||
export const invoke = (deps: Deps, params: Params): Promise<OcrResult> =>
|
||||
invokeOidb(deps, ImageOcr, params);
|
||||
}
|
||||
@@ -163,6 +163,19 @@ export class IncomingPacketPipeline {
|
||||
private async dispatchGroupInvite(event: Extract<QQEventVariant, { kind: 'group_invite' }>): Promise<void> {
|
||||
const uid = event.fromUid;
|
||||
if (uid) {
|
||||
// Record the requester's identity up-front (synchronously), mirroring the
|
||||
// friend_request path — uid-bearing group_invites take this async branch
|
||||
// and would otherwise never store the inviter's uid↔uin when the uin is
|
||||
// already known (needsProfile=false). uin equal to the group's own uin is
|
||||
// the legacy decoder-pollution signature → pass 0 so the map write is
|
||||
// skipped (rememberUidUin short-circuits on uin <= 0).
|
||||
this.deps.identity.rememberRequestIdentity({
|
||||
groupId: event.groupId,
|
||||
uid,
|
||||
uin: event.fromUin > 0 && event.fromUin !== event.groupId ? event.fromUin : 0,
|
||||
source: 'group_request',
|
||||
});
|
||||
|
||||
const subType = event.subType === 'invite' ? 'invite' : 'add';
|
||||
// ALWAYS fetch the verify comment (it's never in the push). Resolve
|
||||
// the UID→UIN profile only when the requester isn't already known —
|
||||
@@ -180,6 +193,13 @@ export class IncomingPacketPipeline {
|
||||
if (needsProfile) {
|
||||
if (profileR.status === 'fulfilled' && profileR.value && profileR.value.uin > 0) {
|
||||
event.fromUin = profileR.value.uin;
|
||||
// uin was unknown/polluted at entry; now resolved → self-heal the map.
|
||||
this.deps.identity.rememberRequestIdentity({
|
||||
groupId: event.groupId,
|
||||
uid,
|
||||
uin: event.fromUin,
|
||||
source: 'group_request',
|
||||
});
|
||||
} else if (profileR.status === 'rejected') {
|
||||
this.log.warn('failed to resolve stranger profile: uid=%s err=%s',
|
||||
uid, profileR.reason instanceof Error ? profileR.reason.message : String(profileR.reason));
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { OidbGroupFileReq, OidbGroupFileResp } from '@snowluma/proto-defs/oidb-actions/group-file';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { RenameGroupFile } from '../../../src/oidb-services/group-file/rename-group-file';
|
||||
|
||||
// A success response the real server would send: command/sub echoed, rename
|
||||
// ret slot with retCode 0. Lets `invoke`'s deserialize pass so we can assert
|
||||
// the request wire (cmd name + body) without it throwing on an empty body.
|
||||
function okRenameResponse(): Buffer {
|
||||
const env: OidbBase<OidbGroupFileResp> = {
|
||||
command: 0x6D6, subCommand: 4, body: { rename: { retCode: 0 } },
|
||||
};
|
||||
return Buffer.from(protobuf_encode<OidbBase<OidbGroupFileResp>>(env));
|
||||
}
|
||||
|
||||
function makeSender() {
|
||||
const defaultResp: SendPacketResult = {
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
|
||||
responseData: okRenameResponse(),
|
||||
};
|
||||
return { sendRawPacket: vi.fn(async () => defaultResp) };
|
||||
}
|
||||
|
||||
describe('RenameGroupFile namespace', () => {
|
||||
it('declares command 0x6D6 sub 4 (rename slot), uin form', () => {
|
||||
expect(RenameGroupFile.command).toBe(0x6D6);
|
||||
expect(RenameGroupFile.subCommand).toBe(4);
|
||||
expect(RenameGroupFile.uinForm).toBe(true);
|
||||
});
|
||||
|
||||
it('serializes into the rename slot with busId 102 and the current parent folder', () => {
|
||||
const out = RenameGroupFile.serialize({} as any, {
|
||||
groupId: 12345, fileId: '/abc', parentDirectory: '/sub', newFileName: 'new.txt',
|
||||
});
|
||||
expect(out).toEqual({
|
||||
rename: {
|
||||
groupUin: 12345, busId: 102, fileId: '/abc', parentFolder: '/sub', newFileName: 'new.txt',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('round-trips the rename body through the OIDB envelope (locks the pb field tags)', async () => {
|
||||
const sender = makeSender();
|
||||
await RenameGroupFile.invoke(sender, {
|
||||
groupId: 12345, fileId: '/abc', parentDirectory: '/', newFileName: 'new.txt',
|
||||
});
|
||||
expect(sender.sendRawPacket).toHaveBeenCalledOnce();
|
||||
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0x6d6_4');
|
||||
const env = protobuf_decode<OidbBase<OidbGroupFileReq>>(bytes);
|
||||
expect(env.command).toBe(0x6D6);
|
||||
expect(env.subCommand).toBe(4);
|
||||
expect(env.body.rename).toMatchObject({
|
||||
groupUin: 12345, busId: 102, fileId: '/abc', parentFolder: '/', newFileName: 'new.txt',
|
||||
});
|
||||
});
|
||||
|
||||
it('deserialize throws when the rename slot is missing from the response', () => {
|
||||
expect(() => RenameGroupFile.deserialize({} as any, {})).toThrow(/rename response missing/);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import type { OidbBase } from '@snowluma/proto-defs/oidb';
|
||||
import type { ImageOcrReq, ImageOcrResp } from '@snowluma/proto-defs/oidb-actions/ocr';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
import { ImageOcr } from '../../../src/oidb-services/misc/image-ocr';
|
||||
|
||||
// A server OCR response: retCode 0, one text detection with a 2-vertex box.
|
||||
function ocrResponse(): Buffer {
|
||||
const env: OidbBase<ImageOcrResp> = {
|
||||
command: 0xE07, subCommand: 0,
|
||||
body: {
|
||||
retCode: 0,
|
||||
ocrRspBody: {
|
||||
language: 'zh',
|
||||
textDetections: [
|
||||
{ detectedText: '你好', confidence: 95, polygon: { coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] } },
|
||||
],
|
||||
},
|
||||
},
|
||||
};
|
||||
return Buffer.from(protobuf_encode<OidbBase<ImageOcrResp>>(env));
|
||||
}
|
||||
|
||||
function makeSender(resp = ocrResponse()) {
|
||||
const r: SendPacketResult = {
|
||||
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: resp,
|
||||
};
|
||||
return { sendRawPacket: vi.fn(async () => r) };
|
||||
}
|
||||
|
||||
describe('ImageOcr namespace', () => {
|
||||
it('declares command 0xE07 sub 0 (no uin form)', () => {
|
||||
expect(ImageOcr.command).toBe(0xE07);
|
||||
expect(ImageOcr.subCommand).toBe(0);
|
||||
expect(ImageOcr.uinForm).toBeUndefined(); // defaults to false in invokeOidb
|
||||
});
|
||||
|
||||
it('serializes the image url into ocrReqBody with the fixed version/client/entrance header', () => {
|
||||
const out = ImageOcr.serialize({} as any, { imageUrl: 'https://x/a.jpg' });
|
||||
expect(out).toMatchObject({ version: 1, client: 0, entrance: 1 });
|
||||
expect(out.ocrReqBody).toMatchObject({ imageUrl: 'https://x/a.jpg', isCut: false });
|
||||
});
|
||||
|
||||
it('routes to OidbSvcTrpcTcp.0xe07_0 and encodes the exact wire bytes (fixed byte-oracle locks pb tags)', async () => {
|
||||
const sender = makeSender();
|
||||
await ImageOcr.invoke(sender, { imageUrl: 'https://x/a.jpg' });
|
||||
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
|
||||
expect(cmd).toBe('OidbSvcTrpcTcp.0xe07_0');
|
||||
// Independent byte-oracle: a fixed hex constant, NOT re-derived from the
|
||||
// proto, so a tag change actually goes red (a symmetric encode→decode
|
||||
// round-trip would not). Hand-decoded: 08 871c = field1 command varint
|
||||
// 0xE07; 22 17 = field4 body (23B); body: 08 01 version=1, 18 01
|
||||
// entrance=1 (client=0 omitted), 52 11 = field10 ocrReqBody (17B):
|
||||
// 0a 0f = field1 imageUrl + "https://x/a.jpg".
|
||||
expect(Buffer.from(bytes).toString('hex'))
|
||||
.toBe('08871c22170801180152110a0f68747470733a2f2f782f612e6a7067');
|
||||
// And the structure decodes back as expected.
|
||||
const env = protobuf_decode<OidbBase<ImageOcrReq>>(bytes);
|
||||
expect(env.command).toBe(0xE07);
|
||||
expect(env.body.ocrReqBody?.imageUrl).toBe('https://x/a.jpg');
|
||||
});
|
||||
|
||||
it('deserializes an empty ocr body to {texts:[], language:""}', () => {
|
||||
expect(ImageOcr.deserialize({} as any, { retCode: 0 })).toEqual({ texts: [], language: '' });
|
||||
});
|
||||
|
||||
it('deserializes text detections + coordinates + language', async () => {
|
||||
const result = await ImageOcr.invoke(makeSender(), { imageUrl: 'https://x/a.jpg' });
|
||||
expect(result.language).toBe('zh');
|
||||
expect(result.texts).toEqual([
|
||||
{ text: '你好', confidence: 95, coordinates: [{ x: 1, y: 2 }, { x: 3, y: 4 }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it('throws on a non-zero retCode', () => {
|
||||
expect(() => ImageOcr.deserialize({} as any, { retCode: 5, errMsg: 'bad', wording: 'nope' }))
|
||||
.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/runtime",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "motricseven@gmail.com"
|
||||
},
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/websocket",
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.9.12",
|
||||
"version": "1.9.13",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select } from '@/components/ui/select';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type {
|
||||
HttpClientNetwork,
|
||||
@@ -447,17 +448,13 @@ function SelectField<T extends string>({
|
||||
return (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<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"
|
||||
>
|
||||
<Select value={value} onChange={(e) => onChange(e.target.value as T)}>
|
||||
{options.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { Bug, Check, Eye, EyeOff, GripVertical, LayoutDashboard, Lock, PlugZap, Settings, Sparkles, SlidersHorizontal, Terminal } from 'lucide-react';
|
||||
import { motion, Reorder } from 'motion/react';
|
||||
import { Link, useRouterState } from '@tanstack/react-router';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
@@ -21,6 +21,7 @@ export const NAV_ITEMS: NavItem[] = [
|
||||
{ to: '/processes', label: '进程注入', icon: PlugZap, description: '加载 / 卸载 / 登录' },
|
||||
{ to: '/config', label: '节点配置', icon: Settings, description: 'OneBot 协议端点' },
|
||||
{ to: '/logs', label: '日志', icon: Terminal, description: '实时事件流' },
|
||||
{ to: '/debug', label: '调试', icon: Bug, description: '测试台与实时活动' },
|
||||
{ to: '/settings', label: '系统设置', icon: SlidersHorizontal, description: '主题与账号' },
|
||||
];
|
||||
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
// Debug — a standalone top-level page (Wave A3, redesigned). Apple-HIG flavour:
|
||||
// clarity (calm type hierarchy, generous whitespace), deference (translucent
|
||||
// chrome, content-first), depth (soft layered cards, a sliding segmented
|
||||
// control). Two tools over /api/debug/*:
|
||||
// • Action 测试台 — pick account + action (schema form / raw JSON), invoke.
|
||||
// • 实时活动 — merged live SSE of events + action calls.
|
||||
import { useEffect, useId, useMemo, useRef, useState, type ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Activity, Bug, ChevronRight, FlaskConical, Loader2, Pause, Play, RadioTower, Trash2 } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Select } from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { DebugActionDoc, DebugInvokeResult, DebugStreamMessage, QQInfo } from '@/types';
|
||||
|
||||
const STREAM_CAP = 300;
|
||||
|
||||
interface StreamRow { id: number; at: number; msg: Extract<DebugStreamMessage, { kind: 'event' | 'action' | 'dropped' }> }
|
||||
|
||||
function coerceParam(type: string, raw: string): unknown {
|
||||
if (raw === '') return undefined;
|
||||
if (type.includes('int') || type === 'number' || type === 'uint') {
|
||||
const n = Number(raw);
|
||||
return Number.isFinite(n) ? n : raw;
|
||||
}
|
||||
if (type === 'bool' || type === 'boolean') return raw === 'true' || raw === '1';
|
||||
return raw;
|
||||
}
|
||||
|
||||
// ── iOS-style segmented control with a sliding active pill ──
|
||||
function Segmented<T extends string>({ value, onChange, options }: {
|
||||
value: T; onChange: (v: T) => void; options: { value: T; label: ReactNode }[];
|
||||
}) {
|
||||
const id = useId();
|
||||
return (
|
||||
<div role="radiogroup" className="inline-flex rounded-full bg-muted/70 p-0.5 text-sm">
|
||||
{options.map((o) => {
|
||||
const active = o.value === value;
|
||||
return (
|
||||
<button
|
||||
key={o.value}
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={active}
|
||||
onClick={() => onChange(o.value)}
|
||||
className={cn('relative rounded-full px-3.5 py-1 font-medium transition-colors',
|
||||
active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground')}
|
||||
>
|
||||
{active && (
|
||||
<motion.span
|
||||
layoutId={`seg-${id}`}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 38 }}
|
||||
className="absolute inset-0 rounded-full bg-card shadow-sm ring-1 ring-border/50"
|
||||
/>
|
||||
)}
|
||||
<span className="relative z-10">{o.label}</span>
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Field({ label, children }: { label: ReactNode; children: ReactNode }) {
|
||||
return (
|
||||
<label className="flex flex-col gap-1.5">
|
||||
<span className="text-xs font-medium text-muted-foreground">{label}</span>
|
||||
{children}
|
||||
</label>
|
||||
);
|
||||
}
|
||||
|
||||
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
|
||||
|
||||
export function DebugPage() {
|
||||
const api = useApi();
|
||||
|
||||
// ── action tester ──
|
||||
const [accounts, setAccounts] = useState<QQInfo[]>([]);
|
||||
const [docs, setDocs] = useState<DebugActionDoc[]>([]);
|
||||
const [uin, setUin] = useState('');
|
||||
const [actionName, setActionName] = useState('');
|
||||
const [fields, setFields] = useState<Record<string, string>>({});
|
||||
const [paramMode, setParamMode] = useState<'form' | 'json'>('form');
|
||||
const [rawJson, setRawJson] = useState('{}');
|
||||
const [invoking, setInvoking] = useState(false);
|
||||
const [result, setResult] = useState<DebugInvokeResult | { error: string } | null>(null);
|
||||
|
||||
const doc = useMemo(() => docs.find((d) => d.name === actionName), [docs, actionName]);
|
||||
const effectiveMode = paramMode === 'json' || !doc ? 'json' : 'form';
|
||||
|
||||
useEffect(() => {
|
||||
void (async () => {
|
||||
try {
|
||||
const [qq, acts] = await Promise.all([api.qqList(), api.debug.actions()]);
|
||||
setAccounts(qq);
|
||||
setDocs(acts.actions);
|
||||
if (qq[0]) setUin(qq[0].uin);
|
||||
} catch { /* surfaced lazily on invoke */ }
|
||||
})();
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const invoke = async () => {
|
||||
if (!uin) { setResult({ error: '请选择账号' }); return; }
|
||||
if (!actionName.trim()) { setResult({ error: '请填写 action' }); return; }
|
||||
let params: Record<string, unknown> = {};
|
||||
if (effectiveMode === 'json') {
|
||||
try { params = JSON.parse(rawJson || '{}'); } catch { setResult({ error: 'params JSON 无效' }); return; }
|
||||
if (typeof params !== 'object' || params === null || Array.isArray(params)) { setResult({ error: 'params 必须是对象' }); return; }
|
||||
} else if (doc) {
|
||||
for (const p of doc.params) {
|
||||
const v = coerceParam(p.type, fields[p.name] ?? '');
|
||||
if (v !== undefined) params[p.name] = v;
|
||||
}
|
||||
}
|
||||
setInvoking(true);
|
||||
setResult(null);
|
||||
try { setResult(await api.debug.invoke(uin, actionName.trim(), params)); }
|
||||
catch (e) { setResult({ error: e instanceof Error ? e.message : '调用失败' }); }
|
||||
finally { setInvoking(false); }
|
||||
};
|
||||
|
||||
const resultFailed = !!result && ('error' in result || result.status === 'failed');
|
||||
|
||||
// ── live stream ──
|
||||
const [rows, setRows] = useState<StreamRow[]>([]);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [status, setStatus] = useState<'open' | 'reconnecting' | 'closed'>('closed');
|
||||
const [kindFilter, setKindFilter] = useState<'all' | 'event' | 'action'>('all');
|
||||
const pausedRef = useRef(paused);
|
||||
pausedRef.current = paused;
|
||||
const idRef = useRef(0);
|
||||
|
||||
useEffect(() => {
|
||||
const off = api.debug.stream(
|
||||
(m) => {
|
||||
if (m.kind === 'ready' || pausedRef.current) return;
|
||||
setRows((prev) => {
|
||||
const next = [{ id: idRef.current++, at: Date.now(), msg: m }, ...prev];
|
||||
return next.length > STREAM_CAP ? next.slice(0, STREAM_CAP) : next;
|
||||
});
|
||||
},
|
||||
(s) => setStatus(s),
|
||||
);
|
||||
return off;
|
||||
}, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const visible = rows.filter((r) => kindFilter === 'all' || r.msg.kind === kindFilter);
|
||||
|
||||
return (
|
||||
<div className="mx-auto flex max-w-6xl flex-col gap-6">
|
||||
{/* header */}
|
||||
<motion.header
|
||||
initial={{ opacity: 0, y: -6 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.3 }}
|
||||
className="sticky top-0 z-10 -mx-1 flex items-center justify-between gap-4 rounded-b-2xl bg-background/60 px-1 py-3 backdrop-blur-xl"
|
||||
>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-10 w-10 items-center justify-center rounded-2xl bg-primary/10 text-primary">
|
||||
<Bug className="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-semibold tracking-tight">调试</h1>
|
||||
<p className="text-sm text-muted-foreground">接口测试台与实时活动观测</p>
|
||||
</div>
|
||||
</div>
|
||||
<StatusPill status={status} />
|
||||
</motion.header>
|
||||
|
||||
<div className="grid grid-cols-1 gap-6 xl:grid-cols-12">
|
||||
{/* tester */}
|
||||
<motion.section
|
||||
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.05 }}
|
||||
className={cn(cardCls, 'flex flex-col gap-5 p-6 xl:col-span-5')}
|
||||
>
|
||||
<div className="flex items-center gap-2.5">
|
||||
<FlaskConical className="h-[18px] w-[18px] text-primary" />
|
||||
<h2 className="text-[15px] font-semibold tracking-tight">Action 测试台</h2>
|
||||
</div>
|
||||
<div className="flex items-start gap-2 rounded-xl bg-amber-500/10 px-3 py-2 text-[12px] leading-relaxed text-amber-700 dark:text-amber-300">
|
||||
<span>调用会<strong className="font-semibold">真实生效</strong>(真发消息 / 真踢人等),请谨慎。</span>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<Field label="账号">
|
||||
<Select value={uin} onChange={(e) => setUin(e.target.value)}>
|
||||
{accounts.length === 0 && <option value="">(无在线账号)</option>}
|
||||
{accounts.map((a) => <option key={a.uin} value={a.uin}>{a.nickname || a.uin}</option>)}
|
||||
</Select>
|
||||
</Field>
|
||||
<Field label="Action">
|
||||
<Input list="dbg-actions" value={actionName} placeholder="send_group_msg"
|
||||
onChange={(e) => { setActionName(e.target.value); setResult(null); }} />
|
||||
<datalist id="dbg-actions">
|
||||
{docs.map((d) => <option key={d.name} value={d.name}>{d.summary}</option>)}
|
||||
</datalist>
|
||||
</Field>
|
||||
</div>
|
||||
|
||||
{doc && (
|
||||
<p className="-mt-1 text-[12px] text-muted-foreground">
|
||||
{doc.summary}{doc.returns ? <> · 返回 <code className="font-mono text-[11px]">{doc.returns}</code></> : null}
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-xs font-medium text-muted-foreground">参数</span>
|
||||
<Segmented
|
||||
value={effectiveMode}
|
||||
onChange={(m) => setParamMode(m)}
|
||||
options={[{ value: 'form', label: '表单' }, { value: 'json', label: 'JSON' }]}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{effectiveMode === 'json' ? (
|
||||
<Textarea className="min-h-28 rounded-xl font-mono text-xs" value={rawJson}
|
||||
onChange={(e) => setRawJson(e.target.value)} placeholder='{ "group_id": 12345, "message": "hi" }' />
|
||||
) : (
|
||||
<div className="flex flex-col gap-3">
|
||||
{doc!.params.length === 0 && <p className="text-[12px] text-muted-foreground">该接口无参数。</p>}
|
||||
{doc!.params.map((p) => (
|
||||
<Field key={p.name} label={<>{p.name}<span className="ml-1 font-normal text-muted-foreground/70">{p.type}{p.required ? ' · 必填' : ''}</span></>}>
|
||||
<Input value={fields[p.name] ?? ''}
|
||||
onChange={(e) => setFields((f) => ({ ...f, [p.name]: e.target.value }))}
|
||||
placeholder={p.desc || (p.default !== undefined ? `默认 ${JSON.stringify(p.default)}` : '')} />
|
||||
</Field>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<button type="button" onClick={invoke} disabled={invoking}
|
||||
className="inline-flex h-11 items-center justify-center gap-2 rounded-xl bg-primary text-[15px] font-medium text-primary-foreground shadow-sm transition-all hover:bg-primary/90 active:scale-[0.99] disabled:opacity-50">
|
||||
{invoking ? <Loader2 className="h-4 w-4 animate-spin" /> : <Play className="h-4 w-4" />} 执行
|
||||
</button>
|
||||
|
||||
{result && (
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<span className={cn('text-xs font-medium', resultFailed ? 'text-destructive' : 'text-success')}>
|
||||
{resultFailed ? '失败' : '成功'}
|
||||
</span>
|
||||
<pre className={cn('max-h-72 overflow-auto rounded-xl border border-border/60 bg-muted/30 p-4 font-mono text-[11.5px] leading-relaxed',
|
||||
resultFailed && 'text-destructive')}>
|
||||
{JSON.stringify(result, null, 2)}
|
||||
</pre>
|
||||
</div>
|
||||
)}
|
||||
</motion.section>
|
||||
|
||||
{/* live stream */}
|
||||
<motion.section
|
||||
initial={{ opacity: 0, y: 10 }} animate={{ opacity: 1, y: 0 }} transition={{ duration: 0.35, delay: 0.1 }}
|
||||
className={cn(cardCls, 'flex min-h-[28rem] flex-col p-6 xl:col-span-7')}
|
||||
>
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="flex items-center gap-2.5">
|
||||
<RadioTower className="h-[18px] w-[18px] text-primary" />
|
||||
<h2 className="text-[15px] font-semibold tracking-tight">实时活动</h2>
|
||||
<span className="text-xs text-muted-foreground tabular-nums">{visible.length}</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Segmented
|
||||
value={kindFilter}
|
||||
onChange={setKindFilter}
|
||||
options={[{ value: 'all', label: '全部' }, { value: 'event', label: '事件' }, { value: 'action', label: '调用' }]}
|
||||
/>
|
||||
<IconBtn onClick={() => setPaused((v) => !v)} title={paused ? '继续' : '暂停'}>
|
||||
{paused ? <Play className="h-4 w-4" /> : <Pause className="h-4 w-4" />}
|
||||
</IconBtn>
|
||||
<IconBtn onClick={() => setRows([])} title="清空"><Trash2 className="h-4 w-4" /></IconBtn>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="mt-4 flex flex-1 flex-col gap-1 overflow-auto">
|
||||
{visible.length === 0 ? (
|
||||
<div className="flex flex-1 flex-col items-center justify-center gap-3 py-12 text-center">
|
||||
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-muted/60">
|
||||
<Activity className="h-6 w-6 text-muted-foreground/70" />
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">{paused ? '已暂停' : '等待事件…'}</p>
|
||||
</div>
|
||||
) : (
|
||||
visible.map((r) => <StreamRowItem key={r.id} row={r} />)
|
||||
)}
|
||||
</div>
|
||||
</motion.section>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function IconBtn({ onClick, title, children }: { onClick: () => void; title: string; children: ReactNode }) {
|
||||
return (
|
||||
<button type="button" onClick={onClick} title={title} aria-label={title}
|
||||
className="flex h-8 w-8 items-center justify-center rounded-full text-muted-foreground transition-colors hover:bg-muted hover:text-foreground">
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
function StatusPill({ status }: { status: 'open' | 'reconnecting' | 'closed' }) {
|
||||
const map = {
|
||||
open: { dot: 'bg-emerald-500', label: '已连接', glow: 'shadow-[0_0_0_3px_rgb(16_185_129/0.15)]' },
|
||||
reconnecting: { dot: 'bg-amber-500', label: '重连中', glow: 'shadow-[0_0_0_3px_rgb(245_158_11/0.15)]' },
|
||||
closed: { dot: 'bg-muted-foreground/50', label: '未连接', glow: '' },
|
||||
}[status];
|
||||
return (
|
||||
<div className="inline-flex items-center gap-2 rounded-full border border-border/60 bg-card/70 px-3 py-1.5 text-xs font-medium backdrop-blur-sm">
|
||||
<span className={cn('h-2 w-2 rounded-full', map.dot, map.glow)} />
|
||||
<span className="text-muted-foreground">{map.label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function StreamRowItem({ row }: { row: StreamRow }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const { msg } = row;
|
||||
const time = new Date(row.at).toLocaleTimeString('zh-CN', { hour12: false });
|
||||
|
||||
if (msg.kind === 'dropped') {
|
||||
return <div className="px-2 py-1.5 text-[11px] text-amber-600 dark:text-amber-400">因客户端过慢丢弃了 {msg.count} 条</div>;
|
||||
}
|
||||
|
||||
const isAction = msg.kind === 'action';
|
||||
let label: string;
|
||||
let detail: unknown;
|
||||
let ok = true;
|
||||
if (msg.kind === 'event') {
|
||||
const e = msg.event as Record<string, unknown>;
|
||||
label = `${e.post_type ?? 'event'}${e.message_type ? `.${e.message_type}` : e.notice_type ? `.${e.notice_type}` : ''}`;
|
||||
detail = e;
|
||||
} else {
|
||||
ok = (msg.response as { status?: string }).status === 'ok';
|
||||
label = msg.action;
|
||||
detail = { params: msg.params, response: msg.response };
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="group rounded-xl transition-colors hover:bg-muted/40">
|
||||
<button type="button" aria-expanded={open} className="flex w-full items-center gap-2.5 px-2.5 py-2 text-left text-[13px]" onClick={() => setOpen((v) => !v)}>
|
||||
<ChevronRight className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground tabular-nums">{time}</span>
|
||||
<span className={cn('shrink-0 rounded-md px-1.5 py-0.5 text-[10px] font-semibold',
|
||||
isAction ? 'bg-primary/12 text-primary' : 'bg-muted text-muted-foreground')}>
|
||||
{isAction ? '调用' : '事件'}
|
||||
</span>
|
||||
<span className="shrink-0 font-mono text-[11px] text-muted-foreground/80">{msg.uin}</span>
|
||||
<span className="min-w-0 flex-1 truncate font-mono text-foreground/90">{label}</span>
|
||||
{isAction && (
|
||||
<span className={cn('shrink-0 text-[11px] tabular-nums', ok ? 'text-success' : 'text-destructive')}>
|
||||
{ok ? 'ok' : 'failed'} · {msg.ms}ms
|
||||
</span>
|
||||
)}
|
||||
</button>
|
||||
{open && (
|
||||
<pre className="mx-2.5 mb-2 max-h-72 overflow-auto rounded-lg bg-muted/40 p-3 font-mono text-[11px] leading-relaxed">
|
||||
{JSON.stringify(detail, null, 2)}
|
||||
</pre>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -2,13 +2,14 @@ import { createContext, useContext, useId, useRef, useState, type ReactNode } fr
|
||||
import { motion } from 'motion/react';
|
||||
import {
|
||||
Accessibility, AlertTriangle, Bell, Bug, Check, Clock, Code2, Download, ExternalLink, Github, Image as ImageIcon,
|
||||
Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, ShieldCheck,
|
||||
Info, KeyRound, Loader2, Monitor, Moon, Palette, PanelTop, Plus, RefreshCw, RotateCcw, Server, ShieldCheck,
|
||||
Sparkles, Star, Sun, Tag, Upload, Trash2,
|
||||
} from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { Slider } from '@/components/ui/slider';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import {
|
||||
ACCENTS,
|
||||
DEFAULT_APPEARANCE,
|
||||
@@ -41,12 +42,14 @@ import { useAppState } from '@/contexts/AppStateContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { settingsRoute, type SettingsTab } from '@/router';
|
||||
import { NotificationsPanel } from '@/components/settings/notifications-panel';
|
||||
import { SystemPanel } from '@/components/settings/system-panel';
|
||||
|
||||
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
|
||||
{ key: 'appearance', label: '外观', icon: Palette },
|
||||
{ key: 'data', label: '数据与格式', icon: RefreshCw },
|
||||
{ key: 'advanced', label: '高级', icon: Code2 },
|
||||
{ key: 'account', label: '账号安全', icon: ShieldCheck },
|
||||
{ key: 'system', label: '服务', icon: Server },
|
||||
{ key: 'notifications', label: '通知', icon: Bell },
|
||||
{ key: 'about', label: '关于', icon: Info },
|
||||
];
|
||||
@@ -78,6 +81,7 @@ export function SettingsPage() {
|
||||
{tab === 'data' && <DataPanel />}
|
||||
{tab === 'advanced' && <AdvancedPanel />}
|
||||
{tab === 'account' && <AccountPanel />}
|
||||
{tab === 'system' && <SystemPanel />}
|
||||
{tab === 'notifications' && <NotificationsPanel />}
|
||||
{tab === 'about' && <AboutPanel />}
|
||||
</motion.div>
|
||||
@@ -977,7 +981,7 @@ function AdvancedPanel() {
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<textarea
|
||||
<Textarea
|
||||
ref={cssRef}
|
||||
value={appearance.customCss}
|
||||
onChange={(e) => { setAppearance({ customCss: e.target.value }); if (cssWarn) setCssWarn(null); }}
|
||||
@@ -985,7 +989,7 @@ function AdvancedPanel() {
|
||||
maxLength={50000}
|
||||
spellCheck={false}
|
||||
placeholder={'/* 例如:放大侧栏字号 */\n.text-sidebar-foreground { font-size: 1.05em; }'}
|
||||
className="h-64 w-full resize-y rounded-lg border bg-card/40 p-3 font-mono text-[12px] leading-relaxed outline-none focus:border-primary"
|
||||
className="h-64 resize-y rounded-lg bg-card/40 p-3 font-mono text-[12px] leading-relaxed"
|
||||
/>
|
||||
{cssWarn && (
|
||||
<p className="flex items-start gap-1.5 text-[11px] text-warning">
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useId } from 'react';
|
||||
import { Bell, BookOpen, ExternalLink, Github, Globe, Link2, Server, Star } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useAppState } from '@/contexts/AppStateContext';
|
||||
import {
|
||||
@@ -172,13 +173,13 @@ export function NoteConfigForm({ config, onChange }: FormProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<span className="text-sm text-muted-foreground">便签内容(纯文本,保留换行)</span>
|
||||
<textarea
|
||||
<Textarea
|
||||
value={c.text}
|
||||
onChange={(e) => onChange({ text: e.target.value.slice(0, NOTE_MAX) })}
|
||||
maxLength={NOTE_MAX}
|
||||
spellCheck={false}
|
||||
placeholder="写点备注、待办或快捷信息…"
|
||||
className="h-40 w-full resize-y rounded-lg border bg-card/40 p-3 text-sm leading-relaxed outline-none focus:border-primary"
|
||||
className="h-40 resize-y rounded-lg bg-card/40 p-3 text-sm leading-relaxed"
|
||||
/>
|
||||
<span className="text-right text-[11px] text-muted-foreground">{c.text.length} / {NOTE_MAX}</span>
|
||||
</div>
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { NotificationChannel } from '@/types';
|
||||
@@ -100,12 +101,12 @@ export function NotificationChannelDialog(props: NotificationChannelDialogProps)
|
||||
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>Body 模板</Label>
|
||||
<textarea
|
||||
<Textarea
|
||||
value={draft.bodyTemplate}
|
||||
rows={3}
|
||||
spellCheck={false}
|
||||
onChange={(e) => patch({ bodyTemplate: e.target.value })}
|
||||
className="w-full rounded-md border border-border bg-transparent px-3 py-2 font-mono text-xs leading-relaxed shadow-xs outline-none transition-[color,box-shadow] placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40"
|
||||
className="font-mono text-xs leading-relaxed"
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
变量:<code className="font-mono">{'{uin}'}</code> <code className="font-mono">{'{nickname}'}</code>{' '}
|
||||
|
||||
@@ -16,7 +16,10 @@ import { cn } from '@/lib/utils';
|
||||
import type { NotificationChannel, NotificationsConfig } from '@/types';
|
||||
import { NotificationChannelDialog } from './notification-channel-dialog';
|
||||
|
||||
const DEFAULT_TEMPLATE = '{nickname}({uin}) {event} @ {time}';
|
||||
const DEFAULT_TEMPLATE = `{
|
||||
"title": "账号状态通知:{event}",
|
||||
"desp": "您的账号状态发生了改变。\\n\\n**昵称**:{nickname}\\n**QQ号**:{uin}\\n**当前状态**:{event}\\n**时间**:{time}"
|
||||
}`;
|
||||
|
||||
/** A fresh channel with a non-colliding default id. */
|
||||
function blankChannel(existing: NotificationChannel[]): NotificationChannel {
|
||||
|
||||
@@ -0,0 +1,315 @@
|
||||
// Settings → 服务 tab (Wave A1). Edits the WebUI listener's own config
|
||||
// (port / bind host / trust-proxy / HTTPS). Listener-level changes are
|
||||
// persisted but apply only after a restart — there is no supervisor to
|
||||
// self-restart, so we never offer a "restart now" button, only a banner.
|
||||
// Fields currently pinned by SNOWLUMA_* env vars are flagged (edits to them
|
||||
// won't take effect until the env var is removed).
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { AlertTriangle, Database, Download, Loader2, Lock, Pencil, Save, ShieldCheck, Trash2, Upload } from 'lucide-react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select } from '@/components/ui/select';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { useApi } from '@/lib/api';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { SystemSettingsResponse } from '@/types';
|
||||
|
||||
export function SystemPanel() {
|
||||
const api = useApi();
|
||||
const [data, setData] = useState<SystemSettingsResponse | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null);
|
||||
|
||||
// editable form state
|
||||
const [port, setPort] = useState('');
|
||||
const [host, setHost] = useState('0.0.0.0');
|
||||
const [trustProxy, setTrustProxy] = useState('');
|
||||
const [tlsEnabled, setTlsEnabled] = useState(false);
|
||||
const [certPem, setCertPem] = useState('');
|
||||
const [keyPem, setKeyPem] = useState('');
|
||||
// When a cert is already installed we hide the PEM inputs (sensitive) and
|
||||
// show a "已安装" summary + 更改 button; editing reveals the inputs again.
|
||||
const [editingCert, setEditingCert] = useState(false);
|
||||
|
||||
// backup / restore
|
||||
const [exportCreds, setExportCreds] = useState(false);
|
||||
const [restoreCreds, setRestoreCreds] = useState(false);
|
||||
const fileRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const load = async () => {
|
||||
try {
|
||||
const res = await api.systemSettings.get();
|
||||
setData(res);
|
||||
setPort(String(res.settings.webuiPort));
|
||||
setHost(res.settings.webuiHost);
|
||||
setTrustProxy(res.settings.trustProxy);
|
||||
setTlsEnabled(res.settings.tlsEnabled);
|
||||
} catch {
|
||||
setMsg({ kind: 'err', text: '加载系统设置失败' });
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => { void load(); }, []); // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
const overridden = (field: string) => data?.envOverrides.includes(field) ?? false;
|
||||
const flash = (kind: 'ok' | 'err', text: string) => {
|
||||
setMsg({ kind, text });
|
||||
window.setTimeout(() => setMsg(null), 4000);
|
||||
};
|
||||
|
||||
const saveSettings = async () => {
|
||||
const portNum = Number(port);
|
||||
if (!Number.isInteger(portNum) || portNum <= 0 || portNum > 65535) {
|
||||
flash('err', '端口必须是 1–65535 的整数');
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.systemSettings.save({ webuiPort: portNum, webuiHost: host.trim(), trustProxy, tlsEnabled });
|
||||
await load();
|
||||
flash('ok', '已保存,重启 SnowLuma 后生效');
|
||||
} catch (e) {
|
||||
flash('err', e instanceof Error ? e.message : '保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const uploadCert = async () => {
|
||||
if (!certPem.trim() || !keyPem.trim()) { flash('err', '请同时填入证书与私钥'); return; }
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.systemSettings.uploadCert(certPem, keyPem);
|
||||
setCertPem(''); setKeyPem('');
|
||||
setEditingCert(false);
|
||||
await load();
|
||||
flash('ok', '证书已保存,重启后生效');
|
||||
} catch (e) {
|
||||
flash('err', e instanceof Error ? e.message : '证书保存失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const deleteCert = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
await api.systemSettings.deleteCert();
|
||||
setEditingCert(false);
|
||||
await load();
|
||||
flash('ok', '证书已删除');
|
||||
} catch (e) {
|
||||
flash('err', e instanceof Error ? e.message : '删除失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const exportBackup = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const bundle = await api.systemSettings.exportBackup(exportCreds);
|
||||
const blob = new Blob([JSON.stringify(bundle, null, 2)], { type: 'application/json' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `snowluma-backup-${new Date().toISOString().replace(/[:.]/g, '-')}.json`;
|
||||
a.click();
|
||||
URL.revokeObjectURL(url);
|
||||
flash('ok', '已导出备份');
|
||||
} catch (e) {
|
||||
flash('err', e instanceof Error ? e.message : '导出失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const importBackup = async (file: File) => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const text = await file.text();
|
||||
let parsed: Record<string, unknown>;
|
||||
try { parsed = JSON.parse(text); } catch { flash('err', '文件不是有效的 JSON'); return; }
|
||||
const res = await api.systemSettings.importBackup(parsed, restoreCreds);
|
||||
const parts = [`已恢复 ${res.restored.length} 项`];
|
||||
if (res.skipped.length) parts.push(`跳过 ${res.skipped.length} 项(凭据未恢复)`);
|
||||
flash('ok', `${parts.join(',')},重启后生效`);
|
||||
} catch (e) {
|
||||
flash('err', e instanceof Error ? e.message : '恢复失败');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
if (fileRef.current) fileRef.current.value = '';
|
||||
}
|
||||
};
|
||||
|
||||
if (loading) {
|
||||
return <div className="flex items-center gap-2 px-1 py-8 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" /> 加载中…</div>;
|
||||
}
|
||||
|
||||
const EnvBadge = ({ field }: { field: string }) =>
|
||||
overridden(field)
|
||||
? <Badge variant="secondary" className="ml-2 gap-1 text-[10px]"><Lock className="h-3 w-3" /> 被环境变量覆盖</Badge>
|
||||
: null;
|
||||
|
||||
return (
|
||||
<motion.div initial={{ opacity: 0, y: 8 }} animate={{ opacity: 1, y: 0 }} className="flex flex-col gap-5">
|
||||
{/* restart-to-apply notice */}
|
||||
<div className="flex items-start gap-2 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-700 dark:text-amber-300">
|
||||
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
|
||||
<span>监听相关设置(端口 / 绑定地址 / HTTPS)属服务级配置,保存后需<strong>重启 SnowLuma</strong> 才生效;本机无自动重启。</span>
|
||||
</div>
|
||||
|
||||
{msg && (
|
||||
<div className={cn('rounded-lg px-3 py-2 text-xs', msg.kind === 'ok'
|
||||
? 'bg-emerald-500/10 text-emerald-700 dark:text-emerald-300'
|
||||
: 'bg-red-500/10 text-red-700 dark:text-red-300')}>{msg.text}</div>
|
||||
)}
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-sm">服务监听</CardTitle>
|
||||
<CardDescription>WebUI 当前监听端口:{data?.listeningPort}</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="flex items-center">端口<EnvBadge field="webuiPort" /></Label>
|
||||
<Input value={port} onChange={(e) => setPort(e.target.value)} inputMode="numeric" placeholder="5099" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="flex items-center">绑定地址<EnvBadge field="webuiHost" /></Label>
|
||||
<Select value={host} onChange={(e) => setHost(e.target.value)}>
|
||||
<option value="0.0.0.0">0.0.0.0(所有网卡)</option>
|
||||
<option value="127.0.0.1">127.0.0.1(仅本机)</option>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label className="flex items-center">信任代理 (trust-proxy)<EnvBadge field="trustProxy" /></Label>
|
||||
<Input value={trustProxy} onChange={(e) => setTrustProxy(e.target.value)} placeholder="留空=只信任 socket 对端;1=信任反代头" />
|
||||
<p className="text-[11px] text-muted-foreground">仅在 WebUI 位于受信任反向代理之后时才设为 1 / loopback / IP 列表。</p>
|
||||
</div>
|
||||
<div>
|
||||
<Button onClick={saveSettings} disabled={saving} className="gap-1.5">
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />} 保存
|
||||
</Button>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm">
|
||||
<ShieldCheck className="h-4 w-4" /> HTTPS / TLS
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{data?.hasCert ? '已安装证书。' : '尚未安装证书。'} 启用 TLS 需先安装有效的证书与私钥(PEM)。
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>启用 HTTPS</Label>
|
||||
<ToggleSwitch value={tlsEnabled} onChange={setTlsEnabled} ariaLabel="启用 HTTPS" />
|
||||
</div>
|
||||
|
||||
{data?.hasCert && !editingCert ? (
|
||||
// Cert already installed — don't re-render the sensitive PEM. Show a
|
||||
// summary + actions; private key is never sent back to the client.
|
||||
<div className="flex flex-col gap-3">
|
||||
<div className="flex items-center gap-2 rounded-lg border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground">
|
||||
<ShieldCheck className="h-4 w-4 text-emerald-500" />
|
||||
<span>证书与私钥已安装(出于安全不回显,未改变)。</span>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => setEditingCert(true)} className="gap-1.5">
|
||||
<Pencil className="h-4 w-4" /> 更改证书
|
||||
</Button>
|
||||
<Button variant="outline" onClick={deleteCert} disabled={saving} className="gap-1.5">
|
||||
<Trash2 className="h-4 w-4" /> 删除证书
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>证书 (cert.pem)</Label>
|
||||
<Textarea className="min-h-28 font-mono text-xs" value={certPem} onChange={(e) => setCertPem(e.target.value)} placeholder="-----BEGIN CERTIFICATE-----" />
|
||||
</div>
|
||||
<div className="flex flex-col gap-1.5">
|
||||
<Label>私钥 (key.pem)</Label>
|
||||
<Textarea className="min-h-28 font-mono text-xs" value={keyPem} onChange={(e) => setKeyPem(e.target.value)} placeholder="-----BEGIN PRIVATE KEY-----" />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<Button onClick={uploadCert} disabled={saving} className="gap-1.5">
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Save className="h-4 w-4" />} 保存证书
|
||||
</Button>
|
||||
{data?.hasCert && editingCert && (
|
||||
<Button variant="outline" onClick={() => { setEditingCert(false); setCertPem(''); setKeyPem(''); }} className="gap-1.5">
|
||||
取消
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">
|
||||
私钥仅写入服务器 config/key.pem(0600 权限),不会回显。证书无效时保存会被拒绝;若启用了 TLS 但证书加载失败,启动时会自动回退到 HTTP。
|
||||
</p>
|
||||
</>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2 text-sm"><Database className="h-4 w-4" /> 配置备份 / 恢复</CardTitle>
|
||||
<CardDescription>导出/导入全部配置(OneBot、外观、通知、系统设置、证书)。不含消息数据库。</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>导出时包含登录凭据</Label>
|
||||
<ToggleSwitch value={exportCreds} onChange={setExportCreds} ariaLabel="导出包含登录凭据" />
|
||||
</div>
|
||||
{exportCreds && (
|
||||
<p className="text-[11px] text-red-600 dark:text-red-400">⚠ 备份文件将包含登录口令哈希与 TLS 私钥,请妥善保管。</p>
|
||||
)}
|
||||
<div>
|
||||
<Button onClick={exportBackup} disabled={saving} className="gap-1.5">
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />} 导出备份
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="h-px bg-border" />
|
||||
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Label>恢复时一并恢复登录凭据</Label>
|
||||
<ToggleSwitch value={restoreCreds} onChange={setRestoreCreds} ariaLabel="恢复包含登录凭据" />
|
||||
</div>
|
||||
{restoreCreds && (
|
||||
<p className="text-[11px] text-red-600 dark:text-red-400">⚠ 将覆盖当前登录口令与私钥;若备份口令未知可能登不进。</p>
|
||||
)}
|
||||
<input
|
||||
ref={fileRef}
|
||||
type="file"
|
||||
accept="application/json,.json"
|
||||
className="hidden"
|
||||
onChange={(e) => { const f = e.target.files?.[0]; if (f) void importBackup(f); }}
|
||||
/>
|
||||
<div>
|
||||
<Button variant="outline" onClick={() => fileRef.current?.click()} disabled={saving} className="gap-1.5">
|
||||
{saving ? <Loader2 className="h-4 w-4 animate-spin" /> : <Upload className="h-4 w-4" />} 选择备份文件并恢复
|
||||
</Button>
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground">恢复前会自动把当前配置快照到 config/.restore-backup-*;恢复后需重启生效。</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</motion.div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import * as React from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// A styled native <select> matching Input's design language. Native keeps it
|
||||
// accessible + zero-dep; we hide the OS arrow (appearance-none) and draw our
|
||||
// own chevron for a consistent look. Pass <option>s as children.
|
||||
const Select = React.forwardRef<HTMLSelectElement, React.SelectHTMLAttributes<HTMLSelectElement>>(
|
||||
({ className, children, ...props }, ref) => (
|
||||
<div className="relative w-full">
|
||||
<select
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex h-9 w-full min-w-0 appearance-none rounded-md border border-border bg-transparent px-3 py-1 pr-8 text-sm shadow-xs transition-[color,box-shadow] outline-none',
|
||||
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
>
|
||||
{children}
|
||||
</select>
|
||||
<ChevronDown className="pointer-events-none absolute right-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
|
||||
</div>
|
||||
)
|
||||
);
|
||||
Select.displayName = 'Select';
|
||||
|
||||
export { Select };
|
||||
@@ -0,0 +1,25 @@
|
||||
import * as React from 'react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Shares Input's design language (border-border, bg-transparent, shadow-xs,
|
||||
// focus ring). Callers may override surface specifics (height, resize, bg,
|
||||
// font-mono) via className — twMerge lets later classes win.
|
||||
const Textarea = React.forwardRef<HTMLTextAreaElement, React.TextareaHTMLAttributes<HTMLTextAreaElement>>(
|
||||
({ className, ...props }, ref) => (
|
||||
<textarea
|
||||
ref={ref}
|
||||
className={cn(
|
||||
'flex w-full min-w-0 rounded-md border border-border bg-transparent px-3 py-2 text-sm shadow-xs transition-[color,box-shadow] outline-none',
|
||||
'placeholder:text-muted-foreground',
|
||||
'focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/40',
|
||||
'disabled:cursor-not-allowed disabled:opacity-50',
|
||||
'aria-invalid:border-destructive aria-invalid:ring-destructive/20',
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
);
|
||||
Textarea.displayName = 'Textarea';
|
||||
|
||||
export { Textarea };
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, UiAppearance, UiConfig, UpdateInfo } from '@/types';
|
||||
import type { AccountConnections, BackupBundle, BackupImportResult, DebugActionDoc, DebugInvokeResult, DebugStreamMessage, HookProcessInfo, LogEntry, LogLevel, NotificationDeliveryRecord, NotificationsConfig, QQInfo, SystemInfo, SystemSettingsPatch, SystemSettingsResponse, UiAppearance, UiConfig, UpdateInfo } from '@/types';
|
||||
import type { PasswordRule } from '@/components/pages/change-password-page';
|
||||
import { normalizeOneBotConfig } from '@/lib/onebot-config';
|
||||
import {
|
||||
@@ -45,6 +45,8 @@ class HttpApiClient implements ApiClient {
|
||||
readonly update: ApiClient['update'];
|
||||
readonly ui: ApiClient['ui'];
|
||||
readonly notifications: ApiClient['notifications'];
|
||||
readonly systemSettings: ApiClient['systemSettings'];
|
||||
readonly debug: ApiClient['debug'];
|
||||
|
||||
constructor(opts: CreateApiClientOptions = {}) {
|
||||
this.tokenStore = opts.tokenStore ?? localStorageTokenStore(DEFAULT_TOKEN_KEY);
|
||||
@@ -98,6 +100,32 @@ class HttpApiClient implements ApiClient {
|
||||
this.getJson<UpdateInfo>(`/api/update/check${force ? '?force=true' : ''}`),
|
||||
};
|
||||
|
||||
this.systemSettings = {
|
||||
get: () => this.getJson<SystemSettingsResponse>('/api/system/settings'),
|
||||
save: (patch: SystemSettingsPatch) =>
|
||||
this.postJson<{ settings: SystemSettingsResponse['settings']; restartRequiredToApply: boolean }>(
|
||||
'/api/system/settings',
|
||||
patch,
|
||||
),
|
||||
uploadCert: async (cert: string, key: string) => {
|
||||
await this.postJson<{ success: boolean }>('/api/system/tls/cert', { cert, key });
|
||||
},
|
||||
deleteCert: async () => {
|
||||
await this.fetchJson<{ success: boolean }>('/api/system/tls/cert', { method: 'DELETE' });
|
||||
},
|
||||
exportBackup: (includeCredentials: boolean) =>
|
||||
this.getJson<BackupBundle>(`/api/system/backup/export${includeCredentials ? '?credentials=1' : ''}`),
|
||||
importBackup: (backup: BackupBundle, restoreCredentials: boolean) =>
|
||||
this.postJson<BackupImportResult>('/api/system/backup/import', { backup, restoreCredentials }),
|
||||
};
|
||||
|
||||
this.debug = {
|
||||
actions: () => this.getJson<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>('/api/debug/actions'),
|
||||
invoke: (uin: string, action: string, params: Record<string, unknown>) =>
|
||||
this.postJson<DebugInvokeResult>('/api/debug/invoke', { uin, action, params }),
|
||||
stream: (onMessage, onStatus) => this.openDebugStream(onMessage, onStatus),
|
||||
};
|
||||
|
||||
this.ui = {
|
||||
get: () => this.getJson<{ config: UiConfig }>('/api/ui').then((d) => d.config),
|
||||
save: async (config) => {
|
||||
@@ -319,6 +347,21 @@ class HttpApiClient implements ApiClient {
|
||||
options.onStatus?.('closed');
|
||||
};
|
||||
}
|
||||
|
||||
private openDebugStream(
|
||||
onMessage: (m: DebugStreamMessage) => void,
|
||||
onStatus?: (s: import('./types').StreamStatus) => void,
|
||||
): () => void {
|
||||
if (!this.currentToken) { onStatus?.('closed'); return () => {}; }
|
||||
const url = `/api/debug/stream?token=${encodeURIComponent(this.currentToken)}`;
|
||||
const source = new EventSource(url);
|
||||
source.onopen = () => onStatus?.('open');
|
||||
source.onerror = () => onStatus?.('reconnecting');
|
||||
source.onmessage = (event) => {
|
||||
try { onMessage(JSON.parse(event.data) as DebugStreamMessage); } catch { /* skip malformed */ }
|
||||
};
|
||||
return () => { source.close(); onStatus?.('closed'); };
|
||||
}
|
||||
}
|
||||
|
||||
export function createApiClient(options: CreateApiClientOptions = {}): ApiClient {
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import type {
|
||||
AccountConnections,
|
||||
BackupBundle,
|
||||
BackupImportResult,
|
||||
DebugActionDoc,
|
||||
DebugInvokeResult,
|
||||
DebugStreamMessage,
|
||||
HookProcessInfo,
|
||||
LogEntry,
|
||||
LogLevel,
|
||||
@@ -8,6 +13,9 @@ import type {
|
||||
OneBotConfig,
|
||||
QQInfo,
|
||||
SystemInfo,
|
||||
SystemSettings,
|
||||
SystemSettingsPatch,
|
||||
SystemSettingsResponse,
|
||||
UiAppearance,
|
||||
UiConfig,
|
||||
UpdateInfo,
|
||||
@@ -74,6 +82,27 @@ export interface ApiClient {
|
||||
save(uin: string, config: OneBotConfig): Promise<OneBotConfig>;
|
||||
};
|
||||
|
||||
// ---- WebUI listener self-config (port / host / TLS / trust-proxy) ----
|
||||
systemSettings: {
|
||||
get(): Promise<SystemSettingsResponse>;
|
||||
save(patch: SystemSettingsPatch): Promise<{ settings: SystemSettings; restartRequiredToApply: boolean }>;
|
||||
/** Validate + write config/cert.pem + key.pem (restart to apply). */
|
||||
uploadCert(cert: string, key: string): Promise<void>;
|
||||
deleteCert(): Promise<void>;
|
||||
/** Download the config backup bundle (credentials gated). */
|
||||
exportBackup(includeCredentials: boolean): Promise<BackupBundle>;
|
||||
/** Validate + restore a bundle (snapshots current config first). */
|
||||
importBackup(backup: BackupBundle, restoreCredentials: boolean): Promise<BackupImportResult>;
|
||||
};
|
||||
|
||||
// ---- debug tools (action tester + live event/action stream) ----
|
||||
debug: {
|
||||
actions(): Promise<{ actions: DebugActionDoc[]; categories: { category: string; count: number }[] }>;
|
||||
invoke(uin: string, action: string, params: Record<string, unknown>): Promise<DebugInvokeResult>;
|
||||
/** Live merged SSE; returns an unsubscribe. */
|
||||
stream(onMessage: (m: DebugStreamMessage) => void, onStatus?: (s: StreamStatus) => void): () => void;
|
||||
};
|
||||
|
||||
// ---- notifications (account up/down webhooks) ----
|
||||
notifications: {
|
||||
/** Global channel store (channels + debounce). Bearer-gated. */
|
||||
|
||||
@@ -64,8 +64,17 @@ const logsRoute = createRoute({
|
||||
),
|
||||
});
|
||||
|
||||
const debugRoute = createRoute({
|
||||
path: '/debug',
|
||||
getParentRoute: () => appLayoutRoute,
|
||||
component: lazyRouteComponent(
|
||||
() => import('@/components/pages/debug-page'),
|
||||
'DebugPage',
|
||||
),
|
||||
});
|
||||
|
||||
/** Settings sub-tabs — also the contract for the `?tab=` deep link. */
|
||||
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'notifications', 'about'] as const;
|
||||
export const SETTINGS_TABS = ['appearance', 'data', 'advanced', 'account', 'system', 'notifications', 'about'] as const;
|
||||
export type SettingsTab = (typeof SETTINGS_TABS)[number];
|
||||
|
||||
export const settingsRoute = createRoute({
|
||||
@@ -86,7 +95,7 @@ export const settingsRoute = createRoute({
|
||||
});
|
||||
|
||||
const routeTree = rootRoute.addChildren([
|
||||
appLayoutRoute.addChildren([overviewRoute, processesRoute, configRoute, logsRoute, settingsRoute]),
|
||||
appLayoutRoute.addChildren([overviewRoute, processesRoute, configRoute, logsRoute, debugRoute, settingsRoute]),
|
||||
]);
|
||||
|
||||
export const appRouter = createRouter({
|
||||
@@ -103,4 +112,4 @@ declare module '@tanstack/react-router' {
|
||||
}
|
||||
|
||||
/** Paths registered on the layout — single source of truth for nav metadata. */
|
||||
export type AppPath = '/' | '/processes' | '/config' | '/logs' | '/settings';
|
||||
export type AppPath = '/' | '/processes' | '/config' | '/logs' | '/debug' | '/settings';
|
||||
@@ -141,6 +141,64 @@ export interface NotificationDeliveryRecord {
|
||||
|
||||
export type NetworkKind = keyof OneBotNetworks;
|
||||
|
||||
// WebUI listener self-config (Wave A1). Listener-level changes are
|
||||
// restart-to-apply; `envOverrides` lists fields currently pinned by env vars.
|
||||
export interface SystemSettings {
|
||||
webuiPort: number;
|
||||
webuiHost: string;
|
||||
tlsEnabled: boolean;
|
||||
trustProxy: string;
|
||||
}
|
||||
export type SystemSettingsPatch = Partial<SystemSettings>;
|
||||
export interface SystemSettingsResponse {
|
||||
settings: SystemSettings;
|
||||
hasCert: boolean;
|
||||
envOverrides: string[];
|
||||
listeningPort: number;
|
||||
restartRequiredToApply: boolean;
|
||||
}
|
||||
|
||||
// Debug tools (Wave A3).
|
||||
export interface DebugActionParam {
|
||||
name: string;
|
||||
type: string;
|
||||
required: boolean;
|
||||
default?: unknown;
|
||||
desc?: string;
|
||||
values?: (string | number)[];
|
||||
}
|
||||
export interface DebugActionDoc {
|
||||
name: string;
|
||||
aliases: string[];
|
||||
category?: string;
|
||||
summary?: string;
|
||||
returns?: string;
|
||||
readOnly: boolean;
|
||||
params: DebugActionParam[];
|
||||
}
|
||||
export interface DebugInvokeResult {
|
||||
status: string;
|
||||
retcode?: number;
|
||||
data?: unknown;
|
||||
message?: string;
|
||||
wording?: string;
|
||||
}
|
||||
export type DebugStreamMessage =
|
||||
| { kind: 'ready' }
|
||||
| { kind: 'dropped'; count: number }
|
||||
| { kind: 'event'; uin: string; event: Record<string, unknown> }
|
||||
| { kind: 'action'; uin: string; action: string; params: Record<string, unknown>; response: Record<string, unknown>; ms: number };
|
||||
|
||||
// Config backup/restore (Wave A2). The bundle is an opaque JSON object the
|
||||
// server validates; the client never inspects its internals.
|
||||
export type BackupBundle = Record<string, unknown>;
|
||||
export interface BackupImportResult {
|
||||
restored: string[];
|
||||
skipped: string[];
|
||||
snapshotDir: string;
|
||||
restartRequiredToApply: boolean;
|
||||
}
|
||||
|
||||
export interface SystemInfo {
|
||||
hostname: string;
|
||||
platform: string;
|
||||
|
||||
Generated
+5
-39
@@ -81,6 +81,9 @@ importers:
|
||||
typescript:
|
||||
specifier: 'catalog:'
|
||||
version: 6.0.2
|
||||
vitest:
|
||||
specifier: ^4.1.4
|
||||
version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
|
||||
packages/core:
|
||||
dependencies:
|
||||
@@ -4437,7 +4440,7 @@ snapshots:
|
||||
magicast: 0.5.3
|
||||
obug: 2.1.1
|
||||
tinyrainbow: 3.1.0
|
||||
vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
@@ -4453,7 +4456,7 @@ snapshots:
|
||||
obug: 2.1.1
|
||||
std-env: 4.1.0
|
||||
tinyrainbow: 3.1.0
|
||||
vitest: 4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
vitest: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
|
||||
'@vitest/expect@4.1.4':
|
||||
dependencies:
|
||||
@@ -4472,14 +4475,6 @@ snapshots:
|
||||
optionalDependencies:
|
||||
vite: 8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
|
||||
|
||||
'@vitest/mocker@4.1.4(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))':
|
||||
dependencies:
|
||||
'@vitest/spy': 4.1.4
|
||||
estree-walker: 3.0.3
|
||||
magic-string: 0.30.21
|
||||
optionalDependencies:
|
||||
vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
|
||||
|
||||
'@vitest/pretty-format@4.1.4':
|
||||
dependencies:
|
||||
tinyrainbow: 3.1.0
|
||||
@@ -5777,35 +5772,6 @@ snapshots:
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
vitest@4.1.4(@types/node@25.6.0)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)):
|
||||
dependencies:
|
||||
'@vitest/expect': 4.1.4
|
||||
'@vitest/mocker': 4.1.4(vite@8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0))
|
||||
'@vitest/pretty-format': 4.1.4
|
||||
'@vitest/runner': 4.1.4
|
||||
'@vitest/snapshot': 4.1.4
|
||||
'@vitest/spy': 4.1.4
|
||||
'@vitest/utils': 4.1.4
|
||||
es-module-lexer: 2.0.0
|
||||
expect-type: 1.3.0
|
||||
magic-string: 0.30.21
|
||||
obug: 2.1.1
|
||||
pathe: 2.0.3
|
||||
picomatch: 4.0.4
|
||||
std-env: 4.1.0
|
||||
tinybench: 2.9.0
|
||||
tinyexec: 1.1.1
|
||||
tinyglobby: 0.2.16
|
||||
tinyrainbow: 3.1.0
|
||||
vite: 8.0.8(@types/node@25.6.0)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)
|
||||
why-is-node-running: 2.3.0
|
||||
optionalDependencies:
|
||||
'@types/node': 25.6.0
|
||||
'@vitest/coverage-istanbul': 4.1.4(vitest@4.1.4)
|
||||
'@vitest/coverage-v8': 4.1.4(vitest@4.1.4)
|
||||
transitivePeerDependencies:
|
||||
- msw
|
||||
|
||||
vp-runtime-helper@1.0.10:
|
||||
dependencies:
|
||||
'@types/fs-extra': 11.0.4
|
||||
|
||||
Reference in new issue
Block a user