Merge pull request #77 from SnowLuma/dev
chore: promote dev → main (a1f372b)
This commit is contained in:
34 files changed
+1038
-131
No files matched your search
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "snowluma-monorepo",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"description": "SnowLuma monorepo workspace (pnpm)",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/bridge",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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,5 +1,6 @@
|
||||
import { exec } from 'child_process';
|
||||
import net from 'net';
|
||||
import https from 'https';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
@@ -8,6 +9,13 @@ const PORT_RANGE_START = 9210;
|
||||
const PORT_RANGE_END = 9219;
|
||||
const PROBE_TIMEOUT_MS = 1000;
|
||||
const CONNECTION_TIMEOUT_MS = 500;
|
||||
// QQ's Ptlogin quick-login ports plus its main process mean a single
|
||||
// logged-in client surfaces roughly this many processes. When no usable
|
||||
// probe port is found, a count BELOW this implies the target PID is still at
|
||||
// the login screen; AT/ABOVE it the environment is ambiguous (multiple or
|
||||
// unrelated `qq` processes), so we fall through to deep-link probing rather
|
||||
// than guess "logged out".
|
||||
const LOGGED_OUT_PROCESS_COUNT_MAX = 6;
|
||||
|
||||
export interface QqPortLoginInfo {
|
||||
port: number;
|
||||
@@ -42,6 +50,7 @@ function decodeJwt(token: string): JwtPayload | null {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
return new Promise((resolve) => {
|
||||
const client = new net.Socket();
|
||||
@@ -108,6 +117,93 @@ async function probePort(port: number): Promise<QqPortLoginInfo | null> {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** One entry of the Ptlogin `pt_get_uins` JSONP array. Only the fields the
|
||||
* probe reads are modelled; QQ sends more but they're irrelevant here. */
|
||||
interface PtloginUin {
|
||||
uin?: string | number;
|
||||
account?: string | number;
|
||||
nickname?: string;
|
||||
}
|
||||
|
||||
async function fetchPtlogin(port: number): Promise<PtloginUin[]> {
|
||||
return new Promise((resolve) => {
|
||||
const url = `https://127.0.0.1:${port}/pt_get_uins?callback=ptui_getuins_CB&pt_local_tk=0`;
|
||||
|
||||
const req = https.get(
|
||||
url,
|
||||
{
|
||||
headers: {
|
||||
Host: 'localhost.ptlogin2.qq.com',
|
||||
Referer: 'https://xui.ptlogin2.qq.com/',
|
||||
Cookie: 'pt_local_token=0',
|
||||
},
|
||||
rejectUnauthorized: false, // 忽略本地自签证书报错
|
||||
timeout: CONNECTION_TIMEOUT_MS,
|
||||
},
|
||||
(res) => {
|
||||
let text = '';
|
||||
res.on('data', (chunk) => { text += chunk.toString(); });
|
||||
res.on('end', () => {
|
||||
try {
|
||||
// 100% 复刻 Python 切片逻辑:获取两个方括号中间的字符串,再包装成数组
|
||||
const inner = text.split('[')[1].split(']')[0];
|
||||
const data = JSON.parse('[' + inner + ']') as PtloginUin[];
|
||||
resolve(data);
|
||||
} catch {
|
||||
resolve([]);
|
||||
}
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
req.on('error', () => resolve([]));
|
||||
req.on('timeout', () => {
|
||||
req.destroy();
|
||||
resolve([]);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function tryPtloginMethod(port: number): Promise<QqPortLoginInfo | 'fallback'> {
|
||||
// 抽象的 QQNT
|
||||
const res1 = await fetchPtlogin(port);
|
||||
const res2 = await fetchPtlogin(port);
|
||||
|
||||
const target = res1.length < res2.length ? res1 : res2;
|
||||
|
||||
if (target.length === 1) {
|
||||
const account = target[0];
|
||||
return {
|
||||
port,
|
||||
uin: String(account.uin || account.account || ''),
|
||||
nickName: account.nickname || '',
|
||||
loggedIn: true,
|
||||
};
|
||||
}
|
||||
|
||||
// Any non-1 result — the 2+0 alternation, both-2, both-empty, etc. — is
|
||||
// inconclusive; hand off to the deep-link / process-count fallback.
|
||||
return 'fallback';
|
||||
}
|
||||
|
||||
|
||||
async function getQqProcessCount(): Promise<number> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
const { stdout } = await execAsync('tasklist /fi "imagename eq QQ.exe" /nh');
|
||||
return stdout.toLowerCase().split('\n').filter(line => line.includes('qq.exe')).length;
|
||||
} else {
|
||||
const { stdout } = await execAsync('pgrep -c qq');
|
||||
return parseInt(stdout.trim(), 10) || 0;
|
||||
}
|
||||
} catch {
|
||||
// On failure report the ambiguous threshold so we never falsely
|
||||
// conclude "logged out".
|
||||
return LOGGED_OUT_PROCESS_COUNT_MAX;
|
||||
}
|
||||
}
|
||||
|
||||
async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
try {
|
||||
if (process.platform === 'win32') {
|
||||
@@ -119,13 +215,11 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
if (parts.length < 5) continue;
|
||||
const owningPid = parts[parts.length - 1];
|
||||
if (owningPid !== String(pid)) continue;
|
||||
|
||||
const localAddr = parts[1];
|
||||
const portMatch = localAddr.match(/:(\d+)$/);
|
||||
if (!portMatch) continue;
|
||||
const port = Number(portMatch[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
ports.add(Number(portMatch[1]));
|
||||
}
|
||||
return Array.from(ports);
|
||||
} else {
|
||||
@@ -135,10 +229,7 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
for (const line of lines) {
|
||||
const match = line.match(/:(\d+)\s/);
|
||||
if (match) {
|
||||
const port = Number(match[1]);
|
||||
if (port >= PORT_RANGE_START && port <= PORT_RANGE_END) {
|
||||
ports.add(port);
|
||||
}
|
||||
ports.add(Number(match[1]));
|
||||
}
|
||||
}
|
||||
return Array.from(ports);
|
||||
@@ -148,18 +239,41 @@ async function getProcessPorts(pid: number): Promise<number[]> {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
export async function probeQqLoginInfo(pid: number): Promise<QqPortLoginInfo | null> {
|
||||
const ports = await getProcessPorts(pid);
|
||||
|
||||
if (ports.length === 0) {
|
||||
for (let port = PORT_RANGE_START; port <= PORT_RANGE_END; port++) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return { port: 0, uin: '', loggedIn: false };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
for (const port of ports) {
|
||||
const PT_PORTS = [4301, 4303, 4305, 4307, 4309];
|
||||
const matchedPtPorts = ports.filter(p => PT_PORTS.includes(p));
|
||||
|
||||
if (matchedPtPorts.length > 0) {
|
||||
for (const port of matchedPtPorts) {
|
||||
const ptResult = await tryPtloginMethod(port);
|
||||
if (ptResult !== 'fallback') {
|
||||
return ptResult;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
const totalPids = await getQqProcessCount();
|
||||
if (totalPids < LOGGED_OUT_PROCESS_COUNT_MAX) {
|
||||
return {
|
||||
port: ports[0] || 0,
|
||||
uin: '',
|
||||
loggedIn: false,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const deepLinkPorts = ports.filter(p => p >= PORT_RANGE_START && p <= PORT_RANGE_END);
|
||||
for (const port of deepLinkPorts) {
|
||||
const info = await probePort(port);
|
||||
if (info) return info;
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/common",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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).",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/core",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -35,6 +35,43 @@ function commonElem(elem: any): { serviceType: number; businessType: number; pbE
|
||||
return elem.commonElem;
|
||||
}
|
||||
|
||||
function inflatePrefixedPayload(data: Uint8Array): string {
|
||||
expect(data[0]).toBe(0x01);
|
||||
return inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
|
||||
}
|
||||
|
||||
describe('element-builder / rich card encoding', () => {
|
||||
it('encodes json segments as deflated LightApp payloads and preserves non-ASCII text', async () => {
|
||||
const card = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'music',
|
||||
prompt: '[音乐]起风了',
|
||||
meta: { music: { title: '起风了', desc: '买辣椒也用券' } },
|
||||
});
|
||||
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'json', text: card } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
|
||||
expect(elem.lightApp).toBeDefined();
|
||||
expect((elem as any).richMsg).toBeUndefined();
|
||||
expect(inflatePrefixedPayload(elem.lightApp!.data!)).toBe(card);
|
||||
});
|
||||
|
||||
it('encodes xml richMsg payloads by UTF-8 bytes, not JavaScript string length', async () => {
|
||||
const xml = '<msg serviceID="35" brief="[分享]中文卡片"></msg>';
|
||||
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'xml', text: xml, subType: 35 } as any],
|
||||
{ bridge: fakeBridge, groupId: 12345 },
|
||||
);
|
||||
|
||||
expect(elem.richMsg?.serviceId).toBe(35);
|
||||
expect(inflatePrefixedPayload(elem.richMsg!.template1!)).toBe(xml);
|
||||
});
|
||||
});
|
||||
|
||||
describe('element-builder / commonElem.businessType per scene', () => {
|
||||
describe('image', () => {
|
||||
it('c2c → businessType 10', async () => {
|
||||
@@ -129,10 +166,7 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
|
||||
// the outer's LongMsgResult — without uniseq the QQ-NT client has
|
||||
// no way to walk the tree and has to re-fetch each inner resId.
|
||||
function decodeLightApp(elem: any): unknown {
|
||||
const data: Uint8Array = elem.lightApp.data;
|
||||
expect(data[0]).toBe(0x01); // deflate prefix
|
||||
const inflated = inflateSync(Buffer.from(data.subarray(1))).toString('utf8');
|
||||
return JSON.parse(inflated);
|
||||
return JSON.parse(inflatePrefixedPayload(elem.lightApp.data));
|
||||
}
|
||||
|
||||
it('emits a lightApp.data blob with prefix=0x01 (deflated JSON, not XML/serviceID=35)', async () => {
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// highway-client.uploadHighwayHttp 的连接生命周期测试。
|
||||
//
|
||||
// 回归覆盖:当上传数据 > HIGHWAY_BLOCK_SIZE (1 MiB) 时,旧实现会复用
|
||||
// 同一个 TCP socket 在 keep-alive 模式下连续 POST,但 QQ highway 的
|
||||
// 边缘节点经常在第一次响应后立刻 FIN 关闭,导致第二次 POST 报
|
||||
// `connection closed before response`。用户上报的 1.19 MB 图片
|
||||
// (onebot retcode=1200)就是这个分支。
|
||||
//
|
||||
// 修复方案:每个 chunk 独立建一个新的 TCP 连接。本测试通过 mock
|
||||
// `net.createConnection` 计数建连次数,断言每个 chunk 一连接的不变量。
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import { EventEmitter } from 'events';
|
||||
|
||||
// highway-client 解析响应只关心 errorCode === 0 —— 一个完全空的
|
||||
// RespDataHighwayHead protobuf 体(0 字节)会被解为 ,errorCode
|
||||
// 是 undefined,走 falsy 通过分支。
|
||||
//
|
||||
// HTTP body 是 highway frame:
|
||||
// 0x28 | head_len(BE32) | body_len(BE32) | head | body | 0x29
|
||||
function buildEmptyHighwayResponseFrame(): Buffer {
|
||||
const frame = Buffer.alloc(10);
|
||||
frame[0] = 0x28;
|
||||
frame.writeUInt32BE(0, 1); // head_len
|
||||
frame.writeUInt32BE(0, 5); // body_len
|
||||
frame[9] = 0x29;
|
||||
return frame;
|
||||
}
|
||||
|
||||
function buildHttpResponse(frameBody: Buffer): Buffer {
|
||||
const headers = [
|
||||
'HTTP/1.1 200 OK',
|
||||
`Content-Length: ${frameBody.length}`,
|
||||
'Connection: close',
|
||||
'',
|
||||
'',
|
||||
].join('\r\n');
|
||||
return Buffer.concat([Buffer.from(headers, 'ascii'), frameBody]);
|
||||
}
|
||||
|
||||
// FakeSocket 模拟 net.Socket 的最小子集。highway-client 用到:
|
||||
// - 'data' / 'error' / 'close' 事件
|
||||
// - .write(data, cb) cb 会被 socketWrite 等待
|
||||
// - .destroy()
|
||||
// - .setTimeout / .once / .removeListener (继承自 EventEmitter)
|
||||
class FakeSocket extends EventEmitter {
|
||||
destroyed = false;
|
||||
// 每个 POST = 2 次 write(HTTP header + body)。第二次 write 落地后
|
||||
// 异步回放响应并立刻 close —— 复现 QQ highway 真实行为:响应一发完
|
||||
// 就 FIN,旧实现的下一次 POST 必然撞上已关闭的 socket。
|
||||
private writeCount = 0;
|
||||
private response: Buffer;
|
||||
|
||||
constructor(response: Buffer) {
|
||||
super();
|
||||
this.response = response;
|
||||
}
|
||||
|
||||
setTimeout(_ms: number) { /* no-op */ }
|
||||
|
||||
write(_data: unknown, cb?: (err?: Error) => void): boolean {
|
||||
this.writeCount += 1;
|
||||
if (this.writeCount === 2) {
|
||||
setImmediate(() => {
|
||||
this.emit('data', this.response);
|
||||
this.emit('close');
|
||||
});
|
||||
}
|
||||
if (cb) cb();
|
||||
return true;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
}
|
||||
}
|
||||
|
||||
// vitest 把 vi.mock 工厂 hoist 到文件顶部,所以工厂里不能引用普通的
|
||||
// 顶层 const —— 那会触发 "Cannot access X before initialization"。
|
||||
// 用 vi.hoisted 让这两个值跟着 mock 一起被 hoist。
|
||||
const { createdSockets, createConnectionMock } = vi.hoisted(() => ({
|
||||
createdSockets: [] as FakeSocket[],
|
||||
createConnectionMock: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('net', () => ({
|
||||
default: { createConnection: createConnectionMock },
|
||||
createConnection: createConnectionMock,
|
||||
}));
|
||||
|
||||
import { uploadHighwayHttp, type HighwaySession } from '@snowluma/protocol/highway';
|
||||
import type { BridgeContext } from '@snowluma/protocol/bridge-context';
|
||||
|
||||
const HIGHWAY_BLOCK_SIZE = 1024 * 1024;
|
||||
|
||||
function makeBridge(): BridgeContext {
|
||||
return {
|
||||
identity: { uin: '10001' } as unknown,
|
||||
} as unknown as BridgeContext;
|
||||
}
|
||||
|
||||
function makeSession(): HighwaySession {
|
||||
return {
|
||||
sigSession: new Uint8Array([0xAA]),
|
||||
sessionKey: new Uint8Array([0xBB]),
|
||||
host: '127.0.0.1',
|
||||
port: 80,
|
||||
};
|
||||
}
|
||||
|
||||
describe('uploadHighwayHttp connection lifecycle', () => {
|
||||
beforeEach(() => {
|
||||
createdSockets.length = 0;
|
||||
createConnectionMock.mockReset();
|
||||
createConnectionMock.mockImplementation((_opts: unknown, listener?: () => void) => {
|
||||
const sock = new FakeSocket(buildHttpResponse(buildEmptyHighwayResponseFrame()));
|
||||
createdSockets.push(sock);
|
||||
// net.createConnection 在握手成功后调用 listener。同步触发即可,
|
||||
// tcpConnect 的 Promise 会立刻 resolve。
|
||||
if (listener) setImmediate(listener);
|
||||
return sock as unknown as ReturnType<typeof createConnectionMock>;
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('uses a single TCP connection for a sub-block payload', async () => {
|
||||
// 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。
|
||||
const bytes = new Uint8Array(512 * 1024);
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(1);
|
||||
expect(createdSockets[0]!.destroyed).toBe(true);
|
||||
});
|
||||
|
||||
it('uses a fresh TCP connection per chunk for multi-block payloads', async () => {
|
||||
// 1.5 MiB → ceil(1.5) = 2 chunks。这正是用户上报的 1.19 MB 图片
|
||||
// 触发的代码路径:旧实现复用 socket 时第二次 POST 撞上 keep-alive
|
||||
// 关闭,新实现必须为每个 chunk 各开一个 socket。
|
||||
const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1003, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(2);
|
||||
expect(createdSockets).toHaveLength(2);
|
||||
for (const sock of createdSockets) {
|
||||
expect(sock.destroyed).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('opens N connections for N chunks (3 chunks here)', async () => {
|
||||
const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE));
|
||||
await uploadHighwayHttp(
|
||||
makeBridge(), makeSession(), 1004, bytes, new Uint8Array(16), new Uint8Array(0),
|
||||
);
|
||||
expect(createConnectionMock).toHaveBeenCalledTimes(3);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/onebot",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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>'`.",
|
||||
|
||||
@@ -9,6 +9,7 @@ import type {
|
||||
MessageFormat,
|
||||
OneBotConfig,
|
||||
OneBotNetworks,
|
||||
StatusCommandConfig,
|
||||
WsClientNetwork,
|
||||
WsRole,
|
||||
WsServerNetwork,
|
||||
@@ -20,6 +21,14 @@ const CONFIG_DIR = 'config';
|
||||
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
|
||||
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
|
||||
|
||||
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 };
|
||||
/** Upper bound on the `#sl` reply cooldown — a year is effectively "off but sane". */
|
||||
const STATUS_COMMAND_COOLDOWN_MAX = 31_536_000;
|
||||
|
||||
function makeDefaultStatusCommand(): StatusCommandConfig {
|
||||
return { ...DEFAULT_STATUS_COMMAND };
|
||||
}
|
||||
|
||||
export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
return {
|
||||
networks: {
|
||||
@@ -46,6 +55,7 @@ export function makeDefaultOneBotConfig(): OneBotConfig {
|
||||
wsClients: [],
|
||||
},
|
||||
musicSignUrl: '',
|
||||
statusCommand: makeDefaultStatusCommand(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -98,6 +108,11 @@ function toJsonObject(config: OneBotConfig): JsonObject {
|
||||
wsClients: nets.wsClients.map(wsClientToJson),
|
||||
},
|
||||
musicSignUrl: config.musicSignUrl ?? '',
|
||||
statusCommand: {
|
||||
enabled: config.statusCommand.enabled,
|
||||
swallow: config.statusCommand.swallow,
|
||||
cooldownSeconds: config.statusCommand.cooldownSeconds,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -181,7 +196,26 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
|
||||
}
|
||||
|
||||
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
|
||||
return { networks, musicSignUrl };
|
||||
return { networks, musicSignUrl, statusCommand: parseStatusCommand(sources) };
|
||||
}
|
||||
|
||||
/** Last-write-wins merge of `statusCommand` across config sources, with
|
||||
* defaults filled and the cooldown clamped to a sane non-negative range. */
|
||||
function parseStatusCommand(sources: JsonObject[]): StatusCommandConfig {
|
||||
const out = makeDefaultStatusCommand();
|
||||
for (const src of sources) {
|
||||
const raw = src.statusCommand;
|
||||
if (!isObject(raw)) continue;
|
||||
if (typeof raw.enabled === 'boolean') out.enabled = raw.enabled;
|
||||
if (typeof raw.swallow === 'boolean') out.swallow = raw.swallow;
|
||||
if (raw.cooldownSeconds !== undefined) {
|
||||
out.cooldownSeconds = Math.min(
|
||||
STATUS_COMMAND_COOLDOWN_MAX,
|
||||
asNumber(raw.cooldownSeconds, DEFAULT_STATUS_COMMAND.cooldownSeconds),
|
||||
);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function collectByName<T extends { name: string }>(
|
||||
|
||||
@@ -43,7 +43,18 @@ export class RKeyCache {
|
||||
const url = element.imageUrl ?? '';
|
||||
if (!urlNeedsRKey(url)) return url;
|
||||
|
||||
const rkey = await this.findRKey(bridge, isGroup);
|
||||
// The rkey scene must follow the IMAGE's own upload context, not the
|
||||
// message currently carrying it. A c2c image forwarded into a group
|
||||
// keeps its original c2c fileid/appid (1406); signing it with the
|
||||
// group rkey just because the forward node looks like a group message
|
||||
// yields `invalid rkey` on download. So derive the scene from the
|
||||
// appid baked into the URL, and only fall back to `isGroup` when the
|
||||
// URL carries no recognised appid (legacy gchat / unknown shapes).
|
||||
// Mirrors NapCat's getImageUrlFromParsedUrl (appid 1406 → private,
|
||||
// 1407 → group).
|
||||
const primaryType = imageRKeyTypeFromUrl(url)
|
||||
?? (isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE);
|
||||
const rkey = await this.findRKeyForType(bridge, primaryType);
|
||||
if (!rkey) return url;
|
||||
|
||||
const cleanRKey = stripRKeyPrefix(rkey);
|
||||
@@ -90,11 +101,6 @@ export class RKeyCache {
|
||||
}
|
||||
}
|
||||
|
||||
private findRKey(bridge: BridgeInterface, isGroup: boolean): Promise<string | null> {
|
||||
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
|
||||
return this.findRKeyForType(bridge, primaryType);
|
||||
}
|
||||
|
||||
/** Pull a still-valid rkey out of the cache, or null if missing/expiring. */
|
||||
private findInCache(primaryType: number): string | null {
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
@@ -153,6 +159,23 @@ export class RKeyCache {
|
||||
}
|
||||
}
|
||||
|
||||
// QQ-NT download appids embedded in the image URL query string. The scene
|
||||
// they encode is a property of the image (where it was uploaded), so they
|
||||
// outrank the carrying message's group/private context — see resolveImageUrl.
|
||||
const APPID_PRIVATE_IMAGE = '1406';
|
||||
const APPID_GROUP_IMAGE = '1407';
|
||||
|
||||
/** Map the `appid` baked into an NT download URL to its rkey type. Returns
|
||||
* null when the URL carries no recognised appid, leaving the caller to fall
|
||||
* back to the message's group/private context. */
|
||||
function imageRKeyTypeFromUrl(url: string): number | null {
|
||||
const match = url.match(/[?&]appid=(\d+)/);
|
||||
if (!match) return null;
|
||||
if (match[1] === APPID_PRIVATE_IMAGE) return PRIVATE_IMAGE_RKEY_TYPE;
|
||||
if (match[1] === APPID_GROUP_IMAGE) return GROUP_IMAGE_RKEY_TYPE;
|
||||
return null;
|
||||
}
|
||||
|
||||
function urlNeedsRKey(url: string): boolean {
|
||||
if (!url || url.includes('rkey=')) return false;
|
||||
if (url.includes('gchat.qpic.cn')) return false;
|
||||
|
||||
@@ -12,6 +12,8 @@ import { MediaStore } from './media-store';
|
||||
import { MediaUrlResolver } from './media-url-resolver';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
|
||||
import { MessageStore } from './message-store';
|
||||
import { sendGroupMessage, sendPrivateMessage } from './modules/message-actions';
|
||||
import { buildStatusText, matchesStatusCommand, statusCooldownElapsed } from './modules/status-command';
|
||||
import {
|
||||
HttpPostAdapter,
|
||||
HttpServerAdapter,
|
||||
@@ -37,6 +39,11 @@ export class OneBotInstance {
|
||||
private readonly reactionStore: ReactionStore;
|
||||
private readonly networkManager: OneBotNetworkManager;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
/** Process-uptime baseline for the `#sl` status reply. */
|
||||
private readonly startedAt = Date.now();
|
||||
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
|
||||
private readonly statusCommandCooldown = new Map<string, number>();
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
@@ -90,6 +97,7 @@ export class OneBotInstance {
|
||||
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
|
||||
dispatchEvent: (event) => this.dispatchEvent(event),
|
||||
};
|
||||
this.ctx = ctx;
|
||||
|
||||
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
|
||||
this.networkManager = new OneBotNetworkManager();
|
||||
@@ -104,6 +112,9 @@ export class OneBotInstance {
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): void {
|
||||
// Keep the shared context's config in sync so live readers (e.g. the
|
||||
// `#sl` handler reading `statusCommand`) pick up edits without a restart.
|
||||
this.ctx.config = config;
|
||||
void this.applyConfigDiff(config).catch((err) => {
|
||||
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
@@ -145,11 +156,53 @@ export class OneBotInstance {
|
||||
private dispatchEvent(event: JsonObject): void {
|
||||
this.cacheMessageEvent(event);
|
||||
this.logReceivedMessage(event);
|
||||
// Built-in `#sl`: always cache + log first (a swallowed `#sl` is still
|
||||
// observable locally); only forwarding to downstream adapters is gated.
|
||||
if (this.handleStatusCommand(event)) return;
|
||||
void this.networkManager.emitEvent(event).catch((err) => {
|
||||
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in `#sl` status command. Returns `true` when the event matched AND
|
||||
* `swallow` is configured — the caller then skips `emitEvent` so downstream
|
||||
* adapters never see it. The reply itself is fired async and rate-limited
|
||||
* per conversation; matching and replying are independent of swallowing.
|
||||
*/
|
||||
private handleStatusCommand(event: JsonObject): boolean {
|
||||
const cfg = this.ctx.config.statusCommand;
|
||||
if (!cfg.enabled) return false;
|
||||
const postType = event.post_type;
|
||||
if (postType !== 'message' && postType !== 'message_sent') return false;
|
||||
if (!matchesStatusCommand(event.message)) return false;
|
||||
|
||||
const isGroup = event.message_type === 'group';
|
||||
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
|
||||
if (sessionId === 0) return cfg.swallow;
|
||||
|
||||
const key = `${isGroup ? 'g' : 'p'}:${sessionId}`;
|
||||
const now = Date.now();
|
||||
if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) {
|
||||
this.statusCommandCooldown.set(key, now);
|
||||
void this.replyStatus(isGroup, sessionId).catch((err) => {
|
||||
this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err));
|
||||
});
|
||||
}
|
||||
return cfg.swallow;
|
||||
}
|
||||
|
||||
private async replyStatus(isGroup: boolean, sessionId: number): Promise<void> {
|
||||
const text = buildStatusText({
|
||||
version: typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev',
|
||||
platform: process.platform,
|
||||
arch: process.arch,
|
||||
uptimeMs: Date.now() - this.startedAt,
|
||||
});
|
||||
if (isGroup) await sendGroupMessage(this.ctx, sessionId, text, true);
|
||||
else await sendPrivateMessage(this.ctx, sessionId, text, true);
|
||||
}
|
||||
|
||||
private buildNetworkContext(): NetworkAdapterContext {
|
||||
return {
|
||||
uin: this.uin,
|
||||
|
||||
@@ -675,7 +675,16 @@ export async function getForwardMessage(
|
||||
for (const node of nodes) {
|
||||
const isGroup = node.messageType === 'group' || (node.groupId !== undefined && node.groupId > 0);
|
||||
const sessionId = isGroup ? (node.groupId ?? 0) : node.userUin;
|
||||
const segments = await elementsToOneBotSegments(node.elements, isGroup, sessionId);
|
||||
// Route forward nodes through the SAME resolver-equipped conversion the
|
||||
// normal receive path uses (to-message.ts). Without the image/media URL
|
||||
// resolvers the segments come back with raw, rkey-less download URLs —
|
||||
// exactly issue #74 (`/get_forward_msg` image url 缺少 rkey). Image rkey
|
||||
// re-signing is scene-aware via the appid in the URL (see instance-rkey).
|
||||
const segments = await elementsToOneBotSegments(
|
||||
node.elements, isGroup, sessionId,
|
||||
ref.converterCtx.imageUrlResolver,
|
||||
ref.converterCtx.mediaUrlResolver,
|
||||
);
|
||||
|
||||
const sender: JsonObject = {
|
||||
user_id: node.userUin,
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
import type { JsonObject, JsonValue } from '../types';
|
||||
|
||||
/**
|
||||
* Hardcoded trigger for the built-in status command — exact match,
|
||||
* case-insensitive, after trimming. Intentionally NOT configurable: the
|
||||
* `statusCommand.enabled` toggle is the only knob (the gate is on/off, not
|
||||
* the word).
|
||||
*/
|
||||
export const STATUS_COMMAND_TRIGGER = '#sl';
|
||||
|
||||
/**
|
||||
* True iff `message` is exactly the trigger: a single `text` segment (or a
|
||||
* bare string for string-format adapters) whose trimmed, lowercased content
|
||||
* equals {@link STATUS_COMMAND_TRIGGER}.
|
||||
*
|
||||
* Reads the segment array rather than `raw_message` to avoid CQ-encoding
|
||||
* ambiguity, and rejects mixed-segment messages (`#sl` + image/at/reply) so
|
||||
* only a pure `#sl` triggers — no `startsWith`, so `#slogan` never matches.
|
||||
*/
|
||||
export function matchesStatusCommand(message: JsonValue | undefined): boolean {
|
||||
if (typeof message === 'string') {
|
||||
return normalize(message) === STATUS_COMMAND_TRIGGER;
|
||||
}
|
||||
if (!Array.isArray(message) || message.length !== 1) return false;
|
||||
const seg = message[0];
|
||||
if (!isObject(seg) || seg.type !== 'text') return false;
|
||||
const data = isObject(seg.data) ? seg.data : null;
|
||||
const text = data && typeof data.text === 'string' ? data.text : '';
|
||||
return normalize(text) === STATUS_COMMAND_TRIGGER;
|
||||
}
|
||||
|
||||
function normalize(s: string): string {
|
||||
return s.trim().toLowerCase();
|
||||
}
|
||||
|
||||
function isObject(value: unknown): value is JsonObject {
|
||||
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a reply is allowed now given the last reply time + cooldown.
|
||||
* `cooldownSeconds <= 0` disables the cooldown entirely.
|
||||
*/
|
||||
export function statusCooldownElapsed(
|
||||
lastRepliedAtMs: number | undefined,
|
||||
nowMs: number,
|
||||
cooldownSeconds: number,
|
||||
): boolean {
|
||||
if (lastRepliedAtMs === undefined) return true;
|
||||
if (cooldownSeconds <= 0) return true;
|
||||
return nowMs - lastRepliedAtMs >= cooldownSeconds * 1000;
|
||||
}
|
||||
|
||||
export interface StatusInfo {
|
||||
version: string;
|
||||
platform: string;
|
||||
arch: string;
|
||||
uptimeMs: number;
|
||||
}
|
||||
|
||||
/** Render the public-safe `#sl` reply: version + platform/arch + uptime. */
|
||||
export function buildStatusText(info: StatusInfo): string {
|
||||
return [
|
||||
'SnowLuma 状态',
|
||||
`版本: ${info.version}`,
|
||||
`平台: ${info.platform}-${info.arch}`,
|
||||
`运行时长: ${formatUptime(info.uptimeMs)}`,
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** Human-readable uptime (zh-CN), dropping leading zero units. */
|
||||
export function formatUptime(ms: number): string {
|
||||
const totalSec = Math.max(0, Math.floor(ms / 1000));
|
||||
const days = Math.floor(totalSec / 86400);
|
||||
const hours = Math.floor((totalSec % 86400) / 3600);
|
||||
const minutes = Math.floor((totalSec % 3600) / 60);
|
||||
const seconds = totalSec % 60;
|
||||
if (days > 0) return `${days}天 ${hours}小时 ${minutes}分钟`;
|
||||
if (hours > 0) return `${hours}小时 ${minutes}分钟`;
|
||||
if (minutes > 0) return `${minutes}分钟 ${seconds}秒`;
|
||||
return `${seconds}秒`;
|
||||
}
|
||||
@@ -63,11 +63,29 @@ export interface OneBotNetworks {
|
||||
wsClients: WsClientNetwork[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Built-in `#sl` status command. The trigger word is hardcoded (`#sl`,
|
||||
* exact match, case-insensitive); only these toggles are configurable.
|
||||
*/
|
||||
export interface StatusCommandConfig {
|
||||
/** Master on/off. Default `true` — built-in, but freely disableable. */
|
||||
enabled: boolean;
|
||||
/**
|
||||
* When `true`, a matched `#sl` is NOT forwarded to downstream adapters
|
||||
* (it is still cached, logged, and replied to). Default `false` (pass-through).
|
||||
*/
|
||||
swallow: boolean;
|
||||
/** Per-conversation reply cooldown in seconds. `0` disables it. Default `5`. */
|
||||
cooldownSeconds: number;
|
||||
}
|
||||
|
||||
/** Per-UIN OneBot configuration. */
|
||||
export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
/** Music card signing service URL (optional). */
|
||||
musicSignUrl?: string;
|
||||
/** Built-in `#sl` status command settings. Always present after normalization. */
|
||||
statusCommand: StatusCommandConfig;
|
||||
}
|
||||
|
||||
export interface MessageMeta {
|
||||
|
||||
@@ -25,6 +25,7 @@ describe('makeDefaultOneBotConfig', () => {
|
||||
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
|
||||
expect(config.networks.wsClients).toEqual([]);
|
||||
expect(config.musicSignUrl).toBe('');
|
||||
expect(config.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,6 +58,26 @@ describe('loadOneBotConfig', () => {
|
||||
// Legacy keys must not appear in the persisted file.
|
||||
expect(onDisk.httpServers).toBeUndefined();
|
||||
expect(onDisk.wsServers).toBeUndefined();
|
||||
// statusCommand is materialised with defaults on a fresh install.
|
||||
expect(onDisk.statusCommand).toEqual({ enabled: true, swallow: false, cooldownSeconds: 5 });
|
||||
});
|
||||
|
||||
it('fills statusCommand defaults and clamps a negative cooldown', () => {
|
||||
const uin = '10042';
|
||||
const dir = path.join(tempDir, 'config');
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(dir, `onebot_${uin}.json`),
|
||||
JSON.stringify({
|
||||
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
|
||||
statusCommand: { swallow: true, cooldownSeconds: -3 },
|
||||
}),
|
||||
);
|
||||
|
||||
const config = loadOneBotConfig(uin);
|
||||
expect(config.statusCommand.enabled).toBe(true); // default filled (absent in file)
|
||||
expect(config.statusCommand.swallow).toBe(true); // taken from file
|
||||
expect(config.statusCommand.cooldownSeconds).toBe(0); // negative clamped to 0
|
||||
});
|
||||
|
||||
it('migrates legacy per-type arrays into networks groups', () => {
|
||||
|
||||
@@ -3,7 +3,9 @@ import { RKeyCache } from '../src/instance-rkey';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
|
||||
// The screenshot URL: a raw QQ-NT multimedia download link with no rkey yet.
|
||||
// appid 1407 = group image, 1406 = private/c2c image (see instance-rkey).
|
||||
const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC';
|
||||
const NT_PRIVATE_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1406&fileid=XYZ';
|
||||
const GROUP_IMAGE_TYPE = 20;
|
||||
const PRIVATE_IMAGE_TYPE = 10;
|
||||
|
||||
@@ -20,10 +22,21 @@ function freshGroupRkey(value = 'GROUPKEY') {
|
||||
return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }];
|
||||
}
|
||||
|
||||
function freshBothRkeys() {
|
||||
return [
|
||||
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
];
|
||||
}
|
||||
|
||||
function imageEl(): MessageElement {
|
||||
return { type: 'image', imageUrl: NT_IMAGE_URL };
|
||||
}
|
||||
|
||||
function privateImageEl(): MessageElement {
|
||||
return { type: 'image', imageUrl: NT_PRIVATE_IMAGE_URL };
|
||||
}
|
||||
|
||||
describe('RKeyCache.resolveImageUrl', () => {
|
||||
it('awaits a refresh on a cold cache and appends the rkey', async () => {
|
||||
const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey());
|
||||
@@ -69,16 +82,46 @@ describe('RKeyCache.resolveImageUrl', () => {
|
||||
expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('uses the private rkey type for c2c images', async () => {
|
||||
const { bridge } = makeBridge(async () => [
|
||||
{ rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
{ rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 },
|
||||
]);
|
||||
it('uses the private rkey type for c2c images (appid 1406)', async () => {
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), false);
|
||||
|
||||
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
});
|
||||
|
||||
// The scene follows the image's own appid, not the carrying message — the
|
||||
// crux of `/get_forward_msg` rkey correctness (issue #74): a c2c image
|
||||
// forwarded into a group must still be signed with the private rkey.
|
||||
it('signs an appid-1406 image with the private rkey even when isGroup is true', async () => {
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, privateImageEl(), true);
|
||||
|
||||
expect(url).toBe(`${NT_PRIVATE_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
});
|
||||
|
||||
it('signs an appid-1407 image with the group rkey even when isGroup is false', async () => {
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(bridge as never, imageEl(), false);
|
||||
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=PRIVATEKEY`);
|
||||
expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`);
|
||||
});
|
||||
|
||||
it('falls back to the isGroup scene when the URL carries no appid', async () => {
|
||||
const noAppidUrl = 'https://multimedia.nt.qq.com.cn/download?fileid=NOAPPID';
|
||||
const { bridge } = makeBridge(async () => freshBothRkeys());
|
||||
const cache = new RKeyCache();
|
||||
|
||||
const url = await cache.resolveImageUrl(
|
||||
bridge as never, { type: 'image', imageUrl: noAppidUrl }, true,
|
||||
);
|
||||
|
||||
expect(url).toBe(`${noAppidUrl}&rkey=GROUPKEY`);
|
||||
});
|
||||
|
||||
it('leaves non-NT URLs untouched and never fetches', async () => {
|
||||
|
||||
@@ -413,6 +413,33 @@ describe('parseMessage', () => {
|
||||
const parsed = JSON.parse(result[0].text!);
|
||||
expect(parsed.meta.contact.type).toBe('group');
|
||||
});
|
||||
|
||||
it('parses signed music cards and buildSendElems preserves non-ASCII JSON', async () => {
|
||||
const card = JSON.stringify({
|
||||
app: 'com.tencent.structmsg',
|
||||
view: 'music',
|
||||
prompt: '[音乐]风中有朵雨做的云',
|
||||
meta: { music: { title: '风中有朵雨做的云', desc: '孟庭苇' } },
|
||||
});
|
||||
vi.stubGlobal('fetch', vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => card,
|
||||
})));
|
||||
|
||||
try {
|
||||
const result = await parseMessage(
|
||||
[{ type: 'music', data: { type: '163', id: '123456' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(result).toEqual([{ type: 'json', text: card }]);
|
||||
|
||||
const protoElems = await buildSendElems(result);
|
||||
expect(protoElems).toHaveLength(1);
|
||||
expect(protoElems[0].lightApp?.data?.[0]).toBe(0x01);
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('single segment object', () => {
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
STATUS_COMMAND_TRIGGER,
|
||||
buildStatusText,
|
||||
formatUptime,
|
||||
matchesStatusCommand,
|
||||
statusCooldownElapsed,
|
||||
} from '../src/modules/status-command';
|
||||
import type { JsonValue } from '../src/types';
|
||||
|
||||
function textSeg(text: string): JsonValue {
|
||||
return [{ type: 'text', data: { text } }] as unknown as JsonValue;
|
||||
}
|
||||
|
||||
describe('matchesStatusCommand', () => {
|
||||
it('matches a single text segment equal to the trigger', () => {
|
||||
expect(matchesStatusCommand(textSeg('#sl'))).toBe(true);
|
||||
});
|
||||
|
||||
it('is case-insensitive and trims surrounding whitespace', () => {
|
||||
expect(matchesStatusCommand(textSeg('#SL'))).toBe(true);
|
||||
expect(matchesStatusCommand(textSeg(' #Sl '))).toBe(true);
|
||||
});
|
||||
|
||||
it('matches a bare string (string-format adapters)', () => {
|
||||
expect(matchesStatusCommand('#sl' as unknown as JsonValue)).toBe(true);
|
||||
expect(matchesStatusCommand(' #SL ' as unknown as JsonValue)).toBe(true);
|
||||
});
|
||||
|
||||
it('does NOT match as a prefix — only exact', () => {
|
||||
expect(matchesStatusCommand(textSeg('#slogan'))).toBe(false);
|
||||
expect(matchesStatusCommand(textSeg('#sl help'))).toBe(false);
|
||||
expect(matchesStatusCommand(textSeg('你好 #sl'))).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects mixed-segment messages', () => {
|
||||
const mixed = [
|
||||
{ type: 'text', data: { text: '#sl' } },
|
||||
{ type: 'image', data: { file: 'x.png' } },
|
||||
] as unknown as JsonValue;
|
||||
expect(matchesStatusCommand(mixed)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects non-text leading segments and empty/garbage input', () => {
|
||||
expect(matchesStatusCommand([{ type: 'at', data: { qq: '1' } }] as unknown as JsonValue)).toBe(false);
|
||||
expect(matchesStatusCommand([] as unknown as JsonValue)).toBe(false);
|
||||
expect(matchesStatusCommand(undefined)).toBe(false);
|
||||
expect(matchesStatusCommand(123 as unknown as JsonValue)).toBe(false);
|
||||
});
|
||||
|
||||
it('exposes the hardcoded trigger', () => {
|
||||
expect(STATUS_COMMAND_TRIGGER).toBe('#sl');
|
||||
});
|
||||
});
|
||||
|
||||
describe('statusCooldownElapsed', () => {
|
||||
it('allows the first reply (no prior timestamp)', () => {
|
||||
expect(statusCooldownElapsed(undefined, 1_000, 5)).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores the cooldown when set to 0 or negative', () => {
|
||||
expect(statusCooldownElapsed(1_000, 1_500, 0)).toBe(true);
|
||||
expect(statusCooldownElapsed(1_000, 1_000, -1)).toBe(true);
|
||||
});
|
||||
|
||||
it('blocks within the window and allows once elapsed', () => {
|
||||
const last = 10_000;
|
||||
expect(statusCooldownElapsed(last, last + 4_999, 5)).toBe(false);
|
||||
expect(statusCooldownElapsed(last, last + 5_000, 5)).toBe(true);
|
||||
expect(statusCooldownElapsed(last, last + 9_999, 5)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('formatUptime', () => {
|
||||
it('drops leading zero units', () => {
|
||||
expect(formatUptime(0)).toBe('0秒');
|
||||
expect(formatUptime(45_000)).toBe('45秒');
|
||||
expect(formatUptime(90_000)).toBe('1分钟 30秒');
|
||||
expect(formatUptime(3_600_000)).toBe('1小时 0分钟');
|
||||
expect(formatUptime((26 * 3600 + 12 * 60) * 1000)).toBe('1天 2小时 12分钟');
|
||||
});
|
||||
|
||||
it('never goes negative', () => {
|
||||
expect(formatUptime(-5_000)).toBe('0秒');
|
||||
});
|
||||
});
|
||||
|
||||
describe('buildStatusText', () => {
|
||||
it('renders version / platform / uptime, no leaked uin or topology', () => {
|
||||
const text = buildStatusText({
|
||||
version: '1.9.3-node',
|
||||
platform: 'linux',
|
||||
arch: 'x64',
|
||||
uptimeMs: 90_000,
|
||||
});
|
||||
expect(text).toContain('SnowLuma');
|
||||
expect(text).toContain('版本: 1.9.3-node');
|
||||
expect(text).toContain('平台: linux-x64');
|
||||
expect(text).toContain('运行时长: 1分钟 30秒');
|
||||
// public-safe: must not echo a uin or connection count
|
||||
expect(text).not.toMatch(/uin|连接|adapter/i);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proto-defs",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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).",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/protocol",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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>'`.",
|
||||
|
||||
@@ -105,32 +105,31 @@ function makeReplyElem(element: MessageElement): ProtoElem {
|
||||
return { srcMsg };
|
||||
}
|
||||
|
||||
function makeDeflatedPayload(content: string): Uint8Array {
|
||||
const deflated = deflateSync(Buffer.from(content, 'utf8'));
|
||||
const payload = new Uint8Array(deflated.length + 1);
|
||||
payload[0] = 0x01;
|
||||
payload.set(deflated, 1);
|
||||
return payload;
|
||||
}
|
||||
|
||||
function makeJsonElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: 1,
|
||||
template1: payload,
|
||||
lightApp: {
|
||||
data: makeDeflatedPayload(content),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeXmlElem(element: MessageElement): ProtoElem {
|
||||
const content = element.text ?? '';
|
||||
const payload = new Uint8Array(content.length + 1);
|
||||
payload[0] = 0x00;
|
||||
const encoded = new TextEncoder().encode(content);
|
||||
payload.set(encoded, 1);
|
||||
|
||||
return {
|
||||
richMsg: {
|
||||
serviceId: element.subType === 0 ? 35 : (element.subType ?? 35),
|
||||
template1: payload,
|
||||
template1: makeDeflatedPayload(content),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -208,14 +207,9 @@ function makeForwardElem(element: MessageElement): ProtoElem {
|
||||
};
|
||||
|
||||
const json = JSON.stringify(lightApp);
|
||||
const deflated = deflateSync(Buffer.from(json, 'utf8'));
|
||||
const payload = new Uint8Array(deflated.length + 1);
|
||||
payload[0] = 0x01; // 0x01 prefix = deflated JSON (vs 0x00 = uncompressed XML)
|
||||
payload.set(deflated, 1);
|
||||
|
||||
return {
|
||||
lightApp: {
|
||||
data: payload,
|
||||
data: makeDeflatedPayload(json),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -202,7 +202,14 @@ function readHttpResponseBody(socket: net.Socket): Promise<Uint8Array> {
|
||||
const onClose = () => finish(() => {
|
||||
const buf = Buffer.concat(chunks);
|
||||
if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd)));
|
||||
else reject(new Error('connection closed before response'));
|
||||
// QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定:
|
||||
// 第一次 POST 拿到响应后服务器经常立刻 FIN 关闭,下一次写入的请求体
|
||||
// 走到一个已被对端 close 的 socket 上,触发这里。诊断信息把已收到的
|
||||
// 字节数和是否解析到 header 一起带出来,便于区分 “连接刚握手就被关”
|
||||
// 和 “响应读到一半被截断” 两种情况。
|
||||
else reject(new Error(
|
||||
`connection closed before response (received=${buf.length}B, headerSeen=${headerEnd >= 0})`
|
||||
));
|
||||
});
|
||||
|
||||
socket.on('data', onData);
|
||||
@@ -225,42 +232,60 @@ export async function uploadHighwayHttp(
|
||||
bytes: Uint8Array, fileMd5: Uint8Array, extend: Uint8Array,
|
||||
): Promise<void> {
|
||||
const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`;
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
|
||||
try {
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
const responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
// Surface every diagnostic the highway response carries so
|
||||
// user reports of `error_code=921` and friends include the
|
||||
// server-side context (segHead.retCode, chunk size, file md5)
|
||||
// — without these we can't tell apart a malformed-payload
|
||||
// reject, a session-ticket mismatch, or a per-account rate-
|
||||
// limit.
|
||||
const segRetCode = resp.msgSegHead?.retCode ?? 0;
|
||||
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
|
||||
throw new Error(
|
||||
`highway upload error_code=${resp.errorCode}` +
|
||||
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
|
||||
` offset=${offset} segRetCode=${segRetCode}` +
|
||||
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
|
||||
);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
// 每个 chunk 一个独立的 TCP 连接。
|
||||
//
|
||||
// 旧实现整个文件复用同一个 socket,依赖 `Connection: keep-alive` 跑多次
|
||||
// POST。但 QQ highway 边缘节点(以及链路上的代理/NAT)经常在第一次响应
|
||||
// 之后立刻 FIN 关闭连接,导致第二个 chunk 写入一个已被对端关闭的 socket,
|
||||
// `readHttpResponseBody` 立刻收到 `close` 事件并抛 `connection closed
|
||||
// before response`。
|
||||
//
|
||||
// 现象上的体现:≤1 MB 的图片/PTT 因为只发一个 chunk,不会触发;超过 1 MB
|
||||
// 的图片或视频(HIGHWAY_BLOCK_SIZE = 1 MiB)必然失败。
|
||||
//
|
||||
// 改成每 chunk 一连接代价可忽略:
|
||||
// - 单个 1 MB chunk 的传输时间远大于 TCP 建连开销;
|
||||
// - QQ 服务端反正也不希望客户端长时间占用连接;
|
||||
// - 与 NapCat / Lagrange 在大文件上传时的连接生命周期一致。
|
||||
let offset = 0;
|
||||
while (offset < bytes.length) {
|
||||
const chunkSize = Math.min(HIGHWAY_BLOCK_SIZE, bytes.length - offset);
|
||||
const chunk = bytes.subarray(offset, offset + chunkSize);
|
||||
const chunkMd5 = computeMd5(chunk);
|
||||
const head = makeHighwayHead(
|
||||
bridge.identity.uin, commandId, bytes.length, offset, chunkSize,
|
||||
chunkMd5, fileMd5, session.sigSession, extend,
|
||||
);
|
||||
const frame = packHighwayFrame(head, chunk);
|
||||
|
||||
const socket = await tcpConnect(session.host, session.port);
|
||||
let responseBody: Uint8Array;
|
||||
try {
|
||||
responseBody = await httpPostFrame(socket, session.host, pathStr, frame);
|
||||
} finally {
|
||||
socket.destroy();
|
||||
}
|
||||
} finally {
|
||||
socket.destroy();
|
||||
|
||||
const { head: respHead } = unpackHighwayFrame(responseBody);
|
||||
const resp = protobuf_decode<RespDataHighwayHead>(respHead);
|
||||
if (resp?.errorCode && resp.errorCode !== 0) {
|
||||
// Surface every diagnostic the highway response carries so
|
||||
// user reports of `error_code=921` and friends include the
|
||||
// server-side context (segHead.retCode, chunk size, file md5)
|
||||
// — without these we can't tell apart a malformed-payload
|
||||
// reject, a session-ticket mismatch, or a per-account rate-
|
||||
// limit.
|
||||
const segRetCode = resp.msgSegHead?.retCode ?? 0;
|
||||
const fileMd5Hex = Buffer.from(fileMd5).toString('hex');
|
||||
throw new Error(
|
||||
`highway upload error_code=${resp.errorCode}` +
|
||||
` (cmdId=${commandId} chunk=${chunkSize}/${bytes.length}` +
|
||||
` offset=${offset} segRetCode=${segRetCode}` +
|
||||
` fileMd5=${fileMd5Hex.slice(0, 16)}…)`,
|
||||
);
|
||||
}
|
||||
offset += chunkSize;
|
||||
console.log(`[Highway] uploaded ${offset}/${bytes.length} bytes`);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@snowluma/proton",
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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.3",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "index.mjs",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
|
||||
"keywords": [
|
||||
"snowluma",
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
"name": "MotricSeven",
|
||||
"email": "[email protected]"
|
||||
},
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"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.3",
|
||||
"version": "1.9.4",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "webui",
|
||||
"private": true,
|
||||
"version": "1.9.3",
|
||||
"version": "1.9.4",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
// "通用设置" tab — fields that apply to the whole OneBotInstance rather
|
||||
// than any specific adapter. Currently just the music-sign service URL,
|
||||
// but the layout has room for additional cross-cutting toggles.
|
||||
// than any specific adapter: the music-sign service URL and the built-in
|
||||
// `#sl` status command. Edits here mark the config dirty and are persisted
|
||||
// via the page's explicit top-right 保存 (a continuously-edited surface).
|
||||
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import type { OneBotConfig } from '@/types';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import type { OneBotConfig, StatusCommandConfig } from '@/types';
|
||||
|
||||
interface GeneralSettingsTabProps {
|
||||
config: OneBotConfig;
|
||||
@@ -12,6 +14,10 @@ interface GeneralSettingsTabProps {
|
||||
}
|
||||
|
||||
export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps) {
|
||||
const sc = config.statusCommand;
|
||||
const setStatusCommand = (patch: Partial<StatusCommandConfig>) =>
|
||||
onChange({ ...config, statusCommand: { ...sc, ...patch } });
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-1.5 rounded-lg border bg-card/40 p-4">
|
||||
@@ -26,6 +32,57 @@ export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps
|
||||
用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-4 rounded-lg border bg-card/40 p-4">
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="min-w-0">
|
||||
<Label>
|
||||
内置状态命令 <code className="font-mono text-xs">#sl</code>
|
||||
</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
收到纯文本 <code className="font-mono">#sl</code> 时回复 SnowLuma 版本 / 平台 / 运行时长。任何人可触发,关闭后完全不响应。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={sc.enabled}
|
||||
onChange={(v) => setStatusCommand({ enabled: v })}
|
||||
ariaLabel="启用 #sl 状态命令"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex items-start justify-between gap-3 border-t pt-3">
|
||||
<div className="min-w-0">
|
||||
<Label className={sc.enabled ? undefined : 'text-muted-foreground'}>不转发给下游(swallow)</Label>
|
||||
<p className="mt-1 text-[11px] leading-relaxed text-muted-foreground">
|
||||
开启后,命中的 <code className="font-mono">#sl</code> 不再投递给已连接的 Bot(仍会回复并本地记录)。默认关闭即透传。
|
||||
</p>
|
||||
</div>
|
||||
<ToggleSwitch
|
||||
value={sc.swallow}
|
||||
onChange={(v) => setStatusCommand({ swallow: v })}
|
||||
ariaLabel="吞掉 #sl 不转发给下游"
|
||||
disabled={!sc.enabled}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="flex flex-col gap-1.5 border-t pt-3">
|
||||
<Label className={sc.enabled ? undefined : 'text-muted-foreground'}>回复冷却(秒)</Label>
|
||||
<Input
|
||||
type="number"
|
||||
min={0}
|
||||
className="w-32 tabular-nums"
|
||||
value={sc.cooldownSeconds}
|
||||
disabled={!sc.enabled}
|
||||
onChange={(e) => {
|
||||
const n = Math.trunc(Number(e.target.value));
|
||||
setStatusCommand({ cooldownSeconds: Number.isFinite(n) && n >= 0 ? n : 0 });
|
||||
}}
|
||||
/>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
同一会话在该秒数内重复 <code className="font-mono">#sl</code> 不再回复,防刷屏。<code className="font-mono">0</code> 表示不限制。
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { motion } from 'motion/react';
|
||||
import { Pencil, Trash2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ToggleSwitch } from '@/components/ui/toggle-switch';
|
||||
import { cn } from '@/lib/utils';
|
||||
import type { AdapterCommon } from './defaults';
|
||||
import type { AdapterStatus } from '@/types';
|
||||
@@ -126,30 +127,3 @@ export function NodeSummaryCard<T extends AdapterCommon>({
|
||||
);
|
||||
}
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
}
|
||||
|
||||
function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border transition-colors',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, type ReactNode } from 'react';
|
||||
import { motion } from 'motion/react';
|
||||
import { Check, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Sun } from 'lucide-react';
|
||||
import { Bug, Check, ExternalLink, Github, Info, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Star, Sun, Tag } from 'lucide-react';
|
||||
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
@@ -29,12 +29,13 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[]
|
||||
{ value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' },
|
||||
];
|
||||
|
||||
type SettingsTab = 'appearance' | 'data' | 'account';
|
||||
type SettingsTab = 'appearance' | 'data' | 'account' | 'about';
|
||||
|
||||
const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [
|
||||
{ key: 'appearance', label: '外观', icon: Palette },
|
||||
{ key: 'data', label: '数据刷新', icon: RefreshCw },
|
||||
{ key: 'account', label: '账号安全', icon: ShieldCheck },
|
||||
{ key: 'about', label: '关于', icon: Info },
|
||||
];
|
||||
|
||||
export function SettingsPage() {
|
||||
@@ -47,6 +48,7 @@ export function SettingsPage() {
|
||||
{tab === 'appearance' && <AppearancePanel />}
|
||||
{tab === 'data' && <DataPanel />}
|
||||
{tab === 'account' && <AccountPanel />}
|
||||
{tab === 'about' && <AboutPanel />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -305,3 +307,76 @@ function AccountPanel() {
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// ─────────────── 关于 ───────────────
|
||||
|
||||
const REPO_URL = 'https://github.com/SnowLuma/SnowLuma';
|
||||
|
||||
function AboutPanel() {
|
||||
return (
|
||||
<Card className="overflow-hidden">
|
||||
<CardContent className="flex flex-col items-center gap-6 px-6 py-8 text-center sm:px-8">
|
||||
{/* brand hero */}
|
||||
<motion.div
|
||||
initial={{ opacity: 0, y: 10, scale: 0.96 }}
|
||||
animate={{ opacity: 1, y: 0, scale: 1 }}
|
||||
transition={{ type: 'spring', stiffness: 260, damping: 22 }}
|
||||
className="flex flex-col items-center gap-3"
|
||||
>
|
||||
<div className="relative">
|
||||
<div aria-hidden className="absolute inset-0 -z-10 scale-125 rounded-full bg-primary/20 blur-2xl" />
|
||||
<img src="/logo.png" alt="SnowLuma" className="size-20 object-contain drop-shadow-sm" />
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-2xl font-semibold tracking-tight">SnowLuma</span>
|
||||
<span className="rounded-full border border-primary/30 bg-primary/10 px-2 py-0.5 font-mono text-[11px] text-primary tabular-nums">
|
||||
v{__APP_VERSION__}
|
||||
</span>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">Next Remote Protocol Framework · 下一代远程协议框架</p>
|
||||
</motion.div>
|
||||
|
||||
<p className="max-w-md text-[13px] leading-relaxed text-muted-foreground">
|
||||
以轻量注入驱动 QQ NT,对外提供标准 OneBot v11 接口,让机器人一次部署、长期稳定运行。
|
||||
</p>
|
||||
|
||||
{/* Star CTA */}
|
||||
<div className="flex w-full max-w-sm flex-col items-center gap-2 rounded-xl border bg-gradient-to-b from-primary/[0.07] to-transparent p-5">
|
||||
<Star className="size-6 fill-primary/20 text-primary" />
|
||||
<p className="text-sm font-medium">喜欢 SnowLuma?点个 Star 支持一下</p>
|
||||
<p className="text-[11px] leading-relaxed text-muted-foreground">
|
||||
开源不易,你的 ⭐ 是我们持续维护的最大动力。
|
||||
</p>
|
||||
<Button asChild className="mt-1 w-full">
|
||||
<a href={REPO_URL} target="_blank" rel="noreferrer noopener">
|
||||
<Github className="size-4" />
|
||||
去 GitHub 点 Star
|
||||
</a>
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* secondary links */}
|
||||
<div className="flex flex-wrap items-center justify-center gap-x-5 gap-y-2 text-[12px]">
|
||||
<AboutLink href={REPO_URL} icon={Github}>仓库</AboutLink>
|
||||
<AboutLink href={`${REPO_URL}/releases`} icon={Tag}>发行版</AboutLink>
|
||||
<AboutLink href={`${REPO_URL}/issues`} icon={Bug}>反馈问题</AboutLink>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
function AboutLink({ href, icon: Icon, children }: { href: string; icon: typeof Sun; children: ReactNode }) {
|
||||
return (
|
||||
<a
|
||||
href={href}
|
||||
target="_blank"
|
||||
rel="noreferrer noopener"
|
||||
className="inline-flex items-center gap-1.5 text-muted-foreground transition-colors hover:text-foreground"
|
||||
>
|
||||
<Icon className="size-3.5" />
|
||||
{children}
|
||||
<ExternalLink className="size-3 opacity-50" />
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { motion } from 'motion/react';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ToggleSwitchProps {
|
||||
value: boolean;
|
||||
onChange: (v: boolean) => void;
|
||||
ariaLabel: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
/** Small animated on/off switch (`role="switch"`). Shared across the config
|
||||
* surfaces — node enable toggle, built-in command toggles, etc. */
|
||||
export function ToggleSwitch({ value, onChange, ariaLabel, disabled }: ToggleSwitchProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="switch"
|
||||
aria-checked={value ? 'true' : 'false'}
|
||||
aria-label={ariaLabel}
|
||||
disabled={disabled}
|
||||
onClick={() => onChange(!value)}
|
||||
className={cn(
|
||||
'relative inline-flex h-6 w-11 shrink-0 items-center rounded-full border transition-colors',
|
||||
disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
|
||||
value ? 'border-primary bg-primary' : 'border-input bg-muted',
|
||||
)}
|
||||
>
|
||||
<motion.span
|
||||
className="inline-block size-4 rounded-full bg-background shadow-sm"
|
||||
animate={{ x: value ? 22 : 4 }}
|
||||
transition={{ type: 'spring', stiffness: 500, damping: 30 }}
|
||||
/>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -1,4 +1,20 @@
|
||||
import type { MessageFormat, OneBotConfig } from '@/types';
|
||||
import type { MessageFormat, OneBotConfig, StatusCommandConfig } from '@/types';
|
||||
|
||||
const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, swallow: false, cooldownSeconds: 5 };
|
||||
|
||||
/** Fill the `statusCommand` block with defaults when the backend omits or
|
||||
* partially supplies it (older configs predate the feature). */
|
||||
function normalizeStatusCommand(raw: unknown): StatusCommandConfig {
|
||||
const src = (raw ?? {}) as Record<string, unknown>;
|
||||
return {
|
||||
enabled: typeof src.enabled === 'boolean' ? src.enabled : DEFAULT_STATUS_COMMAND.enabled,
|
||||
swallow: typeof src.swallow === 'boolean' ? src.swallow : DEFAULT_STATUS_COMMAND.swallow,
|
||||
cooldownSeconds:
|
||||
typeof src.cooldownSeconds === 'number' && Number.isFinite(src.cooldownSeconds) && src.cooldownSeconds >= 0
|
||||
? Math.trunc(src.cooldownSeconds)
|
||||
: DEFAULT_STATUS_COMMAND.cooldownSeconds,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Anti-corruption layer for the per-UIN config payload. Older backends emit
|
||||
@@ -30,5 +46,6 @@ export function normalizeOneBotConfig(raw: unknown): OneBotConfig {
|
||||
wsClients: list(nets.wsClients) as unknown as OneBotConfig['networks']['wsClients'],
|
||||
},
|
||||
musicSignUrl: typeof cfg.musicSignUrl === 'string' ? cfg.musicSignUrl : undefined,
|
||||
statusCommand: normalizeStatusCommand(cfg.statusCommand),
|
||||
};
|
||||
}
|
||||
@@ -77,9 +77,17 @@ export interface OneBotNetworks {
|
||||
wsClients: WsClientNetwork[];
|
||||
}
|
||||
|
||||
/** Built-in `#sl` status command settings (trigger word is hardcoded). */
|
||||
export interface StatusCommandConfig {
|
||||
enabled: boolean;
|
||||
swallow: boolean;
|
||||
cooldownSeconds: number;
|
||||
}
|
||||
|
||||
export interface OneBotConfig {
|
||||
networks: OneBotNetworks;
|
||||
musicSignUrl?: string;
|
||||
statusCommand: StatusCommandConfig;
|
||||
}
|
||||
|
||||
export type NetworkKind = keyof OneBotNetworks;
|
||||
|
||||
Reference in new issue
Block a user