From 397087dc748ba2bcd60eacaeba934f94be0ac994 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 30 Jun 2026 23:09:21 +0800 Subject: [PATCH 01/30] test(core): hoist Bridge import to fix flaky 5s timeout MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit bridge-private-routing.test.ts loaded the Bridge dependency tree via `await import(...)` INSIDE each `it`, so the first test paid the whole ~3.8s module-eval cost against its 5000ms per-test budget — fine locally but tipping over on slower CI runners (surfaced as a timeout on an unrelated PR). Moved the Bridge / IdentityService imports to top-level statics (vi.mock is hoisted above them, so element-builder stays mocked): the heavy load now happens once at file collection, not against a test timeout. Per-test execution dropped from ~3.8s to ~7ms. --- packages/core/tests/bridge-private-routing.test.ts | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/core/tests/bridge-private-routing.test.ts b/packages/core/tests/bridge-private-routing.test.ts index f90506ca..7ef9c439 100644 --- a/packages/core/tests/bridge-private-routing.test.ts +++ b/packages/core/tests/bridge-private-routing.test.ts @@ -10,10 +10,15 @@ vi.mock('@snowluma/protocol/element-builder', () => ({ buildSendElems: vi.fn(async () => [{ text: { str: 'stub media elem' } }]), })); +// Imported statically (not via `await import` inside each `it`) so the heavy +// Bridge dependency-tree load happens once at file collection — not against a +// single test's 5s timeout, which tipped over on slower CI runners. vi.mock is +// hoisted above these by vitest, so element-builder is still mocked. +import { Bridge } from '../src/bridge/bridge'; +import { IdentityService } from '@snowluma/protocol/identity-service'; + describe('Bridge private media routing', () => { it('includes resolved uid in the final c2c send request for media messages', async () => { - const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; @@ -61,8 +66,6 @@ describe('Bridge private media routing', () => { // BuildPacketBase` + `FileEntity.PackMessageContent`. Previous // implementation wrote c2c routing + richText.notOnlineFile + // c2cCmd=11 — the QQ-NT server rejected every c2c file send. - const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; @@ -160,8 +163,6 @@ describe('Bridge private media routing', () => { }); it('c2c file send survives a failing 0xE37_800 finalize — sends without field6 (#157 best-effort)', async () => { - const { Bridge } = await import('../src/bridge/bridge'); - const { IdentityService } = await import('@snowluma/protocol/identity-service'); class TestBridge extends Bridge { capturedBody: Uint8Array | null = null; From c90a3954e4d8437b03bf269b2a07e867f1623d8d Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Tue, 30 Jun 2026 23:29:51 +0800 Subject: [PATCH 02/30] fix(bridge): self-heal login detection when the hook misses the edge MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Docker SnowLuma could hang forever at "等待登录" after QQ had already logged in. Root cause: login detection is edge-triggered — it only learns the state from a loginState frame the native hook PUSHES when it observes the login transition. `getLoginState()` is a cached value read once at connect; after that the session waits passively. Desktop attaches the hook before the user logs in, so it catches the edge. In Docker, QQ auto-logs-in from a persisted session — fast on startup — so the transition lands before the recv pipe is connected (frames aren't replayed) or via a silent restore path the hook doesn't intercept. The edge is missed and the cached state stays not-logged-in. Fix: while connected but not logged in, actively re-probe QQ's own ptlogin/deeplink ports via probeQqLoginInfo (level-triggered, pipe- independent — the same call the workaround used) and synthesize the login once it reports a real uin. Immediate probe on connect + a 3s interval; stopped on login / teardown / dispose, with an in-flight guard so a slow port scan can't stack concurrent probes. Idempotent with the pushed-frame path. 7 tests cover detect-via-probe, the later-interval case, the not-logged-in / non-real-uin / throwing-probe guards, no double-emit, and no concurrent stacking. probeLogin is injectable for tests. --- packages/bridge/src/hook-session.ts | 78 +++++++++++- packages/bridge/tests/hook-session.test.ts | 139 +++++++++++++++++++++ 2 files changed, 215 insertions(+), 2 deletions(-) diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index 55326f23..6f18baae 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -4,15 +4,25 @@ import { EventEmitter } from 'events'; import { HookPacketClient } from './hook-packet-client'; import type { HookInjectResult } from './injector'; import type { QqHookClient, QqHookLoginState, QqHookPacket } from './qq-hook-client'; +import { probeQqLoginInfo, type QqPortLoginInfo } from './qq-port-probe'; import { statusFor } from './hook-status'; import type { HookProcessInfo, HookProcessStatus } from './types'; +/** How often to actively re-probe QQ's login state while connected but not yet + * logged in — the safety net for a login the native hook never pushed (Docker + * auto-login races/bypasses the pushed loginState frame). */ +const LOGIN_RECONCILE_INTERVAL_MS = 3000; + export type HookSessionDeps = { injector: { inject: (pid: number) => HookInjectResult; unload: (pid: number, handle: HookInjectResult['handle']) => void; }; makeClient: (pid: number) => QqHookClient; + /** Active, pipe-independent login probe (reads QQ's ptlogin/deeplink ports). + * Drives the login-reconcile safety net; injectable for tests. Defaults to + * `probeQqLoginInfo`. */ + probeLogin?: (pid: number) => Promise; /** Sync fast-path check used by load() to skip re-injection when a * prior SnowLuma run left a working pipe behind. `tickNow` forces a * fresh poll — used after unload to dodge the up-to-1500ms cache @@ -50,6 +60,7 @@ export class HookSession extends EventEmitter { private readonly injector: HookSessionDeps['injector']; private readonly makeClient: HookSessionDeps['makeClient']; + private readonly probeLogin: (pid: number) => Promise; private readonly pipeWatcher: HookSessionDeps['pipeWatcher']; private readonly onPacket: PacketSink | null; private readonly log: Logger; @@ -70,12 +81,15 @@ export class HookSession extends EventEmitter { private bound = false; private opChain: Promise = Promise.resolve(); private disposed = false; + private loginProbeTimer: ReturnType | null = null; + private probing = false; constructor(pid: number, deps: HookSessionDeps) { super(); this.pid = pid; this.injector = deps.injector; this.makeClient = deps.makeClient; + this.probeLogin = deps.probeLogin ?? probeQqLoginInfo; this.pipeWatcher = deps.pipeWatcher; this.onPacket = deps.onPacket ?? null; this.log = deps.log ?? createLogger('HookSession'); @@ -347,8 +361,15 @@ export class HookSession extends EventEmitter { // handleLoginState owns the connected+loggedIn → 'online' (+ login // emit) transition; defer to it so the status is set once. Otherwise // we're connected-but-not-logged-in → 'loaded'. - if (loginState.loggedIn) this.handleLoginState(loginState); - else this.applyStatus(); + if (loginState.loggedIn) { + this.handleLoginState(loginState); + } else { + this.applyStatus(); + // The native hook only PUSHES a loginState frame on the login edge; + // if QQ logged in before/around connect (Docker auto-login) that edge + // is missed and we'd wait forever. Actively re-probe until logged in. + this.startLoginReconcile(); + } this.log.info('pipe connected: PID=%d', this.pid); } catch (error) { this._error = errMsg(error); @@ -381,6 +402,7 @@ export class HookSession extends EventEmitter { } private tearDownClient(): void { + this.stopLoginReconcile(); const client = this.client; if (client) { client.removeAllListeners(); @@ -398,6 +420,9 @@ export class HookSession extends EventEmitter { const previousUin = this._uin; this._uin = state.uin || state.uinNumber.toString(); this.loggedIn = state.loggedIn && isRealUin(this._uin); + // However login was observed (pushed frame or the active probe), the + // safety net's job is done. + if (this.loggedIn) this.stopLoginReconcile(); // Only the connected/logged-in states are ours to set here; when fully // down we leave the status the teardown path already settled. @@ -416,6 +441,55 @@ export class HookSession extends EventEmitter { this.log.success('login detected: PID=%d UIN=%s', this.pid, this._uin); } + // ─────────────── login reconcile (Docker auto-login safety net) ─────────── + // The hook's loginState frame is edge-triggered (pushed only when the native + // observes the login transition). When that edge is missed — QQ auto-logged + // in before connect, or a silent session-restore path the hook doesn't + // intercept — we'd sit at 'loaded'/'connecting' forever. So while connected + // but not logged in, actively re-probe QQ's own ports and synthesize the + // login once it reports a real uin. Idempotent with the pushed-frame path + // (handleLoginState's wasLoggedIn guard dedups the 'login' emit). + + private startLoginReconcile(): void { + if (this.loginProbeTimer || this.disposed) return; + void this.probeLoginOnce(); // immediate — catch already-logged-in fast + this.loginProbeTimer = setInterval(() => void this.probeLoginOnce(), LOGIN_RECONCILE_INTERVAL_MS); + this.loginProbeTimer.unref?.(); + } + + private stopLoginReconcile(): void { + if (this.loginProbeTimer) { + clearInterval(this.loginProbeTimer); + this.loginProbeTimer = null; + } + } + + private async probeLoginOnce(): Promise { + // A port-scan probe can outlast the interval; skip overlapping ticks so a + // slow probe never stacks concurrent subprocess-spawning scans. + if (this.probing) return; + if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } + this.probing = true; + try { + let info: QqPortLoginInfo | null; + try { + info = await this.probeLogin(this.pid); + } catch { + return; // best-effort; the interval retries + } + // The await yielded — re-check we still want this before mutating state. + if (this.disposed || !this.connected || this.loggedIn) { this.stopLoginReconcile(); return; } + if (info?.loggedIn && isRealUin(info.uin)) { + this.log.info('login reconciled via active probe: PID=%d UIN=%s', this.pid, info.uin); + // isRealUin guarantees a pure non-empty digit string, so BigInt() here + // cannot throw (keep that contract if isRealUin's regex is ever changed). + this.handleLoginState({ loggedIn: true, uin: info.uin, uinNumber: BigInt(info.uin) }); + } + } finally { + this.probing = false; + } + } + private handlePacket(packet: QqHookPacket): void { if (!this.loggedIn) return; const uin = packet.uin || this._uin; diff --git a/packages/bridge/tests/hook-session.test.ts b/packages/bridge/tests/hook-session.test.ts index 5301446c..a9b555fe 100644 --- a/packages/bridge/tests/hook-session.test.ts +++ b/packages/bridge/tests/hook-session.test.ts @@ -3,6 +3,7 @@ import { EventEmitter } from 'events'; import { HookSession } from '../src/hook-session'; import type { ManualMapHandle } from '../src/injector'; import type { QqHookClient, QqHookPacket } from '../src/qq-hook-client'; +import type { QqPortLoginInfo } from '../src/qq-port-probe'; import type { PacketSink } from '@snowluma/common/protocol-types'; const DUMMY_HANDLE: ManualMapHandle = { base: 0n, entry: 0n, exceptionTable: 0n, size: 0 }; @@ -42,6 +43,7 @@ function makeSession(opts: { pipeLive?: boolean; clientFailsConnect?: boolean; onPacket?: PacketSink; + probeLogin?: (pid: number) => Promise; } = {}) { const pid = opts.pid ?? 1234; let pipeLive = opts.pipeLive ?? false; @@ -50,6 +52,9 @@ function makeSession(opts: { inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), unload: vi.fn(), }; + // Default probe reports "not logged in" so the reconcile safety net is inert + // unless a test opts into a logged-in probe (never hits the real port scan). + const probeLogin = opts.probeLogin ?? (async () => ({ port: 0, uin: '', loggedIn: false })); const session = new HookSession(pid, { injector, @@ -60,6 +65,7 @@ function makeSession(opts: { // Cast: FakeClient mirrors only the surface HookSession touches. return c as unknown as QqHookClient; }, + probeLogin, pipeWatcher: { isPipeLive: () => pipeLive }, onPacket: opts.onPacket, }); @@ -533,3 +539,136 @@ describe('HookSession — packet forwarding', () => { }); }); }); + +describe('HookSession — login reconcile (Docker auto-login safety net)', () => { + it('reconciles login via the active probe when the pushed frame is missed', async () => { + // Probe reports logged-in; the FakeClient never fires a loginState frame + // (the missed-edge Docker case). The immediate reconcile probe must detect + // it and emit "login". + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn: true }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); // connect (not logged in via frame) → starts reconcile + await flush(); // immediate probe resolves → handleLoginState + + expect(loginSpy).toHaveBeenCalledOnce(); + expect(loginSpy.mock.calls[0]![0]).toBe('10001'); + expect(ctx.session.status).toBe('online'); + expect(ctx.session.uin).toBe('10001'); + }); + + it('does not log in when the probe reports not-logged-in', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 0, uin: '', loggedIn: false }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); await flush(); + + expect(loginSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('loaded'); + }); + + it('ignores a probe with a non-real uin (0)', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '0', loggedIn: true }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); await flush(); + + expect(loginSpy).not.toHaveBeenCalled(); + }); + + it('tolerates a throwing probe (best-effort, no crash/login)', async () => { + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => { throw new Error('port scan failed'); }, + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); await flush(); + + expect(loginSpy).not.toHaveBeenCalled(); + expect(ctx.session.status).toBe('loaded'); + }); + + it('detects a login that lands on a LATER interval probe', async () => { + vi.useFakeTimers(); + try { + let loggedIn = false; + const ctx = makeSession({ + pipeLive: true, + probeLogin: async () => ({ port: 4301, uin: '10001', loggedIn }), + }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (not logged in yet) + expect(loginSpy).not.toHaveBeenCalled(); + + loggedIn = true; // QQ finishes auto-login + await vi.advanceTimersByTimeAsync(3000); // next interval probe picks it up + + expect(loginSpy).toHaveBeenCalledOnce(); + expect(ctx.session.status).toBe('online'); + } finally { + vi.useRealTimers(); + } + }); + + it('does not double-emit when the pushed frame logs in first', async () => { + // Pushed-frame login wins; a subsequent probe with the same uin must not + // re-emit (handleLoginState dedups), and the reconcile timer is stopped. + const probeLogin = vi.fn(async () => ({ port: 4301, uin: '10001', loggedIn: true })); + const ctx = makeSession({ pipeLive: true, probeLogin }); + const loginSpy = vi.fn(); + ctx.session.on('login', loginSpy); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await flush(); + ctx.currentClient().fireLogin('10001'); // pushed-frame login first + await flush(); + + expect(loginSpy).toHaveBeenCalledOnce(); + expect(ctx.session.status).toBe('online'); + }); +}); + +describe('HookSession — login reconcile does not stack concurrent probes', () => { + it('skips overlapping ticks while a slow probe is in flight', async () => { + vi.useFakeTimers(); + try { + // A probe that never resolves — simulates a slow port scan spanning + // multiple intervals. The in-flight guard must call it only once. + const probeLogin = vi.fn(() => new Promise(() => { /* pending */ })); + const ctx = makeSession({ pipeLive: true, probeLogin }); + + await ctx.session.load(); + ctx.session.onPipeUp(); + await vi.advanceTimersByTimeAsync(0); // connect + immediate probe (starts, stays pending) + await vi.advanceTimersByTimeAsync(9000); // 3 more interval ticks + + expect(probeLogin).toHaveBeenCalledTimes(1); // not stacked + } finally { + vi.useRealTimers(); + } + }); +}); From 2f374ea8c90b047bcba5f8dd8e2bdd40131a6303 Mon Sep 17 00:00:00 2001 From: Airline233 Date: Tue, 30 Jun 2026 23:57:39 +0800 Subject: [PATCH 03/30] feat(qzone): support post visibility rights when publishing qzone posts (#178) Add ugc_right and target_uins to the qzone publish path across protocol, bridge, and the send_qzone_msg OneBot action, regenerate the MCP catalog, and cover restricted visibility (16/128) with validation tests. --- packages/core/src/bridge/apis/qzone.ts | 11 ++++- packages/core/tests/actions/qzone.test.ts | 14 +++++-- packages/mcp/src/generated/catalog.json | 45 ++++++++++++++++++++- packages/mcp/src/generated/catalog.ts | 45 ++++++++++++++++++++- packages/onebot/src/actions/qzone.ts | 14 +++++-- packages/onebot/tests/qzone-actions.test.ts | 2 +- packages/protocol/src/web/qzone.ts | 43 ++++++++++++++++++-- packages/protocol/tests/web/qzone.test.ts | 41 +++++++++++++++++++ 8 files changed, 199 insertions(+), 16 deletions(-) diff --git a/packages/core/src/bridge/apis/qzone.ts b/packages/core/src/bridge/apis/qzone.ts index 6e9b1765..99785167 100644 --- a/packages/core/src/bridge/apis/qzone.ts +++ b/packages/core/src/bridge/apis/qzone.ts @@ -55,10 +55,17 @@ export class QzoneApi { * 发表说说,返回新说说的 tid。始终发到机器人自己的空间。 * `richType` / `richval`: 带图说说时传 richType=1 和 richval 字符串 * (多图用 `\t` 连接多个 richval)。纯文字说说省略这两个参数。 + * `ugcRight` / `targetUins`: 查看权限及其作用名单(ugcRight=16/128 时必填)。 */ - async publish(content: string, richType?: number, richval?: string): Promise { + async publish( + content: string, + richType?: number, + richval?: string, + ugcRight = 1, + targetUins?: string, + ): Promise { const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com'); - return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval); + return publishQzoneMsg(cookieObject, this.ctx.identity.uin, content, richType, richval, ugcRight, targetUins); } /** 删除机器人自己空间的一条说说(按 tid)。 */ diff --git a/packages/core/tests/actions/qzone.test.ts b/packages/core/tests/actions/qzone.test.ts index a1e9ed8b..219a1412 100644 --- a/packages/core/tests/actions/qzone.test.ts +++ b/packages/core/tests/actions/qzone.test.ts @@ -74,7 +74,7 @@ describe('apis/qzone', () => { const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 }); const out = await new QzoneApi(bridge as never).publish('hello'); expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); - expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 1, undefined); expect(out).toEqual({ tid: 'T', time: 1 }); }); @@ -85,7 +85,7 @@ describe('apis/qzone', () => { const richval = ',12345,abc,abc,22,800,600,,800,600'; const out = await new QzoneApi(bridge as never).publish('look at this', 1, richval); expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); - expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'look at this', 1, richval, 1, undefined); expect(out).toEqual({ tid: 'T2', time: 2 }); }); @@ -96,10 +96,18 @@ describe('apis/qzone', () => { const richval = ',12345,a,a,22,800,600,,800,600\t,12346,b,b,22,1024,768,,1024,768'; const out = await new QzoneApi(bridge as never).publish('two images', 1, richval); expect(getCookies).toHaveBeenCalledWith('qzone.qq.com'); - expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'two images', 1, richval, 1, undefined); expect(out).toEqual({ tid: 'T3', time: 3 }); }); + it('publish threads qzone visibility params', async () => { + const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); + const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); + const pubSpy = vi.spyOn(qzoneWeb, 'publishQzoneMsg').mockResolvedValue({ tid: 'T', time: 1 }); + await new QzoneApi(bridge as never).publish('hello', undefined, undefined, 16, '10002|10003'); + expect(pubSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'hello', undefined, undefined, 16, '10002|10003'); + }); + it('delete removes a feed by tid from the bot\'s own space', async () => { const getCookies = vi.fn(async () => ({ p_skey: 'PSK' })); const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never }); diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 24438b6c..706f0cd9 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -7183,7 +7183,7 @@ { "name": "send_qzone_msg", "aliases": [], - "summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)", + "summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)", "readOnly": false, "params": [ { @@ -7208,9 +7208,36 @@ } }, "desc": "图片数组(可选),支持 file:// http:// base64://;自动上传" + }, + { + "name": "ugc_right", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见", + "default": 1 + }, + { + "name": "target_uins", + "type": "uint[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + } + }, + "desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" } ], - "invariants": [], + "invariants": [ + "ugc_right must be one of 1, 4, 16, 64, 128", + "target_uins is required when ugc_right is 16 or 128" + ], "inputSchema": { "type": "object", "properties": { @@ -7226,6 +7253,20 @@ "minLength": 1 }, "description": "图片数组(可选),支持 file:// http:// base64://;自动上传" + }, + "ugc_right": { + "type": "integer", + "minimum": 1, + "description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见", + "default": 1 + }, + "target_uins": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" } }, "required": [ diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index b462ff50..8c2ceb70 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -7186,7 +7186,7 @@ export const ACTIONS: CatalogAction[] = [ { "name": "send_qzone_msg", "aliases": [], - "summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)", + "summary": "发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)", "readOnly": false, "params": [ { @@ -7211,9 +7211,36 @@ export const ACTIONS: CatalogAction[] = [ } }, "desc": "图片数组(可选),支持 file:// http:// base64://;自动上传" + }, + { + "name": "ugc_right", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 1 + }, + "desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见", + "default": 1 + }, + { + "name": "target_uins", + "type": "uint[]", + "required": false, + "schema": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + } + }, + "desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" } ], - "invariants": [], + "invariants": [ + "ugc_right must be one of 1, 4, 16, 64, 128", + "target_uins is required when ugc_right is 16 or 128" + ], "inputSchema": { "type": "object", "properties": { @@ -7229,6 +7256,20 @@ export const ACTIONS: CatalogAction[] = [ "minLength": 1 }, "description": "图片数组(可选),支持 file:// http:// base64://;自动上传" + }, + "ugc_right": { + "type": "integer", + "minimum": 1, + "description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见", + "default": 1 + }, + "target_uins": { + "type": "array", + "items": { + "type": "integer", + "minimum": 1 + }, + "description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单" } }, "required": [ diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts index 3650d022..ae7ec6a3 100644 --- a/packages/onebot/src/actions/qzone.ts +++ b/packages/onebot/src/actions/qzone.ts @@ -21,6 +21,8 @@ async function uploadQzoneImages( return parts.join('\t'); } +const QZONE_UGC_RIGHTS = new Set([1, 4, 16, 64, 128]); + export const actions = [ // get_qzone_msg_list — 获取 QQ 空间说说列表。无 go-cqhttp 标准,自定义命名。 // 默认取机器人自己的空间;传 target_uin 可查看指定账号(需有权限)。 @@ -120,19 +122,25 @@ export const actions = [ // 注意:发说说为主动行为,高频会被 Qzone 风控,调用方需自行限流。 defineAction({ name: 'send_qzone_msg', - summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传)', + summary: '发表说说(QQ 空间,支持纯文字或带图;传 images 自动上传;可设置查看权限)', params: { content: f.string({ allowEmpty: false }).describe('说说正文'), images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(), + ugc_right: f.int({ min: 1 }).describe('查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见').default(1), + target_uins: f.array(f.uint()).describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单').optional(), }, + rules: (r) => [ + r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) => QZONE_UGC_RIGHTS.has(p.ugc_right)), + r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length), + ], run: async (p, ctx) => { try { if (p.images && p.images.length > 0) { const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval); - const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval); + const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval, p.ugc_right, p.target_uins?.join('|')); return okResponse(res as unknown as JsonValue); } - const res = await ctx.bridge.apis.qzone.publish(p.content); + const res = await ctx.bridge.apis.qzone.publish(p.content, undefined, undefined, p.ugc_right, p.target_uins?.join('|')); return okResponse(res as unknown as JsonValue); } catch (error) { const message = error instanceof Error ? error.message : 'failed to publish qzone msg'; diff --git a/packages/onebot/tests/qzone-actions.test.ts b/packages/onebot/tests/qzone-actions.test.ts index 1289a988..2579d749 100644 --- a/packages/onebot/tests/qzone-actions.test.ts +++ b/packages/onebot/tests/qzone-actions.test.ts @@ -24,7 +24,7 @@ describe('qzone actions', () => { expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { tid: 'T1', time: 1 } }); expect(uploadImageFromSource).toHaveBeenNthCalledWith(1, 'file:///a.jpg'); expect(uploadImageFromSource).toHaveBeenNthCalledWith(2, 'file:///b.jpg'); - expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2'); + expect(publish).toHaveBeenCalledWith('hello', 1, 'RV1\tRV2', 1, undefined); }); it('comment_qzone uploads images and comments direct urls joined with tab', async () => { diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index a17a066c..fca10501 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -370,6 +370,8 @@ interface RawPublishResponse { now?: number; } +export type QzoneUgcRight = 1 | 4 | 16 | 64 | 128; + /** Result of publishing a 说说. */ export interface QzonePublishResult { [key: string]: JsonValue; @@ -379,6 +381,31 @@ export interface QzonePublishResult { time: number; } +const QZONE_UGC_RIGHTS = new Set([1, 4, 16, 64, 128]); + +function normalizeQzoneUgcRight(ugcRight: number): QzoneUgcRight { + if (!QZONE_UGC_RIGHTS.has(ugcRight)) { + throw new Error('ugc_right must be one of 1, 4, 16, 64, 128'); + } + return ugcRight as QzoneUgcRight; +} + +function normalizeTargetUins(targetUins?: string): string { + const raw = (targetUins ?? '').trim(); + if (!raw) return ''; + + const seen = new Set(); + for (const part of raw.split('|')) { + const uin = part.trim(); + if (!uin) continue; + if (!/^\d+$/.test(uin)) { + throw new Error('target_uins must contain QQ numbers separated by |'); + } + seen.add(uin); + } + return [...seen].join('|'); +} + /** * Publish a 说说 via taotao.qzone.qq.com's emotion_cgi_publish_v6 CGI * (proxied through h5.qzone.qq.com). POSTs a form-urlencoded body with @@ -399,6 +426,8 @@ export async function publishQzoneMsg( content: string, richType?: number, richval?: string, + ugcRight = 1, + targetUins?: string, ): Promise { if (!cookieObject || typeof cookieObject !== 'object') { throw new Error('cookieObject is required'); @@ -408,9 +437,15 @@ export async function publishQzoneMsg( } assertRichParams(richType, richval); + const right = normalizeQzoneUgcRight(ugcRight); + const effectiveTargetUins = right === 16 || right === 128 ? normalizeTargetUins(targetUins) : ''; + if ((right === 16 || right === 128) && !effectiveTargetUins) { + throw new Error('target_uins is required when ugc_right is 16 or 128'); + } + const bkn = getBknFromCookie(cookieObject); const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6?g_tk=${bkn}`; - const body = new URLSearchParams({ + const bodyParams = new URLSearchParams({ syn_tweet_verson: '1', paramstr: '1', pic_template: '', @@ -421,14 +456,16 @@ export async function publishQzoneMsg( con: content, feedversion: '1', ver: '1', - ugc_right: '1', + ugc_right: String(right), to_sign: '0', who: '1', hostuin: hostUin, code_version: '1', format: 'json', qzreferrer: `https://user.qzone.qq.com/${hostUin}`, - }).toString(); + }); + if (effectiveTargetUins) bodyParams.set('allow_uins', effectiveTargetUins); + const body = bodyParams.toString(); const text = await RequestUtil.HttpGetText(url, 'POST', body, { Cookie: cookieToString(cookieObject), diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts index c58a1fed..d45d4629 100644 --- a/packages/protocol/tests/web/qzone.test.ts +++ b/packages/protocol/tests/web/qzone.test.ts @@ -218,6 +218,8 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => { expect(form.get('con')).toBe('hello 世界 & friends'); expect(form.get('hostuin')).toBe('10000'); expect(form.get('who')).toBe('1'); + expect(form.get('ugc_right')).toBe('1'); + expect(form.has('allow_uins')).toBe(false); expect(form.get('format')).toBe('json'); expect(form.get('qzreferrer')).toBe('https://user.qzone.qq.com/10000'); }); @@ -235,6 +237,39 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => { expect(form.get('richval')).toBe(richval); }); + it('threads publish permission fields for restricted visibility', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue( + '{"code":0,"t1_tid":"RIGHTTID","t1_time":"1700000000"}', + ); + + await expect(publishQzoneMsg(cookies, '10000', 'limited', undefined, undefined, 16, '10001 | 10002|10001')).resolves.toEqual({ + tid: 'RIGHTTID', + time: 1700000000, + }); + + const [, , body] = spy.mock.calls[0]!; + const form = new URLSearchParams(body as string); + expect(form.get('ugc_right')).toBe('16'); + expect(form.get('allow_uins')).toBe('10001|10002'); + expect(form.get('who')).toBe('1'); + }); + + it('ignores target_uins for non-restricted visibility', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue( + '{"code":0,"t1_tid":"FRIENDTID","t1_time":"1700000000"}', + ); + + await expect(publishQzoneMsg(cookies, '10000', 'friends', undefined, undefined, 4, 'not-a-uin')).resolves.toEqual({ + tid: 'FRIENDTID', + time: 1700000000, + }); + + const [, , body] = spy.mock.calls[0]!; + const form = new URLSearchParams(body as string); + expect(form.get('ugc_right')).toBe('4'); + expect(form.has('allow_uins')).toBe(false); + }); + it('falls back to tid/now for alternate client builds', async () => { vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"tid":"ALT","now":1700000001}'); await expect(publishQzoneMsg(cookies, '10000', 'hi')).resolves.toEqual({ tid: 'ALT', time: 1700000001 }); @@ -253,6 +288,12 @@ describe('qzone / publishQzoneMsg (HTTP layer)', () => { expect(spy).not.toHaveBeenCalled(); }); + it('rejects restricted visibility without target_uins before any request', async () => { + const spy = vi.spyOn(RequestUtil, 'HttpGetText'); + await expect(publishQzoneMsg(cookies, '10000', 'hi', undefined, undefined, 128)).rejects.toThrow('target_uins is required'); + expect(spy).not.toHaveBeenCalled(); + }); + it('throws on a non-zero qzone code (rejected/rate-limited)', async () => { vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-10000,"message":"too frequent"}'); await expect(publishQzoneMsg(cookies, '10000', 'hi')).rejects.toThrow('code=-10000'); From 9ca64bed10fa0b8251a1b4048c981d752cc72257 Mon Sep 17 00:00:00 2001 From: Airline233 Date: Wed, 1 Jul 2026 02:13:35 +0800 Subject: [PATCH 04/30] feat(core,onebot): implement trans_group_file action (#161) --- packages/core/src/bridge/apis/group-file.ts | 6 +++ packages/core/tests/actions/_helpers.ts | 2 + .../core/tests/actions/group-file.test.ts | 21 ++++++++ packages/mcp/src/generated/catalog.json | 39 ++++++++++++-- packages/mcp/src/generated/catalog.ts | 39 ++++++++++++-- packages/onebot/src/actions/extended.ts | 13 +++-- .../onebot/tests/extended-actions.test.ts | 25 +++++++++ .../proto-defs/src/oidb-actions/group-file.ts | 17 ++++++ packages/protocol/package.json | 4 ++ .../group-file/trans-group-file.ts | 52 +++++++++++++++++++ .../group-file/trans-group-file.test.ts | 52 +++++++++++++++++++ 11 files changed, 260 insertions(+), 10 deletions(-) create mode 100644 packages/protocol/src/oidb-services/group-file/trans-group-file.ts create mode 100644 packages/protocol/tests/oidb-services/group-file/trans-group-file.test.ts diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index b134be54..afd1b8fc 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -23,6 +23,7 @@ import { MoveGroupFile } from '@snowluma/protocol/oidb-services/group-file/move- 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 { TransGroupFile, type TransGroupFileResult } from '@snowluma/protocol/oidb-services/group-file/trans-group-file'; 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'; import { ensureRetCodeZero } from '@snowluma/protocol/oidb-services/shared'; @@ -238,6 +239,11 @@ export class GroupFileApi { return PublishGroupFile.invoke(this.ctx, { groupId, fileId }); } + trans(groupId: number, fileId: string): Promise { + if (!fileId) throw new Error('trans requires fileId'); + return TransGroupFile.invoke(this.ctx, { groupId, fileId }); + } + // ─────────────── count ─────────────── getCount(groupId: number): Promise<{ fileCount: number; maxCount: number }> { diff --git a/packages/core/tests/actions/_helpers.ts b/packages/core/tests/actions/_helpers.ts index d41bc212..fd003e24 100644 --- a/packages/core/tests/actions/_helpers.ts +++ b/packages/core/tests/actions/_helpers.ts @@ -65,6 +65,7 @@ export interface MockGroupFileApi { upload: ReturnType; uploadPrivate: ReturnType; publish: ReturnType; + trans: ReturnType; getCount: ReturnType; list: ReturnType; getUrl: ReturnType; @@ -85,6 +86,7 @@ export function mockGroupFileApi(): MockGroupFileApi { upload: vi.fn(async () => ({ fileId: 'stub-fid' })), uploadPrivate: vi.fn(async () => ({ fileId: 'stub-pfid', fileHash: 'stub-hash' })), publish: vi.fn(async () => undefined), + trans: vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/stub-path' })), getCount: vi.fn(async () => ({ fileCount: 0, maxCount: 10000 })), list: vi.fn(async () => ({ files: [], folders: [] })), getUrl: vi.fn(async () => 'stub://url'), diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index 7b18ef34..d44c4368 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -8,6 +8,7 @@ import type { OidbGroupFileViewResp, OidbGroupFileFolderResp, OidbGroupSendFileReq, + OidbGroupSendFileResp, } from '@snowluma/proto-defs/oidb-actions/group-file'; import type { OidbPrivateFileUploadResp, @@ -246,6 +247,26 @@ describe('apis/group-file', () => { }); }); + it('trans hits OIDB 0x6d9_0 and returns the saved path metadata', async () => { + const bridge = mockBridge(); + bridge.sendRawPacket.mockResolvedValueOnce(packResponse( + protobuf_encode>({ + body: { transFile: { saveBusId: 102, saveFilePath: '/saved/path' } }, + }), + )); + const out = await new GroupFileApi(bridge as any).trans(12345, 'fid-trans'); + expect(out).toEqual({ saveBusId: 102, saveFilePath: '/saved/path' }); + const [wire, bytes] = bridge.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_0'); + const env = protobuf_decode>(bytes); + expect(env.body?.transFile).toMatchObject({ + groupUin: 12345n, + appId: 7, + busId: 102, + fileId: 'fid-trans', + }); + }); + it('uploadPrivate resolves both target + self UID before OIDB call', async () => { const bridge = mockBridge({ identity: { diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 706f0cd9..b6972a28 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -9094,13 +9094,46 @@ { "name": "trans_group_file", "aliases": [], - "summary": "转存群文件(未实现)", + "summary": "转存群文件", + "returns": "{ ok: true }", "readOnly": false, - "params": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "file_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], "invariants": [], "inputSchema": { "type": "object", - "properties": {}, + "properties": { + "group_id": { + "type": "integer", + "minimum": 1 + }, + "file_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "file_id" + ], "additionalProperties": true }, "category": "扩展" diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 8c2ceb70..5d2c9e26 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -9097,13 +9097,46 @@ export const ACTIONS: CatalogAction[] = [ { "name": "trans_group_file", "aliases": [], - "summary": "转存群文件(未实现)", + "summary": "转存群文件", + "returns": "{ ok: true }", "readOnly": false, - "params": [], + "params": [ + { + "name": "group_id", + "type": "uint", + "required": true, + "schema": { + "type": "integer", + "minimum": 1 + } + }, + { + "name": "file_id", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ], "invariants": [], "inputSchema": { "type": "object", - "properties": {}, + "properties": { + "group_id": { + "type": "integer", + "minimum": 1 + }, + "file_id": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "group_id", + "file_id" + ], "additionalProperties": true }, "category": "扩展" diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 95e8b114..20ca9ece 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1636,10 +1636,15 @@ export const actions = [ defineAction({ name: 'trans_group_file', - summary: '转存群文件(未实现)', - params: {}, - run: async () => { - return failedResponse(RETCODE.ACTION_FAILED, 'not yet implemented'); + summary: '转存群文件', + returns: '{ ok: true }', + params: { + group_id: f.uint(), + file_id: f.string({ allowEmpty: false }), + }, + run: async (p, ctx) => { + await ctx.bridge.apis.groupFile.trans(p.group_id, p.file_id); + return okResponse({ ok: true }); }, }), diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index a1cee2e5..68e3594d 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -641,6 +641,31 @@ describe('extended-actions / get_group_shut_list', () => { }); }); +// ─── Wave 1: trans_group_file (0x6D9_0) ─── + +describe('extended-actions / trans_group_file', () => { + it('forwards group_id + file_id to apis.groupFile.trans and returns ok:true', async () => { + const trans = vi.fn(async () => ({ saveBusId: 102, saveFilePath: '/saved/path' })); + const bridge = fakeBridge({ apis: { groupFile: { trans } } }); + const res = await makeHandler(fakeCtx(bridge)).handle('trans_group_file', { + group_id: 12345, + file_id: 'fid-trans', + }); + expect(trans).toHaveBeenCalledWith(12345, 'fid-trans'); + expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { ok: true } }); + }); + + it('rejects missing required params', async () => { + const trans = vi.fn(); + const bridge = fakeBridge({ apis: { groupFile: { trans } } }); + const r1 = await makeHandler(fakeCtx(bridge)).handle('trans_group_file', { file_id: 'fid' }); + const r2 = await makeHandler(fakeCtx(bridge)).handle('trans_group_file', { group_id: 12345 }); + expect(r1).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(r2).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(trans).not.toHaveBeenCalled(); + }); +}); + // ─── Wave 1: get_file (compose image→record cache) ─── describe('extended-actions / get_file', () => { diff --git a/packages/proto-defs/src/oidb-actions/group-file.ts b/packages/proto-defs/src/oidb-actions/group-file.ts index 007bb455..efa4b543 100644 --- a/packages/proto-defs/src/oidb-actions/group-file.ts +++ b/packages/proto-defs/src/oidb-actions/group-file.ts @@ -132,6 +132,19 @@ export interface OidbGroupFileResp { rename?: pb<5, OidbGroupFileRetResp>; move?: pb<6, OidbGroupFileRetResp>; } +export interface OidbGroupTransFileReq { + groupUin?: pb<1, uint_64>; + appId?: pb<2, uint_32>; + busId?: pb<3, uint_32>; + fileId?: pb<4, string>; +} +export interface OidbGroupTransFileResp { + retCode?: pb<1, int_32>; + retMsg?: pb<2, string>; + clientWording?: pb<3, string>; + saveBusId?: pb<4, uint_32>; + saveFilePath?: pb<5, string>; +} export interface OidbGroupSendFileInfo { busiType?: pb<1, uint_32>; fileId?: pb<2, string>; @@ -145,8 +158,12 @@ export interface OidbGroupSendFileBody { info?: pb<3, OidbGroupSendFileInfo>; } export interface OidbGroupSendFileReq { + transFile?: pb<1, OidbGroupTransFileReq>; body?: pb<5, OidbGroupSendFileBody>; } +export interface OidbGroupSendFileResp { + transFile?: pb<1, OidbGroupTransFileResp>; +} export interface OidbGroupFileCreateFolderReq { groupUin?: pb<1, uint_32>; rootDirectory?: pb<3, string>; diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 741295bb..2428f2ca 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -332,6 +332,10 @@ "types": "./src/oidb-services/group-file/publish-group-file.ts", "default": "./src/oidb-services/group-file/publish-group-file.ts" }, + "./oidb-services/group-file/trans-group-file": { + "types": "./src/oidb-services/group-file/trans-group-file.ts", + "default": "./src/oidb-services/group-file/trans-group-file.ts" + }, "./oidb-services/group-file/get-group-file-count": { "types": "./src/oidb-services/group-file/get-group-file-count.ts", "default": "./src/oidb-services/group-file/get-group-file-count.ts" diff --git a/packages/protocol/src/oidb-services/group-file/trans-group-file.ts b/packages/protocol/src/oidb-services/group-file/trans-group-file.ts new file mode 100644 index 00000000..d3f5fccd --- /dev/null +++ b/packages/protocol/src/oidb-services/group-file/trans-group-file.ts @@ -0,0 +1,52 @@ +// 0x6D9_0 — transfer a temporary group file into permanent group storage. +// Mirrors LagrangeV2's TransFileReqBody shape under the 0x6D9 family. + +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { + OidbGroupSendFileReq, + OidbGroupSendFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { ensureRetCodeZero, toInt } from '../shared'; + +export interface TransGroupFileResult { + saveBusId: number; + saveFilePath: string; +} + +export namespace TransGroupFile { + export const command = 0x6D9; + export const subCommand = 0; + + export interface Params { groupId: number; fileId: string; } + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): OidbGroupSendFileReq => ({ + transFile: { + groupUin: BigInt(p.groupId), + appId: 7, + busId: 102, + fileId: p.fileId, + }, + }); + + export const deserialize = (_ctx: Deps, body: OidbGroupSendFileResp): TransGroupFileResult => { + const result = body.transFile; + if (!result) throw new Error('group file transfer response missing'); + ensureRetCodeZero('group file transfer', result.retCode, result.retMsg, result.clientWording); + return { + saveBusId: toInt(result.saveBusId), + saveFilePath: typeof result.saveFilePath === 'string' ? result.saveFilePath : '', + }; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = (deps: Deps, params: Params): Promise => + invokeOidb(deps, TransGroupFile, params); +} diff --git a/packages/protocol/tests/oidb-services/group-file/trans-group-file.test.ts b/packages/protocol/tests/oidb-services/group-file/trans-group-file.test.ts new file mode 100644 index 00000000..9a40069f --- /dev/null +++ b/packages/protocol/tests/oidb-services/group-file/trans-group-file.test.ts @@ -0,0 +1,52 @@ +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 { + OidbGroupSendFileReq, OidbGroupSendFileResp, +} from '@snowluma/proto-defs/oidb-actions/group-file'; +import type { SendPacketResult } from '@snowluma/common/packet-sender'; + +import { TransGroupFile } from '../../../src/oidb-services/group-file/trans-group-file'; + +function makeDeps(body?: OidbGroupSendFileResp) { + const responseData = body !== undefined + ? Buffer.from(protobuf_encode>({ body })) + : Buffer.alloc(0); + const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData }; + return { sendRawPacket: vi.fn(async () => r) }; +} + +describe('TransGroupFile namespace', () => { + it('declares 0x6D9_0', () => { + expect(TransGroupFile.command).toBe(0x6D9); + expect(TransGroupFile.subCommand).toBe(0); + }); + + it('packages group + file id under the transFile slot', async () => { + const deps = makeDeps({ transFile: { saveBusId: 102, saveFilePath: '/abc' } }); + const out = await TransGroupFile.invoke(deps, { groupId: 12345, fileId: 'fid' }); + expect(out).toEqual({ saveBusId: 102, saveFilePath: '/abc' }); + expect(deps.sendRawPacket).toHaveBeenCalledOnce(); + const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!; + expect(wire).toBe('OidbSvcTrpcTcp.0x6d9_0'); + const env = protobuf_decode>(bytes); + expect(env.body?.transFile).toEqual({ + groupUin: 12345n, + appId: 7, + busId: 102, + fileId: 'fid', + }); + }); + + it('throws on missing transFile sub-message', async () => { + const deps = makeDeps({}); + await expect(TransGroupFile.invoke(deps, { groupId: 1, fileId: 'f' })) + .rejects.toThrow(/transfer response missing/); + }); + + it('throws on non-zero retCode', async () => { + const deps = makeDeps({ transFile: { retCode: 7, retMsg: 'denied' } }); + await expect(TransGroupFile.invoke(deps, { groupId: 1, fileId: 'f' })) + .rejects.toThrow(/code=7/); + }); +}); From 5d6ce86b66175782bb6ce3392d16c9a4eedf2ac1 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 02:27:35 +0800 Subject: [PATCH 05/30] refactor(onebot): give trans_group_file semantic param roles Follow-up to #161: trans_group_file's group_id/file_id used plain f.uint()/f.string(); switch them to f.groupId()/f.fileId() (identical coercion) so the WebUI debug console renders a group picker + file-id control for the new action and the catalog carries the roles. Catalog regenerated. --- packages/mcp/src/generated/catalog.json | 8 ++++++-- packages/mcp/src/generated/catalog.ts | 8 ++++++-- packages/onebot/src/actions/extended.ts | 4 ++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index b6972a28..931ebc36 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -9102,6 +9102,7 @@ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -9111,6 +9112,7 @@ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -9123,11 +9125,13 @@ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" } }, "required": [ diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 5d2c9e26..66b59332 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -9105,6 +9105,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "group_id", "type": "uint", "required": true, + "role": "group_id", "schema": { "type": "integer", "minimum": 1 @@ -9114,6 +9115,7 @@ export const ACTIONS: CatalogAction[] = [ "name": "file_id", "type": "string", "required": true, + "role": "file_id", "schema": { "type": "string", "minLength": 1 @@ -9126,11 +9128,13 @@ export const ACTIONS: CatalogAction[] = [ "properties": { "group_id": { "type": "integer", - "minimum": 1 + "minimum": 1, + "x-role": "group_id" }, "file_id": { "type": "string", - "minLength": 1 + "minLength": 1, + "x-role": "file_id" } }, "required": [ diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 20ca9ece..dac7af9d 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1639,8 +1639,8 @@ export const actions = [ summary: '转存群文件', returns: '{ ok: true }', params: { - group_id: f.uint(), - file_id: f.string({ allowEmpty: false }), + group_id: f.groupId(), + file_id: f.fileId(), }, run: async (p, ctx) => { await ctx.bridge.apis.groupFile.trans(p.group_id, p.file_id); From f4244544229f1bd3c5ef8e2e219529709d0d8d63 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=9B=A7=E5=9B=A7JOJO?= <58727904+jiongjiongJOJO@users.noreply.github.com> Date: Wed, 1 Jul 2026 14:43:29 +0800 Subject: [PATCH 06/30] fix(webui): align debug account picker styling (#181) --- .../src/components/debug/action-tester.tsx | 30 +++++++++++++++---- packages/webui/src/components/ui/picker.tsx | 15 ++++++++-- 2 files changed, 38 insertions(+), 7 deletions(-) diff --git a/packages/webui/src/components/debug/action-tester.tsx b/packages/webui/src/components/debug/action-tester.tsx index fd7916db..a463d8ee 100644 --- a/packages/webui/src/components/debug/action-tester.tsx +++ b/packages/webui/src/components/debug/action-tester.tsx @@ -8,7 +8,6 @@ import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'; import { motion } from 'motion/react'; import { AlertTriangle, FlaskConical, History, Loader2, Play, RotateCcw, ShieldCheck, Trash2, Zap } from 'lucide-react'; -import { Select } from '@/components/ui/select'; import { Textarea } from '@/components/ui/textarea'; import { Picker } from '@/components/ui/picker'; import { JsonTree } from '@/components/ui/json-tree'; @@ -27,6 +26,10 @@ const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2p // stakes (the amber banner already warns that any write is real). const DESTRUCTIVE_RE = /(kick|ban|mute|recall|withdraw|delete|del_|dismiss|disband|leave|quit|remove|revoke)/i; +function qqAvatarUrl(uin: string) { + return `/avatar/${encodeURIComponent(uin)}`; +} + function coerceParam(type: string, raw: string): unknown { if (raw === '') return undefined; if (/int|uint|number|messageId/i.test(type)) { @@ -82,6 +85,18 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf const isStream = !!doc?.stream; const isDestructive = DESTRUCTIVE_RE.test(actionName); + const accountOptions = useMemo( + () => accounts.length === 0 + ? [{ value: '', label: '(无在线账号)' }] + : accounts.map((a) => ({ + value: a.uin, + label: a.nickname || a.uin, + sub: a.nickname ? a.uin : undefined, + avatar: qqAvatarUrl(a.uin), + })), + [accounts], + ); + const actionOptions = useMemo( () => docs.map((d) => ({ value: d.name, label: d.name, sub: d.summary })), [docs], @@ -201,10 +216,15 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
- + false} + disabled={accounts.length === 0} + /> (null); const listRef = useRef(null); const searchRef = useRef(null); + const suppressTriggerClick = useRef(false); const selected = options.find((o) => o.value === value); @@ -124,7 +125,13 @@ export function Picker({ aria-label={ariaLabel} aria-haspopup="listbox" aria-expanded={open} - onClick={() => !disabled && setOpen((v) => !v)} + onClick={() => { + if (suppressTriggerClick.current) { + suppressTriggerClick.current = false; + return; + } + if (!disabled) setOpen((v) => !v); + }} className={cn( 'flex h-9 w-full items-center gap-2 rounded-md border border-border bg-transparent px-3 text-sm outline-none transition-colors', 'focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring disabled:opacity-50', @@ -196,7 +203,11 @@ export function Picker({ role="option" aria-selected={idx === active} onMouseEnter={() => setActive(idx)} - onClick={() => choose(idx)} + onPointerDown={(e) => { + e.preventDefault(); + suppressTriggerClick.current = true; + choose(idx); + }} className={cn( 'absolute left-0 right-0 flex cursor-pointer items-center gap-2.5 px-3', idx === active ? 'bg-accent text-accent-foreground' : 'hover:bg-accent/50', From f4170b014aa1b22cf93a0e054209b002a6f4ec29 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 15:35:12 +0800 Subject: [PATCH 07/30] refactor(protocol,onebot): add message-element four-direction reconciliation manifest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 消息元素散在 4 处派发(收·解 / 收·转 / 发·解 / 发·打包),历史上各写各的、 无对账,导致字段名对不上、漏写方向走 default 静默失败。 阶段 1(零行为改动):立一份权威清单 element-manifest + 两道架构护栏测试。 - element-manifest.ts:每种元素类型 × 四向支持('yes'/'no'/'by-design-no') + 字段契约 + typesForDirection() + 输入糖白名单。清单逐字反映当前行为。 - 两道对账测试(因包边界拆两处、共用清单):正则扫 4 处派发代码,比对清单。 谁增删一个方向却不同步清单,测试当场报红,不再运行时静默。 - 取值域用 [A-Za-z0-9_]+,避免未来驼峰/下划线类型名被静默漏抓致护栏失效。 - poke 的 W=by-design-no:QQ 不允许戳一戳当消息段发送,缺席正确。 对抗性 Agent 两轮复审通过。 --- .../onebot/tests/element-manifest.test.ts | 50 +++++++ packages/protocol/package.json | 4 + packages/protocol/src/element-manifest.ts | 137 ++++++++++++++++++ .../protocol/tests/element-manifest.test.ts | 50 +++++++ 4 files changed, 241 insertions(+) create mode 100644 packages/onebot/tests/element-manifest.test.ts create mode 100644 packages/protocol/src/element-manifest.ts create mode 100644 packages/protocol/tests/element-manifest.test.ts diff --git a/packages/onebot/tests/element-manifest.test.ts b/packages/onebot/tests/element-manifest.test.ts new file mode 100644 index 00000000..b9af9f7e --- /dev/null +++ b/packages/onebot/tests/element-manifest.test.ts @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { + typesForDirection, + INPUT_SUGAR_SEGMENTS, +} from '@snowluma/protocol/element-manifest'; + +// 对账测试(onebot 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的两个 +// onebot 方向: +// S 收·转 to-segment.ts 的 `element.type === 'X'` 分支集合 +// P 发·解 message-parser.ts 的 `case 'X'` 分支集合(剔除纯输入糖) +// protocol 侧的 D/W 由 protocol/tests/element-manifest.test.ts 核对(包边界所限)。 +// +// 架构护栏:谁在这两处增删一种元素方向却没同步 element-manifest,测试当场报红。 +// 纯读源码、零运行时行为改动。 + +function readSrc(relFromTestDir: string): string { + const abs = fileURLToPath(new URL(relFromTestDir, import.meta.url)); + const raw = readFileSync(abs, 'utf8'); + return raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); +} + +function extractTypes(src: string, pattern: RegExp): string[] { + const found = new Set(); + for (const m of src.matchAll(pattern)) found.add(m[1]!); + return [...found].sort(); +} + +const sorted = (s: Iterable): string[] => [...s].sort(); + +describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', () => { + it('S:to-segment 的 element.type 分支 == 清单声明的 S=yes', () => { + const src = readSrc('../src/event-converter/to-segment.ts'); + const handled = extractTypes(src, /element\.type\s*===\s*'([A-Za-z0-9_]+)'/g); + expect(handled).toEqual(sorted(typesForDirection('S'))); + }); + + it('P:message-parser 的 case 分支(剔除输入糖)== 清单声明的 P=yes', () => { + const src = readSrc('../src/message-parser.ts'); + // 值域放宽到 `[A-Za-z0-9_]+`:见 protocol/tests/element-manifest.test.ts 同处说明。 + const allCases = extractTypes(src, /case\s*'([A-Za-z0-9_]+)'\s*:/g); + const realElementCases = allCases.filter((t) => !INPUT_SUGAR_SEGMENTS.has(t)); + expect(realElementCases).toEqual(sorted(typesForDirection('P'))); + + // 输入糖必须确实出现在 message-parser 里(否则白名单与代码脱节)。 + const sugarPresent = allCases.filter((t) => INPUT_SUGAR_SEGMENTS.has(t)).sort(); + expect(sugarPresent).toEqual(sorted(INPUT_SUGAR_SEGMENTS)); + }); +}); diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 2428f2ca..8f174814 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -32,6 +32,10 @@ "types": "./src/element-builder.ts", "default": "./src/element-builder.ts" }, + "./element-manifest": { + "types": "./src/element-manifest.ts", + "default": "./src/element-manifest.ts" + }, "./bridge-oidb": { "types": "./src/bridge-oidb.ts", "default": "./src/bridge-oidb.ts" diff --git a/packages/protocol/src/element-manifest.ts b/packages/protocol/src/element-manifest.ts new file mode 100644 index 00000000..20093637 --- /dev/null +++ b/packages/protocol/src/element-manifest.ts @@ -0,0 +1,137 @@ +/** + * 消息元素「四向」对账清单 —— 单一权威。 + * + * 一种消息元素(文字/图片/戳一戳/商城表情…)要在两个流向、共 4 处处理,散在 + * 不同文件、不同包。历史上这 4 处各写各的、没人对账,导致字段名对不上、漏写 + * 方向无人知(都走运行时兜底 `default`,悄悄失败)。 + * + * 本清单声明「每种元素类型应支持哪几个方向」,配套的两道对账测试 + * (`protocol/tests/element-manifest.test.ts` 与 `onebot/tests/element-manifest.test.ts`, + * 因包边界拆两处、共用本清单)拿它逐一核对那 4 处代码 —— 漏写或多写一个方向 + * 立即报红,而不再是运行时静默。 + * + * 四个方向: + * D 收·解 QQ 原始数据 → MessageElement `protocol/msg-push/rich-body-decoder.ts` + * S 收·转 MessageElement → OneBot 段 `onebot/event-converter/to-segment.ts` + * P 发·解 OneBot 段 → MessageElement `onebot/message-parser.ts` + * W 发·打包 MessageElement → QQ 原始数据 `protocol/element-builder.ts` + * + * 注:D(收·解)按 proto 字段分派、一字段可扇出多种元素、多字段可收敛为一种, + * 与另外三个「按 element.type 分派」的方向异构,故它保持独立开关、不进 onebot + * 侧的合并表;但它产出的元素类型集合仍受本清单核对。 + * + * 取值语义: + * 'yes' 该方向有对应处理。 + * 'no' 该方向暂无(记录在案的缺口,本次重构不补,另立任务再议)。 + * 'by-design-no' 该方向按设计不支持(QQ 协议限制),缺席是正确的。 + */ + +export const ELEMENT_DIRECTIONS = ['D', 'S', 'P', 'W'] as const; +export type ElementDirection = (typeof ELEMENT_DIRECTIONS)[number]; + +export type DirectionSupport = 'yes' | 'no' | 'by-design-no'; + +export interface ElementSpec { + /** 每个方向的支持状态。 */ + readonly directions: Readonly>; + /** + * 该元素类型在 `MessageElement` 上「属于自己」的字段 —— 字段契约的文档基准, + * 供各方向读写时对齐(例如 poke 统一用 `subType`,不再收侧 `subType` / 发侧 + * `faceId` 打架)。当前为文档性声明,字段级强制留待后续阶段。 + */ + readonly fields: readonly string[]; + /** 备注:媒体上传、三角映射、协议限制等需要跨方向知道的事。 */ + readonly note?: string; +} + +/** + * 全部规范元素类型 × 四向支持。此表须与那 4 处派发代码逐字一致,否则对账测试报红。 + */ +export const ELEMENT_MANIFEST = { + text: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['text'], + }, + at: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['targetUin', 'uid', 'text'], + }, + face: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['faceId'], + }, + reply: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['replySeq', 'replyMessageId', 'replySenderUin', 'replyTime', 'replyRandom', 'replyElements'], + }, + json: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['text'], + }, + xml: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['text', 'subType'], + }, + forward: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['resId', 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardNews', 'forwardTSum', 'forwardUuid'], + }, + image: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['imageUrl', 'fileId', 'fileName', 'fileSize', 'url', 'subType', 'summary', 'width', 'height', 'flash', 'md5Hex', 'sha1Hex', 'picFormat', 'noByteFallback', 'mediaNode'], + note: 'media:W(打包)经 highway 上传、异步,需 SendContext', + }, + record: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['fileName', 'fileId', 'url', 'duration', 'fileSize', 'md5Hex', 'sha1Hex', 'voiceFormat', 'noByteFallback', 'mediaNode'], + note: 'media', + }, + video: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['fileName', 'fileId', 'url', 'thumbUrl', 'thumbFileId', 'duration', 'width', 'height', 'fileSize', 'md5Hex', 'sha1Hex', 'videoFormat', 'noByteFallback', 'mediaNode'], + note: 'media', + }, + mface: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['emojiId', 'emojiPackageId', 'emojiKey', 'text', 'summary'], + note: '商城表情三角:S(转 OneBot)输出 image 段并挂 emoji_id/emoji_package_id/key 标记,P(解)再从该 image 段认回', + }, + file: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, + fields: ['fileId', 'thumbFileId', 'fileName', 'fileSize', 'url', 'fileHash', 'md5Hex', 'sha1Hex', 'resId'], + note: 'W 特殊:live-send 在 OneBot 层被拆走走独立上传管线,仅 forwardFake 时落 transElem(24)', + }, + poke: { + directions: { D: 'yes', S: 'yes', P: 'yes', W: 'by-design-no' }, + fields: ['subType'], + note: 'QQ 不允许戳一戳当消息段发送,故 W(打包)按设计不支持;戳一戳作为独立动作走 OIDB send-poke,与本表无关。字段契约以收侧既有 subType 为准', + }, + markdown: { + directions: { D: 'no', S: 'no', P: 'yes', W: 'yes' }, + fields: ['text'], + note: '收侧(D/S)无对应,仅发送方向存在', + }, +} as const satisfies Record; + +export type ElementType = keyof typeof ELEMENT_MANIFEST; + +/** + * 某方向应被处理的元素类型集合(`directions[dir] === 'yes'`)—— 对账测试的基准。 + */ +export function typesForDirection(dir: ElementDirection): Set { + const out = new Set(); + for (const [type, spec] of Object.entries(ELEMENT_MANIFEST)) { + if (spec.directions[dir] === 'yes') out.add(type); + } + return out; +} + +/** + * 发·解(P)侧还接收一批「纯 OneBot 输入糖」:它们不是某种真实消息元素,只是被 + * 塌缩成 json / face / poke 的输入便利(如骰子、猜拳、位置/音乐/名片分享、转发 + * node、匿名标记),没有收侧对应,也没有专属的 wire 形态,故不进本清单。对账 P + * 时须先从代码里剔除这些类型。 + */ +export const INPUT_SUGAR_SEGMENTS: ReadonlySet = new Set([ + 'node', 'share', 'music', 'location', 'contact', 'rps', 'dice', 'shake', 'anonymous', +]); diff --git a/packages/protocol/tests/element-manifest.test.ts b/packages/protocol/tests/element-manifest.test.ts new file mode 100644 index 00000000..4fbd7742 --- /dev/null +++ b/packages/protocol/tests/element-manifest.test.ts @@ -0,0 +1,50 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { typesForDirection } from '../src/element-manifest'; + +// 对账测试(protocol 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的 +// 两个 protocol 方向: +// D 收·解 rich-body-decoder.ts 产出的 MessageElement 类型集合 +// W 发·打包 element-builder.ts 的 switch 分支集合 +// onebot 侧的 S/P 由 onebot/tests/element-manifest.test.ts 核对(包边界所限)。 +// +// 这是一道架构护栏(fitness function):谁在这两处新增/删除一种元素方向,却没有 +//同步更新 element-manifest,测试立即报红——把「漏写一个方向」从运行时兜底静默 +// 变成 CI 当场可见。纯读源码、零运行时行为改动。 + +function readSrc(relFromTestDir: string): string { + const abs = fileURLToPath(new URL(relFromTestDir, import.meta.url)); + const raw = readFileSync(abs, 'utf8'); + // 剥掉块注释与行注释,避免注释里出现的类型字面量污染扫描结果。 + return raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); +} + +/** 抽出所有匹配 `pattern` 第 1 捕获组的去重、排序类型名。 */ +function extractTypes(src: string, pattern: RegExp): string[] { + const found = new Set(); + for (const m of src.matchAll(pattern)) found.add(m[1]!); + return [...found].sort(); +} + +const sorted = (s: Iterable): string[] => [...s].sort(); + +describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)', () => { + it('D:rich-body-decoder 产出的元素类型 == 清单声明的 D=yes', () => { + const src = readSrc('../src/msg-push/rich-body-decoder.ts'); + // 解码产出形如 `result.push({ type: 'image', ... })` / `{ type: 'reply', ... }`。 + // 值域放宽到 `[A-Za-z0-9_]+`(而非仅小写):类型名当前虽全小写,但收紧到 + // `[a-z]+` 会让未来的驼峰/下划线类型名被静默漏抓,护栏就形同虚设——正是本 + // 重构要消灭的"漏一个方向、走 default 静默"失效模式,不能在护栏自身重演。 + const handled = extractTypes(src, /(? { + const src = readSrc('../src/element-builder.ts'); + const handled = extractTypes(src, /case\s*'([A-Za-z0-9_]+)'\s*:/g); + // poke 按设计不支持发送(QQ 限制),element-builder 必须没有 poke 分支。 + expect(handled).not.toContain('poke'); + expect(handled).toEqual(sorted(typesForDirection('W'))); + }); +}); From 8e173cf7d731f2ddfeff35367beb8df2c9cbbf7c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 15:47:33 +0800 Subject: [PATCH 08/30] refactor(onebot): merge element toSegment/fromSegment into one codec table MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 2(零行为改动):把「同一种消息元素」的两个 onebot 方向——收·转 (to-segment) 与 发·解(message-parser)——从两个文件各写各的分支,合并到一张 按元素类型索引的 ELEMENT_CODECS 表,每种类型一条 { toSegment?, fromSegment? }。 - 新增 event-converter/element-codecs.ts:13 类 toSegment + 14 类 fromSegment 逐字平移自原实现;私有 helper intOr/marketFaceElement/pickMediaSource 移来并导出。 - to-segment.ts:elementToSegment 改查表 + 保留原 default 透传兜底。 - message-parser.ts:segmentToElement 保留 9 个纯输入糖 case 作前置 normalize, 真实类型改查表,末尾保留原 unsupported warn。 - onebot 对账测试升级为按表键核对 S/P(比正则更硬),并断言真实类型 case 不再 残留于 parser、输入糖仍在。 行为 byte 级不变:onebot 全量 513 全绿、typecheck 干净;对抗性 Agent 逐字比对 确认无漂移、无运行时循环依赖。 --- .../src/event-converter/element-codecs.ts | 409 ++++++++++++++++++ .../onebot/src/event-converter/to-segment.ts | 143 +----- packages/onebot/src/message-parser.ts | 212 +-------- .../onebot/tests/element-manifest.test.ts | 58 +-- 4 files changed, 465 insertions(+), 357 deletions(-) create mode 100644 packages/onebot/src/event-converter/element-codecs.ts diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts new file mode 100644 index 00000000..2ed88ee1 --- /dev/null +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -0,0 +1,409 @@ +import { createLogger } from '@snowluma/common/logger'; +import type { MessageElement } from '@snowluma/protocol/events'; +import type { JsonObject } from '../types'; +import type { ParseMessageOptions } from '../message-parser'; +import type { + ImageUrlResolver, + MediaUrlResolver, + MessageIdResolver, + MediaSegmentSink, +} from './index'; +import { resolveReplyId } from './utils'; + +// ───────────────────────────────────────────────────────────────────────── +// 消息元素 codec 表(onebot 侧)—— 把「同一种元素」的两个 onebot 方向并到一处: +// S 收·转 toSegment MessageElement → OneBot 段 +// P 发·解 fromSegment OneBot 段 → MessageElement +// 历史上这两向分散在 to-segment.ts 与 message-parser.ts、各写各的,容易一起漂。 +// 现在每种元素类型一条 { toSegment?, fromSegment? } 条目,谁少写一向一眼可见, +// 并由 element-manifest 对账测试(onebot 侧)拿本表的键去核对清单。 +// +// 第 1 步(收·解,proto 字段分派、异构)与第 4 步(发·打包,protocol 包)不在本表, +// 见 element-manifest.ts 的说明。纯 OneBot 输入糖(骰子/分享/…)也不进表,留在 +// message-parser 当前置 normalize。 +// +// 行为对 to-segment / message-parser 的原实现 byte 级不变——仅把分支体平移到此。 +// ───────────────────────────────────────────────────────────────────────── + +const log = createLogger('MsgParser'); + +/** toSegment(S 收·转)所需的上下文:会话信息 + 各类 URL/媒体解析器。 */ +export interface ToSegmentContext { + isGroup: boolean; + sessionId: number; + imageUrlResolver?: ImageUrlResolver | null; + mediaUrlResolver?: MediaUrlResolver | null; + messageIdResolver?: MessageIdResolver | null; + mediaSegmentSink?: MediaSegmentSink | null; +} + +export interface ElementCodec { + /** S 收·转:MessageElement → OneBot 段。 */ + toSegment?: (element: MessageElement, ctx: ToSegmentContext) => Promise; + /** P 发·解:OneBot 段 data → MessageElement(null = 丢弃该段)。 */ + fromSegment?: (data: Record, options?: ParseMessageOptions) => Promise; +} + +// ── 共享低层工具(原在 message-parser,移来供本表与 message-parser 的输入糖共用)── + +export function intOr(value: unknown, fallback = 0): number { + if (value === undefined || value === null) return fallback; + if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback; + const n = parseInt(String(value), 10); + return Number.isFinite(n) ? n : fallback; +} + +/** Build a market-face (`mface`) element from an OneBot segment's data. + * Shared by the dedicated `mface` segment and the `image`-with-`emoji_id` + * round-trip path. `emojiId` is the hex GUID the wire builder converts back + * to `MarketFace.faceId`. */ +export function marketFaceElement(emojiId: string, data: Record): MessageElement { + return { + type: 'mface', + text: String(data.summary ?? data.name ?? ''), + emojiId, + emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0), + emojiKey: String(data.key ?? ''), + }; +} + +/** + * Pick the best loadable source from a media segment's `file` / `url` / `path` + * / `media` fields. + * + * `file` is normally the canonical OneBot field and wins, but it can also be a + * QQ-internal media id (e.g. `.png`) that this process cannot resolve to a + * local path. When a bot framework echoes a received image back (Yunzai et al. + * resend the original `file=.ext` together with the download `url`), using + * `file` makes the send path `statSync` the id as a bogus local path and throw + * `ENOENT`. So: keep `file` when it is a directly loadable source (inline + * bytes, a remote url, or a filesystem path with a separator); otherwise, if a + * real http(s) `url` accompanies it, prefer that. (issue #155) + */ +export function pickMediaSource(data: Record): string { + const file = String(data.file ?? '').trim(); + const url = String(data.url ?? '').trim(); + const fallback = file || url || String(data.path ?? '').trim() || String(data.media ?? '').trim(); + if (!file) return fallback; + // `file` is itself loadable: inline bytes, a remote url, or a path (anything + // carrying a `/` or `\` separator, incl. file:// and absolute/relative paths). + if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file; + // `file` is a bare token (QQ-internal id) — fall back to a real url if present. + if (/^https?:\/\//i.test(url)) return url; + return fallback; +} + +// ── codec 表:一种元素类型一条,键即 element.type(收·转)/ 段 type(发·解,二者同名)── + +export const ELEMENT_CODECS: Record = { + text: { + async toSegment(element) { + return { type: 'text', data: { text: element.text ?? '' } }; + }, + async fromSegment(data) { + const text = String(data.text ?? ''); + return text ? { type: 'text', text } : null; + }, + }, + + face: { + async toSegment(element) { + return { type: 'face', data: { id: String(element.faceId ?? 0) } }; + }, + async fromSegment(data) { + const id = intOr(data.id, -1); + if (id < 0) return null; + return { type: 'face', faceId: id }; + }, + }, + + at: { + async toSegment(element) { + const qq = (element.uid === 'all' || element.targetUin === 0) + ? 'all' + : String(element.targetUin ?? 0); + return { type: 'at', data: { qq } }; + }, + async fromSegment(data, options) { + const qq = String(data.qq ?? '').trim(); + if (qq === 'all') { + return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' }; + } + const uin = intOr(qq, 0); + if (uin <= 0) return null; + + const name = String(data.name ?? data.nickname ?? data.card ?? '').trim(); + let uid = String(data.uid ?? '').trim(); + if (!uid && options?.resolveMentionUid) { + uid = (await options.resolveMentionUid(uin))?.trim() ?? ''; + } + const element: MessageElement = { type: 'at', targetUin: uin }; + if (uid) element.uid = uid; + if (name) element.text = `@${name} `; + return element; + }, + }, + + reply: { + async toSegment(element, ctx) { + const id = resolveReplyId(ctx.isGroup, ctx.sessionId, element.replySeq ?? 0, ctx.messageIdResolver); + return { type: 'reply', data: { id: String(id) } }; + }, + async fromSegment(data, options) { + const id = intOr(data.id, 0); + if (id === 0) return null; + + if (options?.resolveReplySequence) { + const resolved = options.resolveReplySequence(id); + if (typeof resolved === 'number' && resolved > 0) { + const element: MessageElement = { + type: 'reply', + replySeq: resolved, + replyMessageId: id // Keep the original messageId for logging + }; + + // Try to get additional meta info for better reply display + if (options?.resolveReplyMeta) { + const meta = options.resolveReplyMeta(id); + if (meta) { + element.replySenderUin = meta.senderUin; + element.replyTime = meta.time; + element.replyRandom = meta.random; + } + } + + return element; + } + } + + // Backward-compatible path: allow direct seq reply IDs. + return id > 0 ? { type: 'reply', replySeq: id } : null; + }, + }, + + image: { + async toSegment(element, ctx) { + const url = ctx.imageUrlResolver ? await ctx.imageUrlResolver(element, ctx.isGroup) : (element.imageUrl ?? ''); + const data: JsonObject = { + url, + file: element.fileId ?? '', + sub_type: element.subType ?? 0, + summary: element.summary ?? '', + }; + if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId); + return { type: 'image', data }; + }, + async fromSegment(data) { + // A market face that was surfaced as an `image` (see toSegment) can be + // echoed straight back: when `emoji_id` is present we rebuild the market + // face instead of re-uploading the gif as a plain picture. + const imgEmojiId = String(data.emoji_id ?? '').trim(); + if (imgEmojiId) return marketFaceElement(imgEmojiId, data); + return { + type: 'image', + url: pickMediaSource(data), + flash: data.type === 'flash', + subType: intOr(data.subType, 0), + summary: data.summary ? String(data.summary) : undefined, + }; + }, + }, + + record: { + async toSegment(element, ctx) { + const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? ''); + const data: JsonObject = { + file: element.fileName ?? element.fileId ?? '', + url, + }; + if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('record', element, data, ctx.isGroup, ctx.sessionId); + return { type: 'record', data }; + }, + async fromSegment(data) { + const source = pickMediaSource(data); + if (!source) return null; + return { + type: 'record', + url: source, + }; + }, + }, + + video: { + async toSegment(element, ctx) { + const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? ''); + const data: JsonObject = { + file: element.fileName ?? element.fileId ?? '', + url, + }; + if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('video', element, data, ctx.isGroup, ctx.sessionId); + return { type: 'video', data }; + }, + async fromSegment(data) { + const source = pickMediaSource(data); + if (!source) return null; + return { + type: 'video', + url: source, + thumbUrl: data.thumb ? String(data.thumb) : undefined, + }; + }, + }, + + json: { + async toSegment(element) { + return { type: 'json', data: { data: element.text ?? '' } }; + }, + async fromSegment(data) { + return { + type: 'json', + text: String(data.data ?? ''), + }; + }, + }, + + xml: { + async toSegment(element) { + return { + type: 'xml', + data: { + data: element.text ?? '', + resid: element.subType ?? 35, + }, + }; + }, + async fromSegment(data) { + return { + type: 'xml', + text: String(data.data ?? ''), + subType: intOr(data.id, 0), + }; + }, + }, + + file: { + async toSegment(element, ctx) { + const url = ctx.mediaUrlResolver ? await ctx.mediaUrlResolver(element, ctx.isGroup, ctx.sessionId) : (element.url ?? ''); + const fileName = element.fileName ?? ''; + const fileSize = element.fileSize ?? 0; + const fileId = element.fileId ?? ''; + return { + type: 'file', + data: { + // NapCat/LLOneBot-style canonical fields — most downstream + // OneBot adapters read these (`file`/`file_id`/`file_size`). + file: fileName, + file_id: fileId, + file_size: fileSize, + // Legacy SnowLuma field names, kept for backward compat with + // any consumer that already reads name/size/id. + name: fileName, + size: fileSize, + id: fileId, + url, + file_hash: element.fileHash ?? '', + }, + }; + }, + async fromSegment(data) { + const fileId = String(data.file_id ?? data.fileId ?? '').trim(); + const source = String(data.file ?? data.url ?? data.path ?? '').trim(); + if (!fileId && !source) { + log.warn('[MsgParser] file segment without file_id or file/url is unsupported'); + return null; + } + const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim(); + const fileSize = intOr(data.size ?? data.fileSize, 0); + const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim(); + const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim(); + const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim(); + const elem: MessageElement = fileId ? { type: 'file', fileId } : { type: 'file', url: source }; + if (fileName) elem.fileName = fileName; + if (fileSize > 0) elem.fileSize = fileSize; + if (md5Hex) elem.md5Hex = md5Hex; + if (sha1Hex) elem.sha1Hex = sha1Hex; + if (fileHash) elem.fileHash = fileHash; + return elem; + }, + }, + + mface: { + async toSegment(element) { + // Unify market faces (商城表情) to an `image` segment so OneBot clients + // that don't special-case `mface` still render the sticker, while the + // `emoji_id`/`emoji_package_id`/`key` markers let aware clients (and our + // own send path) reproduce it as a real market face. Mirrors NapCat's + // marketFaceElement → image conversion. The gxh URL is a self-contained + // external link (no rkey), so we set it directly and skip mediaSegmentSink. + const emojiId = element.emojiId ?? ''; + const dir = emojiId.slice(0, 2); + const url = emojiId + ? `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif` + : ''; + return { + type: 'image', + data: { + file: emojiId ? `${dir}-${emojiId}.gif` : '', + url, + summary: element.text ?? '', + sub_type: 0, + emoji_id: emojiId, + emoji_package_id: element.emojiPackageId ?? 0, + key: element.emojiKey ?? '', + }, + }; + }, + async fromSegment(data) { + // Market face (商城表情). emoji_id is the hex GUID; without it we can't + // construct the wire element, so drop the segment. + const emojiId = String(data.emoji_id ?? '').trim(); + if (!emojiId) { + log.warn('[MsgParser] mface segment without emoji_id is unsupported'); + return null; + } + return marketFaceElement(emojiId, data); + }, + }, + + poke: { + async toSegment(element) { + return { + type: 'poke', + data: { + type: element.subType ?? 0, + }, + }; + }, + async fromSegment(data) { + return { + type: 'poke', + faceId: intOr(data.type ?? data.id, 0), + }; + }, + }, + + forward: { + async toSegment(element) { + return { + type: 'forward', + data: { id: element.resId ?? '' }, + }; + }, + async fromSegment(data) { + return { + type: 'forward', + resId: String(data.id ?? ''), + }; + }, + }, + + markdown: { + // 收侧(S)无对应,仅发·解存在。 + async fromSegment(data) { + return { + type: 'markdown', + text: String(data.content ?? ''), + }; + }, + }, +}; diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index db5bc33d..80199630 100644 --- a/packages/onebot/src/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -6,7 +6,7 @@ import type { MediaUrlResolver, MessageIdResolver, } from './index'; -import { resolveReplyId } from './utils'; +import { ELEMENT_CODECS } from './element-codecs'; import { createLogger } from '@snowluma/common/logger'; const log = createLogger('OneBot'); @@ -46,136 +46,17 @@ async function elementToSegment( messageIdResolver?: MessageIdResolver | null, mediaSegmentSink?: MediaSegmentSink | null, ): Promise { - if (element.type === 'text') { - return { type: 'text', data: { text: element.text ?? '' } }; - } - - if (element.type === 'face') { - return { type: 'face', data: { id: String(element.faceId ?? 0) } }; - } - - if (element.type === 'image') { - const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? ''); - const data: JsonObject = { - url, - file: element.fileId ?? '', - sub_type: element.subType ?? 0, - summary: element.summary ?? '', - }; - if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId); - return { type: 'image', data }; - } - - if (element.type === 'at') { - const qq = (element.uid === 'all' || element.targetUin === 0) - ? 'all' - : String(element.targetUin ?? 0); - return { type: 'at', data: { qq } }; - } - - if (element.type === 'reply') { - const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver); - return { type: 'reply', data: { id: String(id) } }; - } - - if (element.type === 'record') { - const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? ''); - const data: JsonObject = { - file: element.fileName ?? element.fileId ?? '', - url, - }; - if (mediaSegmentSink) mediaSegmentSink('record', element, data, isGroup, sessionId); - return { type: 'record', data }; - } - - if (element.type === 'video') { - const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? ''); - const data: JsonObject = { - file: element.fileName ?? element.fileId ?? '', - url, - }; - if (mediaSegmentSink) mediaSegmentSink('video', element, data, isGroup, sessionId); - return { type: 'video', data }; - } - - if (element.type === 'json') { - return { type: 'json', data: { data: element.text ?? '' } }; - } - - if (element.type === 'xml') { - return { - type: 'xml', - data: { - data: element.text ?? '', - resid: element.subType ?? 35, - }, - }; - } - - if (element.type === 'file') { - const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? ''); - const fileName = element.fileName ?? ''; - const fileSize = element.fileSize ?? 0; - const fileId = element.fileId ?? ''; - return { - type: 'file', - data: { - // NapCat/LLOneBot-style canonical fields — most downstream - // OneBot adapters read these (`file`/`file_id`/`file_size`). - file: fileName, - file_id: fileId, - file_size: fileSize, - // Legacy SnowLuma field names, kept for backward compat with - // any consumer that already reads name/size/id. - name: fileName, - size: fileSize, - id: fileId, - url, - file_hash: element.fileHash ?? '', - }, - }; - } - - if (element.type === 'mface') { - // Unify market faces (商城表情) to an `image` segment so OneBot clients - // that don't special-case `mface` still render the sticker, while the - // `emoji_id`/`emoji_package_id`/`key` markers let aware clients (and our - // own send path) reproduce it as a real market face. Mirrors NapCat's - // marketFaceElement → image conversion. The gxh URL is a self-contained - // external link (no rkey), so we set it directly and skip mediaSegmentSink. - const emojiId = element.emojiId ?? ''; - const dir = emojiId.slice(0, 2); - const url = emojiId - ? `https://gxh.vip.qq.com/club/item/parcel/item/${dir}/${emojiId}/raw300.gif` - : ''; - return { - type: 'image', - data: { - file: emojiId ? `${dir}-${emojiId}.gif` : '', - url, - summary: element.text ?? '', - sub_type: 0, - emoji_id: emojiId, - emoji_package_id: element.emojiPackageId ?? 0, - key: element.emojiKey ?? '', - }, - }; - } - - if (element.type === 'poke') { - return { - type: 'poke', - data: { - type: element.subType ?? 0, - }, - }; - } - - if (element.type === 'forward') { - return { - type: 'forward', - data: { id: element.resId ?? '' }, - }; + // S 收·转:按 element.type 查 codec 表;缺条目则走 default 透传(保持原兜底)。 + const codec = ELEMENT_CODECS[element.type]; + if (codec?.toSegment) { + return codec.toSegment(element, { + isGroup, + sessionId, + imageUrlResolver, + mediaUrlResolver, + messageIdResolver, + mediaSegmentSink, + }); } return { type: element.type, data: {} }; } diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 5dd7ae32..0932fcee 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -1,6 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { MessageElement } from '@snowluma/protocol/events'; import { parseFromCQString } from './helper/cq'; +import { ELEMENT_CODECS, intOr } from './event-converter/element-codecs'; import type { JsonValue } from './types'; const log = createLogger('MsgParser'); @@ -17,27 +18,6 @@ export interface ParseMessageOptions { export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; -function intOr(value: unknown, fallback = 0): number { - if (value === undefined || value === null) return fallback; - if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback; - const n = parseInt(String(value), 10); - return Number.isFinite(n) ? n : fallback; -} - -/** Build a market-face (`mface`) element from an OneBot segment's data. - * Shared by the dedicated `mface` segment and the `image`-with-`emoji_id` - * round-trip path. `emojiId` is the hex GUID the wire builder converts back - * to `MarketFace.faceId`. */ -function marketFaceElement(emojiId: string, data: Record): MessageElement { - return { - type: 'mface', - text: String(data.summary ?? data.name ?? ''), - emojiId, - emojiPackageId: intOr(data.emoji_package_id ?? data.tab_id, 0), - emojiKey: String(data.key ?? ''), - }; -} - export function parseCQParams(raw: string): Record { const params: Record = {}; if (!raw) return params; @@ -54,32 +34,6 @@ export function parseCQParams(raw: string): Record { return params; } -/** - * Pick the best loadable source from a media segment's `file` / `url` / `path` - * / `media` fields. - * - * `file` is normally the canonical OneBot field and wins, but it can also be a - * QQ-internal media id (e.g. `.png`) that this process cannot resolve to a - * local path. When a bot framework echoes a received image back (Yunzai et al. - * resend the original `file=.ext` together with the download `url`), using - * `file` makes the send path `statSync` the id as a bogus local path and throw - * `ENOENT`. So: keep `file` when it is a directly loadable source (inline - * bytes, a remote url, or a filesystem path with a separator); otherwise, if a - * real http(s) `url` accompanies it, prefer that. (issue #155) - */ -function pickMediaSource(data: Record): string { - const file = String(data.file ?? '').trim(); - const url = String(data.url ?? '').trim(); - const fallback = file || url || String(data.path ?? '').trim() || String(data.media ?? '').trim(); - if (!file) return fallback; - // `file` is itself loadable: inline bytes, a remote url, or a path (anything - // carrying a `/` or `\` separator, incl. file:// and absolute/relative paths). - if (/^(base64:\/\/|data:|https?:\/\/|file:\/\/)/i.test(file) || /[\\/]/.test(file)) return file; - // `file` is a bare token (QQ-internal id) — fall back to a real url if present. - if (/^https?:\/\//i.test(url)) return url; - return fallback; -} - // --- JSON segment parsing --- interface MessageSegment { @@ -96,130 +50,11 @@ function isSegmentArray(val: unknown): val is MessageSegment[] { export async function segmentToElement(type: string, data: Record, options?: ParseMessageOptions): Promise { const normalizedType = type.toLowerCase(); + + // 纯 OneBot 输入糖:不是某种真实消息元素,只是被塌缩成 json/face/poke 的输入 + // 便利(或 forward 组装用的中间 node),无收侧对应、无专属 wire 形态,故不进 + // codec 表 —— 在这里前置处理。真实元素(收发同名)走下方的 ELEMENT_CODECS。 switch (normalizedType) { - case 'text': { - const text = String(data.text ?? ''); - return text ? { type: 'text', text } : null; - } - case 'face': { - const id = intOr(data.id, -1); - if (id < 0) return null; - return { type: 'face', faceId: id }; - } - case 'at': { - const qq = String(data.qq ?? '').trim(); - if (qq === 'all') { - return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' }; - } - const uin = intOr(qq, 0); - if (uin <= 0) return null; - - const name = String(data.name ?? data.nickname ?? data.card ?? '').trim(); - let uid = String(data.uid ?? '').trim(); - if (!uid && options?.resolveMentionUid) { - uid = (await options.resolveMentionUid(uin))?.trim() ?? ''; - } - const element: MessageElement = { type: 'at', targetUin: uin }; - if (uid) element.uid = uid; - if (name) element.text = `@${name} `; - return element; - } - case 'reply': { - const id = intOr(data.id, 0); - if (id === 0) return null; - - if (options?.resolveReplySequence) { - const resolved = options.resolveReplySequence(id); - if (typeof resolved === 'number' && resolved > 0) { - const element: MessageElement = { - type: 'reply', - replySeq: resolved, - replyMessageId: id // Keep the original messageId for logging - }; - - // Try to get additional meta info for better reply display - if (options?.resolveReplyMeta) { - const meta = options.resolveReplyMeta(id); - if (meta) { - element.replySenderUin = meta.senderUin; - element.replyTime = meta.time; - element.replyRandom = meta.random; - } - } - - return element; - } - } - - // Backward-compatible path: allow direct seq reply IDs. - return id > 0 ? { type: 'reply', replySeq: id } : null; - } - case 'image': { - // A market face that was surfaced as an `image` (see to-segment) can be - // echoed straight back: when `emoji_id` is present we rebuild the market - // face instead of re-uploading the gif as a plain picture. - const imgEmojiId = String(data.emoji_id ?? '').trim(); - if (imgEmojiId) return marketFaceElement(imgEmojiId, data); - return { - type: 'image', - url: pickMediaSource(data), - flash: data.type === 'flash', - subType: intOr(data.subType, 0), - summary: data.summary ? String(data.summary) : undefined, - }; - } - case 'mface': { - // Market face (商城表情). emoji_id is the hex GUID; without it we can't - // construct the wire element, so drop the segment. - const emojiId = String(data.emoji_id ?? '').trim(); - if (!emojiId) { - log.warn('[MsgParser] mface segment without emoji_id is unsupported'); - return null; - } - return marketFaceElement(emojiId, data); - } - case 'record': { - const source = pickMediaSource(data); - if (!source) return null; - return { - type: 'record', - url: source, - }; - } - case 'video': { - const source = pickMediaSource(data); - if (!source) return null; - return { - type: 'video', - url: source, - thumbUrl: data.thumb ? String(data.thumb) : undefined, - }; - } - case 'json': { - return { - type: 'json', - text: String(data.data ?? ''), - }; - } - case 'xml': { - return { - type: 'xml', - text: String(data.data ?? ''), - subType: intOr(data.id, 0), - }; - } - case 'poke': { - return { - type: 'poke', - faceId: intOr(data.type ?? data.id, 0), - }; - } - case 'forward': { - return { - type: 'forward', - resId: String(data.id ?? ''), - }; - } case 'node': { // Fake forward node segment — store the raw data for later processing // The content field may be a segment array, a single segment, or a CQ string @@ -232,12 +67,6 @@ export async function segmentToElement(type: string, data: Record 0) elem.fileSize = fileSize; - if (md5Hex) elem.md5Hex = md5Hex; - if (sha1Hex) elem.sha1Hex = sha1Hex; - if (fileHash) elem.fileHash = fileHash; - return elem; - } - default: - console.warn(`[MsgParser] unsupported segment type: ${type}`); - return null; } + + // 真实元素(P 发·解,段 type 与 element.type 同名):查 codec 表。 + // 见 event-converter/element-codecs.ts。 + const codec = ELEMENT_CODECS[normalizedType]; + if (codec?.fromSegment) return codec.fromSegment(data, options); + + console.warn(`[MsgParser] unsupported segment type: ${type}`); + return null; } function segmentPayload(seg: MessageSegment): Record { diff --git a/packages/onebot/tests/element-manifest.test.ts b/packages/onebot/tests/element-manifest.test.ts index b9af9f7e..69ce8f49 100644 --- a/packages/onebot/tests/element-manifest.test.ts +++ b/packages/onebot/tests/element-manifest.test.ts @@ -5,46 +5,50 @@ import { typesForDirection, INPUT_SUGAR_SEGMENTS, } from '@snowluma/protocol/element-manifest'; +import { ELEMENT_CODECS } from '../src/event-converter/element-codecs'; // 对账测试(onebot 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的两个 -// onebot 方向: -// S 收·转 to-segment.ts 的 `element.type === 'X'` 分支集合 -// P 发·解 message-parser.ts 的 `case 'X'` 分支集合(剔除纯输入糖) +// onebot 方向。阶段 2 起这两向已合入 ELEMENT_CODECS 表,故直接用**表的键**核对, +// 比扫源码正则更硬: +// S 收·转 codec.toSegment MessageElement → OneBot 段 +// P 发·解 codec.fromSegment OneBot 段 → MessageElement // protocol 侧的 D/W 由 protocol/tests/element-manifest.test.ts 核对(包边界所限)。 // -// 架构护栏:谁在这两处增删一种元素方向却没同步 element-manifest,测试当场报红。 -// 纯读源码、零运行时行为改动。 +// 架构护栏:谁在表里增删一个方向却没同步 element-manifest,测试当场报红。 -function readSrc(relFromTestDir: string): string { - const abs = fileURLToPath(new URL(relFromTestDir, import.meta.url)); - const raw = readFileSync(abs, 'utf8'); - return raw.replace(/\/\*[\s\S]*?\*\//g, '').replace(/\/\/.*$/gm, ''); -} - -function extractTypes(src: string, pattern: RegExp): string[] { - const found = new Set(); - for (const m of src.matchAll(pattern)) found.add(m[1]!); - return [...found].sort(); +function codecTypesWith(dir: 'toSegment' | 'fromSegment'): string[] { + return Object.entries(ELEMENT_CODECS) + .filter(([, codec]) => typeof codec[dir] === 'function') + .map(([type]) => type) + .sort(); } const sorted = (s: Iterable): string[] => [...s].sort(); describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', () => { - it('S:to-segment 的 element.type 分支 == 清单声明的 S=yes', () => { - const src = readSrc('../src/event-converter/to-segment.ts'); - const handled = extractTypes(src, /element\.type\s*===\s*'([A-Za-z0-9_]+)'/g); - expect(handled).toEqual(sorted(typesForDirection('S'))); + it('S:ELEMENT_CODECS 里有 toSegment 的类型 == 清单声明的 S=yes', () => { + expect(codecTypesWith('toSegment')).toEqual(sorted(typesForDirection('S'))); }); - it('P:message-parser 的 case 分支(剔除输入糖)== 清单声明的 P=yes', () => { - const src = readSrc('../src/message-parser.ts'); - // 值域放宽到 `[A-Za-z0-9_]+`:见 protocol/tests/element-manifest.test.ts 同处说明。 - const allCases = extractTypes(src, /case\s*'([A-Za-z0-9_]+)'\s*:/g); - const realElementCases = allCases.filter((t) => !INPUT_SUGAR_SEGMENTS.has(t)); - expect(realElementCases).toEqual(sorted(typesForDirection('P'))); + it('P:ELEMENT_CODECS 里有 fromSegment 的类型 == 清单声明的 P=yes', () => { + expect(codecTypesWith('fromSegment')).toEqual(sorted(typesForDirection('P'))); + }); - // 输入糖必须确实出现在 message-parser 里(否则白名单与代码脱节)。 - const sugarPresent = allCases.filter((t) => INPUT_SUGAR_SEGMENTS.has(t)).sort(); + it('输入糖仍由 message-parser 前置处理,未被静默丢弃', () => { + // 输入糖(骰子/分享/…)不进 codec 表,留在 message-parser 当前置 normalize。 + // 用源码扫描锁住它们确实存在,防止将来重构时被悄悄删掉。 + const abs = fileURLToPath(new URL('../src/message-parser.ts', import.meta.url)); + const src = readFileSync(abs, 'utf8') + .replace(/\/\*[\s\S]*?\*\//g, '') + .replace(/\/\/.*$/gm, ''); + const cases = new Set(); + for (const m of src.matchAll(/case\s*'([A-Za-z0-9_]+)'\s*:/g)) cases.add(m[1]!); + + const sugarPresent = [...cases].filter((t) => INPUT_SUGAR_SEGMENTS.has(t)).sort(); expect(sugarPresent).toEqual(sorted(INPUT_SUGAR_SEGMENTS)); + + // 且 message-parser 不再手写任何真实元素类型的 case(已全部下沉到 codec 表)。 + const realLeftInParser = [...cases].filter((t) => !INPUT_SUGAR_SEGMENTS.has(t)); + expect(realLeftInParser).toEqual([]); }); }); From ab40f086ee2485c1cf659f1b59e4322e4ce376bd Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 15:56:43 +0800 Subject: [PATCH 09/30] refactor(protocol): dedup NTV2 record/video mediaNode builder in decoder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 3(零行为改动):record(bizType 12/22) 与 video(bizType 11/21) 解码分支里 各写一份、逐字完全相同的 23 行 `mediaNode:{ fileUuid,storeId,uploadTime,ttl, subType,info:{…} }` 块,抽成共享 helper buildMediaNode(idx, fi),消除这对并行拷贝 的漂移风险(改一处忘另一处)。 - VideoFile / Ptt 两处的 mediaNode 来源变量与 shape 不同,正确保持独立、未误并。 - 逐字提取,行为 byte 级不变:typecheck 干净、protocol 全量 561 全绿;对抗性 Agent byte-diff 确认原两份完全相同、helper body 与之逐字一致。 注:计划中的 poke faceId→subType 字段对齐已主动撤销——poke 不能当消息段发送, 且自身消息回显路径会读 element.subType 使该改动可观测,违反"重构行为不变"。 --- .../src/msg-push/rich-body-decoder.ts | 82 ++++++++----------- 1 file changed, 36 insertions(+), 46 deletions(-) diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 04cbeb04..b9e33464 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -3,7 +3,9 @@ import { toHex, toHexUpper } from '@snowluma/common/hex'; import type { MessageElement } from '../events'; import type { Elem, + FileInfo, GroupFileExtra, + IndexNode, MentionExtra, MsgInfo, NotOnlineImage, @@ -17,6 +19,38 @@ type ElemDecoded = Elem; type RichTextDecoded = RichText; export type PushMsgBody = MessageBody; +/** + * Build the `mediaNode` re-upload descriptor from an NTV2 IndexNode + FileInfo. + * Record and video decode to the byte-identical `{ fileUuid, storeId, + * uploadTime, ttl, subType, info:{…} }` shape — share one builder so the two + * never drift (add a field to one and forget the other). + */ +function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode'] { + return { + fileUuid: idx.fileUuid, + storeId: idx.storeId, + uploadTime: idx.uploadTime, + ttl: idx.ttl, + subType: idx.subType, + info: { + fileSize: fi.fileSize, + fileHash: fi.fileHash, + fileSha1: fi.fileSha1, + fileName: fi.fileName, + width: fi.width, + height: fi.height, + time: fi.time, + original: fi.original, + type: { + type: fi.type?.type, + picFormat: fi.type?.picFormat, + videoFormat: fi.type?.videoFormat, + voiceFormat: fi.type?.voiceFormat, + }, + }, + }; +} + export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] { const elements: MessageElement[] = []; if (body?.richText) { @@ -418,29 +452,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { md5Hex: fi.fileHash ?? '', sha1Hex: fi.fileSha1 ?? '', voiceFormat: fi.type?.voiceFormat ?? 0, - mediaNode: { - fileUuid: idx.fileUuid, - storeId: idx.storeId, - uploadTime: idx.uploadTime, - ttl: idx.ttl, - subType: idx.subType, - info: { - fileSize: fi.fileSize, - fileHash: fi.fileHash, - fileSha1: fi.fileSha1, - fileName: fi.fileName, - width: fi.width, - height: fi.height, - time: fi.time, - original: fi.original, - type: { - type: fi.type?.type, - picFormat: fi.type?.picFormat, - videoFormat: fi.type?.videoFormat, - voiceFormat: fi.type?.voiceFormat, - }, - }, - }, + mediaNode: buildMediaNode(idx, fi), }); } else if (bizType === 11 || bizType === 21) { // Video @@ -454,29 +466,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { md5Hex: fi.fileHash ?? '', sha1Hex: fi.fileSha1 ?? '', videoFormat: fi.type?.videoFormat ?? 0, - mediaNode: { - fileUuid: idx.fileUuid, - storeId: idx.storeId, - uploadTime: idx.uploadTime, - ttl: idx.ttl, - subType: idx.subType, - info: { - fileSize: fi.fileSize, - fileHash: fi.fileHash, - fileSha1: fi.fileSha1, - fileName: fi.fileName, - width: fi.width, - height: fi.height, - time: fi.time, - original: fi.original, - type: { - type: fi.type?.type, - picFormat: fi.type?.picFormat, - videoFormat: fi.type?.videoFormat, - voiceFormat: fi.type?.voiceFormat, - }, - }, - }, + mediaNode: buildMediaNode(idx, fi), }); } } From ab45667fdfdba3b542060ede0e8e32e1b03a7bce Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 16:11:49 +0800 Subject: [PATCH 10/30] refactor(onebot): unify action-error retcode at the runAction seam MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 将「动作抛错返回什么错误码」从各处不一致(100 / 1200 / 漏包→1200)收敛到唯一 兜底处 ApiHandler.runAction,统一为 ACTION_FAILED(100) + error.message。 阶段 1(改 seam 本身): - runAction catch:默认码 1200 → 100;文案 'internal error' 兜底改为 String(error)。 OidbError.message 本就含 QQ 服务端 code,无需特判。 - 新增 3 个测试锁定策略:抛 Error→100+message;抛 OidbError→100 且 wording 含 code+server msg;抛非 Error→100+String()。 - rename_group_file 那个原断言 1200 的测试(未包裹动作、落 runAction)改为 100。 各 action 里多余的 try/catch(qzone/group-album 等仍返回 1200)留待后续阶段删除, 在此之前其失败不经此 seam。onebot 全量 516 全绿、typecheck 干净。 --- packages/onebot/src/api-handler.ts | 18 +++++++---- .../onebot/tests/api-handler-logging.test.ts | 30 +++++++++++++++++++ .../onebot/tests/extended-actions.test.ts | 4 +-- 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index 743c393b..b512d0b4 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -178,15 +178,23 @@ export class ApiHandler { response = await handler(params, sink); this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]); } catch (error) { - // Action failures are almost always param-shape problems coming - // from the OneBot client; warn (not error) is the right level so - // the log file stays a useful signal of real internal faults. + // Single error seam: any throw from a handler (bridge/OIDB business + // failure or an unexpected internal fault) maps here to one policy — + // ACTION_FAILED (100) + the error's message. Action `run` bodies + // shouldn't need to hand-roll their own try/catch → failedResponse: + // doing so only produced inconsistent retcodes (100 vs 1200) for the same + // kind of failure. The remaining per-action catches (qzone / group-album, + // still returning 1200) are being removed in a follow-up phase — until + // then their failures never reach this seam. `OidbError.message` already + // carries the QQ server code, so no special-casing is needed. warn (not + // error) keeps the log file a useful signal without drowning it in + // expected client-side failures. this.log.warn('%s failed: %s\n%s', action, error instanceof Error ? error.message : String(error), error instanceof Error ? (error.stack ?? '') : ''); - const message = error instanceof Error ? error.message : 'internal error'; - response = failedResponse(RETCODE.INTERNAL_ERROR, message); + const message = error instanceof Error ? error.message : String(error); + response = failedResponse(RETCODE.ACTION_FAILED, message); } this.notifyObservers(action, params, response, Date.now() - startedAt); return response; diff --git a/packages/onebot/tests/api-handler-logging.test.ts b/packages/onebot/tests/api-handler-logging.test.ts index 72d3339a..5aef018f 100644 --- a/packages/onebot/tests/api-handler-logging.test.ts +++ b/packages/onebot/tests/api-handler-logging.test.ts @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import { ApiHandler } from '../src/api-handler'; +import { OidbError } from '@snowluma/protocol/oidb-service'; import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; import { summarizeParams } from '@snowluma/common/log-summary'; @@ -108,6 +109,35 @@ describe('ApiHandler dispatch logging', () => { expect(warn!.message).toMatch(/at\s+/); }); + // The single error seam (ADR-0006 narrow seam): any throw from a handler + // maps to ONE policy here — ACTION_FAILED (100) + the error message — + // instead of each action hand-rolling its own inconsistent try/catch. + it('maps any handler throw to ACTION_FAILED (100) with the error message', async () => { + const handler = new ApiHandler(emptyContext(), 12345); + handler.registerAction('kaboom', async () => { throw new Error('permission denied'); }); + + const result = await handler.handle('kaboom', {}); + expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'permission denied' }); + }); + + it('surfaces the OidbError code + server message through error.message (no special-casing)', async () => { + const handler = new ApiHandler(emptyContext(), 12345); + handler.registerAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); }); + + const result = await handler.handle('oidb_boom', {}); + expect(result).toMatchObject({ status: 'failed', retcode: 100 }); + expect((result as { wording: string }).wording).toContain('34'); + expect((result as { wording: string }).wording).toContain('no permission'); + }); + + it('renders a non-Error throw via String()', async () => { + const handler = new ApiHandler(emptyContext(), 12345); + handler.registerAction('weird', async () => { throw 'just a string'; }); + + const result = await handler.handle('weird', {}); + expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'just a string' }); + }); + it('logs unknown actions at debug level', async () => { const handler = new ApiHandler(emptyContext(), 99); await handler.handle('not_a_real_action', {}); diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 68e3594d..dc7c4ce0 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -730,13 +730,13 @@ describe('extended-actions / rename_group_file', () => { expect(rename).not.toHaveBeenCalled(); }); - it('surfaces oidb errors (handler maps a thrown error to INTERNAL_ERROR, as its sibling file ops do)', async () => { + it('surfaces oidb errors — a thrown error maps to the single seam (ACTION_FAILED 100 + message)', 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' }); + expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'rename rejected' }); }); }); From 5be852f3946473f2fda763412208fe2cfc23093b Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 16:20:26 +0800 Subject: [PATCH 11/30] refactor(onebot): drop redundant per-action try/catch in qzone/album/admin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 2a:删除 qzone(7)、group-album(8)、group-admin(1) 共 16 个「纯兜底再包一层」 的 try/catch,让抛错自然落到唯一 seam runAction(阶段 1 已统一为 ACTION_FAILED 100 + error.message)。qzone/album 原返回 1200 → 归一 100(本任务有意);group-admin 原本就是 100,仅去冗余包装。 - 保留:qzone helper uploadQzoneImages 的带前缀 re-throw catch、group-info 的 honor-info 前缀 catch、message 的吞值 catch(best-effort 保留旧 URL)——均未动。 - 清理三文件不再使用的 RETCODE/failedResponse import。 - qzone-actions 测试断言 1200 → 100(wording 前缀经 seam 仍保留)。 - onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐个对比 HEAD 确认纯兜底、 无其它漂移、无误删漏改。 --- packages/onebot/src/actions/group-admin.ts | 10 +-- packages/onebot/src/actions/group-album.ts | 92 ++++++--------------- packages/onebot/src/actions/qzone.ts | 77 +++++------------ packages/onebot/tests/qzone-actions.test.ts | 2 +- 4 files changed, 51 insertions(+), 130 deletions(-) diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index ab91f520..74d625fe 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -1,6 +1,6 @@ import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; import type { ApiActionContext, ApiHandler } from '../api-handler'; -import { RETCODE, failedResponse, okResponse } from '../types'; +import { okResponse } from '../types'; export const actions = [ groupUserAction({ @@ -120,12 +120,8 @@ export const actions = [ summary: '设置群头像', params: { file: f.image() }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + await ctx.bridge.apis.profile.setGroupAvatar(p.group_id, p.file); + return okResponse(); }, }), ]; diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index 8698fe7b..1c750118 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,7 +1,7 @@ import { groupAction, registerActions, f } from '../action-kit'; import type { ApiActionContext, ApiHandler } from '../api-handler'; import type { JsonValue } from '../types'; -import { RETCODE, failedResponse, okResponse } from '../types'; +import { okResponse } from '../types'; export const actions = [ groupAction({ @@ -23,13 +23,8 @@ export const actions = [ }, }, run: async (p, ctx) => { - try { - const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id); - return okResponse(albumList); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get group album list'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id); + return okResponse(albumList); }, }), @@ -67,22 +62,17 @@ export const actions = [ required: ['album_list', 'attach_info', 'has_more'], }, run: async (p, ctx) => { - try { - const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id); - return okResponse({ - album_list: albumList.map((a) => ({ - album_id: a.id, - album_name: a.name, - create_time: a.createTime, - pic_num: a.picNum, - })), - attach_info: '', - has_more: false, - }); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get qun album list'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id); + return okResponse({ + album_list: albumList.map((a) => ({ + album_id: a.id, + album_name: a.name, + create_time: a.createTime, + pic_num: a.picNum, + })), + attach_info: '', + has_more: false, + }); }, }), @@ -94,13 +84,8 @@ export const actions = [ file: f.image(), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file); - return okResponse(null); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to upload image to group album'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + await ctx.bridge.apis.groupAlbum.upload(p.group_id, p.album_id, p.album_name, p.file); + return okResponse(null); }, }), @@ -125,13 +110,8 @@ export const actions = [ attach_info: f.string().default(''), }, run: async (p, ctx) => { - try { - const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info); - return okResponse(mediaList as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get group album media list'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const mediaList = await ctx.bridge.apis.groupAlbum.getMediaList(p.group_id, p.album_id, p.attach_info); + return okResponse(mediaList as unknown as JsonValue); }, }), @@ -143,13 +123,8 @@ export const actions = [ content: f.string({ allowEmpty: false }), }, run: async (p, ctx) => { - try { - const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content); - return okResponse(comment as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to comment on album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const comment = await ctx.bridge.apis.groupAlbum.comment(p.group_id, p.album_id, p.lloc, p.content); + return okResponse(comment as unknown as JsonValue); }, }), @@ -161,13 +136,8 @@ export const actions = [ lloc: f.string().optional(), // 可选参数(空串按未传处理) }, run: async (p, ctx) => { - try { - const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true); - return okResponse(res); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to set like on album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, true); + return okResponse(res); }, }), @@ -180,13 +150,8 @@ export const actions = [ lloc: f.string().optional(), // 可选参数(空串按未传处理) }, run: async (p, ctx) => { - try { - const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false); - return okResponse(res); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to cancel like on album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const res = await ctx.bridge.apis.groupAlbum.like(p.group_id, p.album_id, p.batch_id, p.lloc || undefined, false); + return okResponse(res); }, }), @@ -197,13 +162,8 @@ export const actions = [ lloc: f.string({ allowEmpty: false }), }, run: async (p, ctx) => { - try { - const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc); - return okResponse(res); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to delete album media'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc); + return okResponse(res); }, }), ]; diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts index ae7ec6a3..9cfec395 100644 --- a/packages/onebot/src/actions/qzone.ts +++ b/packages/onebot/src/actions/qzone.ts @@ -1,7 +1,7 @@ import { defineAction, registerActions, f } from '../action-kit'; import type { ApiActionContext, ApiHandler } from '../api-handler'; import type { JsonValue } from '../types'; -import { RETCODE, failedResponse, okResponse } from '../types'; +import { okResponse } from '../types'; async function uploadQzoneImages( ctx: ApiActionContext, @@ -61,13 +61,8 @@ export const actions = [ num: f.int({ min: 1, max: 100 }).describe('本页数量').default(20), }, run: async (p, ctx) => { - try { - const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num); - return okResponse(res as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get qzone msg list'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const res = await ctx.bridge.apis.qzone.getMsgList(p.target_uin, p.pos, p.num); + return okResponse(res as unknown as JsonValue); }, }), @@ -106,13 +101,8 @@ export const actions = [ count: f.int({ min: 1, max: 50 }).describe('本页数量').default(10), }, run: async (p, ctx) => { - try { - const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count); - return okResponse(res as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to get qzone feeds'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + const res = await ctx.bridge.apis.qzone.getFeeds(p.page_num, p.count); + return okResponse(res as unknown as JsonValue); }, }), @@ -134,18 +124,13 @@ export const actions = [ r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length), ], run: async (p, ctx) => { - try { - if (p.images && p.images.length > 0) { - const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval); - const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval, p.ugc_right, p.target_uins?.join('|')); - return okResponse(res as unknown as JsonValue); - } - const res = await ctx.bridge.apis.qzone.publish(p.content, undefined, undefined, p.ugc_right, p.target_uins?.join('|')); + if (p.images && p.images.length > 0) { + const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.richval); + const res = await ctx.bridge.apis.qzone.publish(p.content, 1, richval, p.ugc_right, p.target_uins?.join('|')); return okResponse(res as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to publish qzone msg'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); } + const res = await ctx.bridge.apis.qzone.publish(p.content, undefined, undefined, p.ugc_right, p.target_uins?.join('|')); + return okResponse(res as unknown as JsonValue); }, }), @@ -157,13 +142,8 @@ export const actions = [ tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.qzone.delete(p.tid); - return okResponse(null); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to delete qzone msg'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + await ctx.bridge.apis.qzone.delete(p.tid); + return okResponse(null); }, }), @@ -179,13 +159,8 @@ export const actions = [ abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime); - return okResponse(null); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to like qzone msg'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, true, p.abstime); + return okResponse(null); }, }), @@ -200,13 +175,8 @@ export const actions = [ abstime: f.int({ min: 0 }).describe('说说发表时间(unix 秒),传真实值更可靠').default(0).role('timestamp'), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime); - return okResponse(null); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to unlike qzone msg'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); - } + await ctx.bridge.apis.qzone.like(p.tid, p.target_uin, false, p.abstime); + return okResponse(null); }, }), @@ -223,18 +193,13 @@ export const actions = [ images: f.array(f.string({ allowEmpty: false })).describe('图片数组(可选),支持 file:// http:// base64://;自动上传').optional(), }, run: async (p, ctx) => { - try { - if (p.images && p.images.length > 0) { - const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url); - const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval); - return okResponse(res as unknown as JsonValue); - } - const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin); + if (p.images && p.images.length > 0) { + const richval = await uploadQzoneImages(ctx, p.images, (upload) => upload.url); + const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin, 1, richval); return okResponse(res as unknown as JsonValue); - } catch (error) { - const message = error instanceof Error ? error.message : 'failed to comment qzone msg'; - return failedResponse(RETCODE.INTERNAL_ERROR, message); } + const res = await ctx.bridge.apis.qzone.comment(p.tid, p.content, p.target_uin); + return okResponse(res as unknown as JsonValue); }, }), ]; diff --git a/packages/onebot/tests/qzone-actions.test.ts b/packages/onebot/tests/qzone-actions.test.ts index 2579d749..92c40a6c 100644 --- a/packages/onebot/tests/qzone-actions.test.ts +++ b/packages/onebot/tests/qzone-actions.test.ts @@ -57,7 +57,7 @@ describe('qzone actions', () => { images: ['file:///a.jpg', 'file:///b.jpg'], }); - expect(res).toMatchObject({ status: 'failed', retcode: 1200 }); + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); expect(res.wording).toContain('第 2 张图片上传失败: network down'); expect(publish).not.toHaveBeenCalled(); }); From 6f6f372337702b3d8df4414458037cef5825dc76 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 16:30:00 +0800 Subject: [PATCH 12/30] refactor(onebot): drop 55 redundant ACTION_FAILED try/catch in extended actions MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 2b:从 extended.ts 删除 55 个「纯兜底」try/catch(catch 体恰为单条 return failedResponse(ACTION_FAILED, String(e)/e.message)),让抛错落到唯一 seam runAction(已统一 100 + error.message)。retcode 不变(这些本就是 100),去的是 冗余包装。 - 保留:try/finally、带前缀的 catch(获取精华消息失败 / 语音转码失败)、 download_file 保存失败的 BAD_REQUEST catch、fetchFilteredGroupRequests 的 catch{return []} 吞值——均原样未动。 - 唯一文案变化:约 30 个原用 String(e) 的 catch,其 wording 由 "Error: X" 变为 seam 的裸 "X"(丢类名前缀,retcode 不变;OidbError 的服务器码仍在 message 内) ——一致化改善,无测试/契约依赖该前缀。 - onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐块比对 HEAD 确认等价、 结构正确、无误删漏改。 --- packages/onebot/src/actions/extended.ts | 578 ++++++++---------------- 1 file changed, 179 insertions(+), 399 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index dac7af9d..785c6cb9 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -110,12 +110,8 @@ async function groupTodoRun( if (!meta.isGroup || meta.targetId !== p.group_id) { return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); } - try { - await op(p.group_id, BigInt(meta.sequence)); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + await op(p.group_id, BigInt(meta.sequence)); + return okResponse(); } /** FlashTransferApi 返回的 FlashFileInfo → OneBot JSON 响应(plain object,JsonObject 兼容)。 @@ -259,12 +255,8 @@ export const actions = [ summary: '删除收藏表情', params: { emoji_id: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.deleteCustomFace(p.emoji_id); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.deleteCustomFace(p.emoji_id); + return okResponse(); }, }), @@ -274,12 +266,8 @@ export const actions = [ summary: '添加收藏表情', params: { file: f.image() }, run: async (p, ctx) => { - try { - const emojiId = await ctx.bridge.apis.profile.addCustomFace(p.file); - return okResponse({ emoji_id: emojiId }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const emojiId = await ctx.bridge.apis.profile.addCustomFace(p.file); + return okResponse({ emoji_id: emojiId }); }, }), @@ -292,12 +280,8 @@ export const actions = [ desc: f.string().default(''), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.modifyCustomFace(p.emoji_id, p.desc); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.modifyCustomFace(p.emoji_id, p.desc); + return okResponse(); }, }), @@ -311,12 +295,8 @@ export const actions = [ summary: '收藏表情移到最前', params: { emoji_id: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.moveCustomFaceToFront(p.emoji_id); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.moveCustomFaceToFront(p.emoji_id); + return okResponse(); }, }), @@ -453,19 +433,15 @@ export const actions = [ confirm_required: f.raw(), }, run: async (p, ctx) => { - try { - const options = { - image: p.image || undefined, - pinned: p.pinned !== undefined ? Number(p.pinned) : 0, - type: p.type !== undefined ? Number(p.type) : 1, - confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1, - }; + const options = { + image: p.image || undefined, + pinned: p.pinned !== undefined ? Number(p.pinned) : 0, + type: p.type !== undefined ? Number(p.type) : 1, + confirm_required: p.confirm_required !== undefined ? Number(p.confirm_required) : 1, + }; - await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.web.sendNotice(p.group_id, p.content, options); + return okResponse(); }, }), @@ -474,12 +450,8 @@ export const actions = [ summary: '获取群公告', readOnly: true, run: async (p, ctx) => { - try { - const notices = await ctx.bridge.apis.web.getNotice(p.group_id); - return okResponse(notices); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const notices = await ctx.bridge.apis.web.getNotice(p.group_id); + return okResponse(notices); }, }), @@ -594,11 +566,7 @@ export const actions = [ run: async (_p, ctx, raw) => { const messageId = asNumber(raw.message_id); if (!messageId) return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); - try { - return okResponse(await ctx.fetchPttText(messageId)); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : '获取语音转文字结果失败'); - } + return okResponse(await ctx.fetchPttText(messageId)); }, }), @@ -617,12 +585,8 @@ export const actions = [ }, params: { domain: f.string().default('qun.qq.com') }, run: async (p, ctx) => { - try { - const cookies = await ctx.bridge.apis.web.getCookiesStr(p.domain || 'qun.qq.com'); - return okResponse({ cookies }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const cookies = await ctx.bridge.apis.web.getCookiesStr(p.domain || 'qun.qq.com'); + return okResponse({ cookies }); }, }), @@ -640,12 +604,8 @@ export const actions = [ }, params: {}, run: async (_p, ctx) => { - try { - const token = await ctx.bridge.apis.web.getCsrfToken(); - return okResponse({ token }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const token = await ctx.bridge.apis.web.getCsrfToken(); + return okResponse({ token }); }, }), @@ -665,12 +625,8 @@ export const actions = [ }, params: { domain: f.string().default('qun.qq.com') }, run: async (p, ctx) => { - try { - const creds = await ctx.bridge.apis.web.getCredentials(p.domain || 'qun.qq.com'); - return okResponse(creds); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const creds = await ctx.bridge.apis.web.getCredentials(p.domain || 'qun.qq.com'); + return okResponse(creds); }, }), @@ -801,12 +757,8 @@ export const actions = [ const nickname = p.nickname; const personalNote = p.personal_note; - try { - await ctx.bridge.apis.profile.setProfile(nickname, personalNote); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.setProfile(nickname, personalNote); + return okResponse(); }, }), @@ -820,12 +772,8 @@ export const actions = [ battery_status: f.int({ min: 0 }).default(100), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.setOnlineStatus(p.status, p.ext_status, p.battery_status); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.setOnlineStatus(p.status, p.ext_status, p.battery_status); + return okResponse(); }, }), @@ -842,12 +790,8 @@ export const actions = [ wording: f.string().default(''), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.setDiyOnlineStatus(p.face_id, p.wording, p.face_type); - return okResponse(); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + await ctx.bridge.apis.profile.setDiyOnlineStatus(p.face_id, p.wording, p.face_type); + return okResponse(); }, }), @@ -979,12 +923,8 @@ export const actions = [ summary: '获取群今日打卡列表', readOnly: true, run: async (p, ctx) => { - try { - const list = await ctx.bridge.apis.web.getSignedList(p.group_id); - return okResponse(list); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + const list = await ctx.bridge.apis.web.getSignedList(p.group_id); + return okResponse(list); }, }), @@ -996,12 +936,8 @@ export const actions = [ user_id: f.userId(), }, run: async (p, ctx) => { - try { - const result = await ctx.forwardSingleMsg(p.message_id, { userId: p.user_id }); - return okResponse({ message_id: result.messageId }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + const result = await ctx.forwardSingleMsg(p.message_id, { userId: p.user_id }); + return okResponse({ message_id: result.messageId }); }, }), @@ -1013,12 +949,8 @@ export const actions = [ group_id: f.groupId(), }, run: async (p, ctx) => { - try { - const result = await ctx.forwardSingleMsg(p.message_id, { groupId: p.group_id }); - return okResponse({ message_id: result.messageId }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + const result = await ctx.forwardSingleMsg(p.message_id, { groupId: p.group_id }); + return okResponse({ message_id: result.messageId }); }, }), @@ -1063,12 +995,8 @@ export const actions = [ count: f.int({ min: 0 }).default(10), }, run: async (p, ctx) => { - try { - const data = await ctx.bridge.apis.profile.getLike(p.user_id, p.start, p.count); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const data = await ctx.bridge.apis.profile.getLike(p.user_id, p.start, p.count); + return okResponse(data); }, }), @@ -1088,19 +1016,15 @@ export const actions = [ return_type: f.string().default('url'), }, run: async (p, ctx) => { - try { - const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count); - if (p.return_type === 'id') { - const emojiIds = urls.map((url) => { - const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url); - return m ? m[1] : ''; - }).filter(Boolean); - return okResponse(emojiIds); - } - return okResponse(urls); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); + const urls = await ctx.bridge.apis.profile.fetchCustomFace(p.count); + if (p.return_type === 'id') { + const emojiIds = urls.map((url) => { + const m = /\/qq_expression\/[^/]+\/([^/]+)\//.exec(url); + return m ? m[1] : ''; + }).filter(Boolean); + return okResponse(emojiIds); } + return okResponse(urls); }, }), @@ -1132,14 +1056,10 @@ export const actions = [ emoji_id: f.string({ allowEmpty: false }), }, run: async (p, ctx) => { - try { - const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emoji_id, 1000); - return okResponse({ - emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), - }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emoji_id, 1000); + return okResponse({ + emoji_like_list: result.users.map(u => ({ user_id: String(u.uin), nick_name: '' })), + }); }, }), @@ -1179,22 +1099,18 @@ export const actions = [ cookie: f.string().default(''), }, run: async (p, ctx) => { - try { - const offset = p.cookie ? Number.parseInt(p.cookie, 10) || 0 : 0; - const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emojiId, p.count, offset); - const nextOffset = offset + result.users.length; - const isLastPage = nextOffset >= result.cachedCount; - return okResponse({ - result: 0, - errMsg: '', - emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), - cookie: isLastPage ? '' : String(nextOffset), - isLastPage, - isFirstPage: offset === 0, - }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const offset = p.cookie ? Number.parseInt(p.cookie, 10) || 0 : 0; + const result = await ctx.fetchEmojiLikeUsers(p.message_id, p.emojiId, p.count, offset); + const nextOffset = offset + result.users.length; + const isLastPage = nextOffset >= result.cachedCount; + return okResponse({ + result: 0, + errMsg: '', + emojiLikesList: result.users.map(u => ({ tinyId: String(u.uin), nickName: '', headUrl: '' })), + cookie: isLastPage ? '' : String(nextOffset), + isLastPage, + isFirstPage: offset === 0, + }); }, }), @@ -1312,12 +1228,8 @@ export const actions = [ required: ['can_at_all', 'remain_at_all_count_for_group', 'remain_at_all_count_for_uin'], }, run: async (p, ctx) => { - try { - const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const data = await ctx.bridge.apis.groupAdmin.getAtAllRemain(p.group_id); + return okResponse(data); }, }), @@ -1327,12 +1239,8 @@ export const actions = [ readOnly: true, params: {}, run: async (_p, ctx) => { - try { - const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const data = await ctx.bridge.apis.profile.getUnidirectionalFriendList(); + return okResponse(data); }, }), @@ -1386,17 +1294,13 @@ export const actions = [ phone_number: f.string().default(''), }, run: async (p, ctx) => { - try { - if (p.group_id) { - return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) }); - } - if (p.user_id) { - return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) }); - } - return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required'); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); + if (p.group_id) { + return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) }); } + if (p.user_id) { + return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) }); + } + return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required'); }, }), defineAction({ @@ -1417,17 +1321,13 @@ export const actions = [ phone_number: f.string().default(''), }, run: async (p, ctx) => { - try { - if (p.group_id) { - return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) }); - } - if (p.user_id) { - return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) }); - } - return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required'); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); + if (p.group_id) { + return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id) }); } + if (p.user_id) { + return okResponse({ arkMsg: await ctx.bridge.apis.contacts.getBuddyRecommendArk(p.user_id, p.phone_number) }); + } + return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required'); }, }), @@ -1443,11 +1343,7 @@ export const actions = [ returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' }, params: { group_id: f.groupId() }, run: async (p, ctx) => { - try { - return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id)); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id)); }, }), defineAction({ @@ -1458,11 +1354,7 @@ export const actions = [ returnsSchema: { type: 'string', description: '群 Ark 卡片 JSON 字符串' }, params: { group_id: f.groupId() }, run: async (p, ctx) => { - try { - return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id)); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + return okResponse(await ctx.bridge.apis.contacts.getGroupRecommendArk(p.group_id)); }, }), @@ -1489,12 +1381,8 @@ export const actions = [ }, params: { count: f.int({ min: 0 }).default(50) }, run: async (p, ctx) => { - try { - const list = await ctx.bridge.apis.friend.getDoubtRequests(p.count); - return okResponse(list); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + const list = await ctx.bridge.apis.friend.getDoubtRequests(p.count); + return okResponse(list); }, }), // set_doubt_friends_add_request — handle a 可疑好友申请 (0xd69_0). `flag` is @@ -1511,16 +1399,12 @@ export const actions = [ run: async (p, ctx) => { // approve → approvalDoubtBuddyReq (0xd69_0); reject → delDoubtBuddyReq // (also 0xd69_0, distinct body) — both RE'd from the binary. - try { - if (p.approve) { - await ctx.bridge.apis.friend.approveDoubtRequest(p.flag); - } else { - await ctx.bridge.apis.friend.rejectDoubtRequest(p.flag); - } - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); + if (p.approve) { + await ctx.bridge.apis.friend.approveDoubtRequest(p.flag); + } else { + await ctx.bridge.apis.friend.rejectDoubtRequest(p.flag); } + return okResponse(); }, }), @@ -1530,14 +1414,10 @@ export const actions = [ name: 'set_group_robot_add_option', summary: '设置群机器人加群选项', run: async (p, ctx) => { - try { - await ctx.bridge.apis.groupAdmin.setRobotAddOption( - p.group_id, p.robot_member_switch, p.robot_member_examine, - ); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + await ctx.bridge.apis.groupAdmin.setRobotAddOption( + p.group_id, p.robot_member_switch, p.robot_member_examine, + ); + return okResponse(); }, params: { robot_member_switch: f.int({ min: 0 }).optional(), @@ -1581,12 +1461,8 @@ export const actions = [ summary: '设置 QQ 头像', params: { file: f.image() }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.setAvatar(p.file); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.setAvatar(p.file); + return okResponse(); }, }), @@ -1599,12 +1475,8 @@ export const actions = [ event_type: f.int().default(0), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.profile.setInputStatus(p.user_id, p.event_type); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.setInputStatus(p.user_id, p.event_type); + return okResponse({}); }, }), @@ -1770,19 +1642,15 @@ export const actions = [ }, params: { chat_type: f.int({ min: 0 }).default(1) }, run: async (p, ctx) => { - try { - const list = await ctx.bridge.apis.extras.fetchAiVoiceList(p.group_id, p.chat_type); - return okResponse(list.map((cat) => ({ - type: cat.category, - characters: cat.voices.map((v) => ({ - character_id: v.voiceId, - character_name: v.voiceDisplayName, - preview_url: v.voiceExampleUrl, - })), - }))); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + const list = await ctx.bridge.apis.extras.fetchAiVoiceList(p.group_id, p.chat_type); + return okResponse(list.map((cat) => ({ + type: cat.category, + characters: cat.voices.map((v) => ({ + character_id: v.voiceId, + character_name: v.voiceDisplayName, + preview_url: v.voiceExampleUrl, + })), + }))); }, }), @@ -1795,13 +1663,9 @@ export const actions = [ chat_type: f.int({ min: 0 }).default(1), }, run: async (p, ctx) => { - try { - const node = await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); - const url = await ctx.bridge.apis.groupFile.getPttUrl(p.group_id, node); - return okResponse(url); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + const node = await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); + const url = await ctx.bridge.apis.groupFile.getPttUrl(p.group_id, node); + return okResponse(url); }, }), @@ -1817,12 +1681,8 @@ export const actions = [ chat_type: f.int({ min: 0 }).default(1), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); - return okResponse({ message_id: 0 }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type); + return okResponse({ message_id: 0 }); }, }), @@ -1831,27 +1691,23 @@ export const actions = [ summary: '请求数据库解密密钥', params: { db_path: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - const buffer = Buffer.alloc(128); - const fileHandle = await readFile(p.db_path); + const buffer = Buffer.alloc(128); + const fileHandle = await readFile(p.db_path); - if (fileHandle.length < 0xaf) { - return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); - } - - fileHandle.copy(buffer, 0, 0x2f, 0xaf); - const dbSalt = buffer.toString('utf8'); - - if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { - return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); - } - - const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); - - return okResponse({ db_key: dbKey }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + if (fileHandle.length < 0xaf) { + return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); } + + fileHandle.copy(buffer, 0, 0x2f, 0xaf); + const dbSalt = buffer.toString('utf8'); + + if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { + return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); + } + + const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); + + return okResponse({ db_key: dbKey }); }, }), @@ -1985,12 +1841,8 @@ export const actions = [ run: async (p, ctx) => { const fid = p.fid || p.notice_id; if (!fid) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and fid/notice_id are required'); - try { - const success = await ctx.bridge.apis.web.deleteNotice(p.group_id, fid); - return success ? okResponse() : failedResponse(RETCODE.ACTION_FAILED, 'delete failed'); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const success = await ctx.bridge.apis.web.deleteNotice(p.group_id, fid); + return success ? okResponse() : failedResponse(RETCODE.ACTION_FAILED, 'delete failed'); }, }), @@ -2107,11 +1959,7 @@ export const actions = [ buf = Buffer.from(base64, 'base64'); if (buf.length > DOWNLOAD_FILE_MAX_BYTES) return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); } else { - try { - buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + buf = await fetchDownloadFile(url, parseDownloadHeaders(raw.headers), DOWNLOAD_FILE_MAX_BYTES, DOWNLOAD_FILE_TIMEOUT_MS); } try { const safe = await saveDownloadBuffer(buf, name); @@ -2139,12 +1987,8 @@ export const actions = [ const rawWords = p.words; if (!Array.isArray(rawWords)) return failedResponse(RETCODE.BAD_REQUEST, 'invalid words array'); const words = rawWords.map((w) => String(w)); - try { - const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); - return okResponse({ words: translated }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const translated = await ctx.bridge.apis.misc.translateEn2Zh(words); + return okResponse({ words: translated }); }, }), @@ -2155,12 +1999,8 @@ export const actions = [ run: async (p, ctx) => { const longNick = p.longNick || p.long_nick; if (typeof longNick !== 'string') return failedResponse(RETCODE.BAD_REQUEST, 'invalid longNick'); - try { - await ctx.bridge.apis.profile.setSelfLongNick(longNick); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.profile.setSelfLongNick(longNick); + return okResponse({}); }, }), @@ -2175,12 +2015,8 @@ export const actions = [ const desc = raw.desc || ''; const picUrl = raw.picUrl || raw.pic_url || ''; const jumpUrl = raw.jumpUrl || raw.jump_url || ''; - try { - const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl)); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const data = await ctx.bridge.apis.misc.getMiniAppArk(String(type), String(title), String(desc), String(picUrl), String(jumpUrl)); + return okResponse(data); }, }), @@ -2192,12 +2028,8 @@ export const actions = [ const buttonId = raw.button_id; const callbackData = raw.callback_data || ''; if (!buttonId) return failedResponse(RETCODE.BAD_REQUEST, 'missing required parameters'); - try { - const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq); - return okResponse(data); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const data = await ctx.bridge.apis.misc.clickInlineKeyboardButton(p.group_id, p.bot_appid, String(buttonId), String(callbackData), p.msg_seq); + return okResponse(data); }, }), @@ -2205,12 +2037,8 @@ export const actions = [ name: ['set_group_sign', 'send_group_sign'], summary: '群签到', run: async (p, ctx) => { - try { - await ctx.bridge.apis.misc.sendGroupSign(p.group_id); - return okResponse({}); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.misc.sendGroupSign(p.group_id); + return okResponse({}); }, }), @@ -2222,16 +2050,12 @@ export const actions = [ if (!/^[0-9a-fA-F]*$/.test(p.data) || p.data.length % 2 !== 0) { return failedResponse(RETCODE.BAD_REQUEST, 'data must be a hex string of even length'); } - try { - const body = hexToBytes(p.data); - const result = await ctx.bridge.sendRawPacket(p.cmd, body); - if (!result.success) return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); - if (!p.rsp) return okResponse(null); - const respHex = result.responseData ? bytesToHex(result.responseData) : ''; - return okResponse(respHex); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + const body = hexToBytes(p.data); + const result = await ctx.bridge.sendRawPacket(p.cmd, body); + if (!result.success) return failedResponse(RETCODE.ACTION_FAILED, result.errorMessage || 'send failed'); + if (!p.rsp) return okResponse(null); + const respHex = result.responseData ? bytesToHex(result.responseData) : ''; + return okResponse(respHex); }, }), @@ -2280,12 +2104,8 @@ export const actions = [ } else { return failedResponse(RETCODE.BAD_REQUEST, 'files must be a string or string array'); } - try { - const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path); - return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const result = await ctx.bridge.apis.flashTransfer.createFlashTask(fileList, p.name, p.thumb_path); + return okResponse({ fileset_id: result.filesetId, task_id: result.filesetId }); }, }), @@ -2294,12 +2114,8 @@ export const actions = [ summary: '获取文件集信息', params: { fileset_id: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - const list = await ctx.bridge.apis.flashTransfer.getFilesetInfo(p.fileset_id); - return okResponse({ fileset_id: p.fileset_id, file_list: list.map(flashFileInfoToJson) }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const list = await ctx.bridge.apis.flashTransfer.getFilesetInfo(p.fileset_id); + return okResponse({ fileset_id: p.fileset_id, file_list: list.map(flashFileInfoToJson) }); }, }), @@ -2308,12 +2124,8 @@ export const actions = [ summary: '获取闪传文件列表', params: { fileset_id: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - const list = await ctx.bridge.apis.flashTransfer.getFlashFileList(p.fileset_id); - return okResponse(list.map(flashFileInfoToJson)); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const list = await ctx.bridge.apis.flashTransfer.getFlashFileList(p.fileset_id); + return okResponse(list.map(flashFileInfoToJson)); }, }), @@ -2322,12 +2134,8 @@ export const actions = [ summary: '列出当前账号的所有闪传文件集', params: {}, run: async (_p, ctx) => { - try { - const list = await ctx.bridge.apis.flashTransfer.listFilesets(); - return okResponse(list.map(flashFileInfoToJson)); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const list = await ctx.bridge.apis.flashTransfer.listFilesets(); + return okResponse(list.map(flashFileInfoToJson)); }, }), @@ -2340,12 +2148,8 @@ export const actions = [ file_index: f.number().optional(), }, run: async (p, ctx) => { - try { - const url = await ctx.bridge.apis.flashTransfer.getFlashFileUrl(p.fileset_id, p.file_index); - return okResponse({ url }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const url = await ctx.bridge.apis.flashTransfer.getFlashFileUrl(p.fileset_id, p.file_index); + return okResponse({ url }); }, }), @@ -2354,12 +2158,8 @@ export const actions = [ summary: '获取文件分享链接', params: { fileset_id: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - const url = await ctx.bridge.apis.flashTransfer.getShareLink(p.fileset_id); - return okResponse(url); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + const url = await ctx.bridge.apis.flashTransfer.getShareLink(p.fileset_id); + return okResponse(url); }, }), @@ -2368,12 +2168,8 @@ export const actions = [ summary: '删除闪传文件', params: { fileset_id: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.flashTransfer.deleteFlashFile(p.fileset_id); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.flashTransfer.deleteFlashFile(p.fileset_id); + return okResponse(); }, }), @@ -2385,12 +2181,8 @@ export const actions = [ new_name: f.string({ allowEmpty: false }), }, run: async (p, ctx) => { - try { - await ctx.bridge.apis.flashTransfer.renameFlashFile(p.fileset_id, p.new_name); - return okResponse(); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, String(e)); - } + await ctx.bridge.apis.flashTransfer.renameFlashFile(p.fileset_id, p.new_name); + return okResponse(); }, }), @@ -2404,19 +2196,15 @@ export const actions = [ file_index: f.number().optional(), }, run: async (p, ctx) => { - try { - const target = await ctx.bridge.apis.flashTransfer.downloadFileset(p.fileset_id, { - fileName: p.file_name, - fileIndex: p.file_index, - }); - return okResponse({ - url: target.url, - file_name: target.fileName, - file_size: target.fileSize, - }); - } catch (err) { - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); - } + const target = await ctx.bridge.apis.flashTransfer.downloadFileset(p.fileset_id, { + fileName: p.file_name, + fileIndex: p.file_index, + }); + return okResponse({ + url: target.url, + file_name: target.fileName, + file_size: target.fileSize, + }); }, }), @@ -2433,16 +2221,12 @@ export const actions = [ if (!p.user_id && !p.group_id) { return failedResponse(RETCODE.BAD_REQUEST, 'user_id or group_id is required'); } - try { - await ctx.bridge.apis.flashTransfer.sendFlashMsg(p.fileset_id, { - userId: p.user_id, - groupId: p.group_id, - }); - // 0x93d7 响应无 message_id(分享 fileset,非传统消息),返回 0 兼容 OneBot 形状。 - return okResponse({ message_id: 0 }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + await ctx.bridge.apis.flashTransfer.sendFlashMsg(p.fileset_id, { + userId: p.user_id, + groupId: p.group_id, + }); + // 0x93d7 响应无 message_id(分享 fileset,非传统消息),返回 0 兼容 OneBot 形状。 + return okResponse({ message_id: 0 }); }, }), @@ -2460,12 +2244,8 @@ export const actions = [ }, params: { share_code: f.string({ allowEmpty: false }) }, run: async (p, ctx) => { - try { - const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code); - return okResponse({ fileset_id: filesetId }); - } catch (e) { - return failedResponse(RETCODE.ACTION_FAILED, e instanceof Error ? e.message : String(e)); - } + const filesetId = await ctx.bridge.apis.flashTransfer.getFilesetIdByCode(p.share_code); + return okResponse({ fileset_id: filesetId }); }, }), ]; From 9d6763039639b7009921032bfd47d287296bd4b9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 17:25:04 +0800 Subject: [PATCH 13/30] refactor(common,core): extract single-flight+TTL cache primitive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 1:把手写多份的「单飞+TTL 记忆化」收进一个 common 原语,消除各处 各自实现「TTL 判定 / inflight 去重 / finally 清理」的漂移风险(底层都是 Tencent 风控:忙碌客户端会为每条消息发一次未缓存 OIDB 拉取,持续爆发触发封号)。 - 新增 common/single-flight-cache.ts:createSingleFlightCache({ ttlMs, load, shouldCache?, now? }).get(key, {force});shouldCache 容纳「错误结果不缓存以便 重试」,now 可注入便于测 TTL。7 个单测覆盖新鲜命中/单飞去重/force/TTL 过期/ shouldCache/错误传播/invalidate。 - 迁移 contacts.fetchGroupMemberList(key=groupId, ttl 60s, 默认 shouldCache)与 update-check.getUpdateInfo(全局 key, ttl 6h, shouldCache=!error)。行为严格不变。 对抗性 Agent 逐条对比 HEAD 确认两处等价(含 update-check 时间戳来源毫秒级微差、 对 6h TTL 可忽略)。common 43 / core 467 全绿、typecheck 干净。 --- packages/common/package.json | 4 + packages/common/src/single-flight-cache.ts | 93 +++++++++++++ .../common/tests/single-flight-cache.test.ts | 131 ++++++++++++++++++ packages/core/src/bridge/apis/contacts.ts | 33 ++--- packages/core/src/webui/update-check.ts | 35 ++--- 5 files changed, 256 insertions(+), 40 deletions(-) create mode 100644 packages/common/src/single-flight-cache.ts create mode 100644 packages/common/tests/single-flight-cache.test.ts diff --git a/packages/common/package.json b/packages/common/package.json index 374511fe..e0cb2dbd 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -20,6 +20,10 @@ "types": "./src/coerce.ts", "default": "./src/coerce.ts" }, + "./single-flight-cache": { + "types": "./src/single-flight-cache.ts", + "default": "./src/single-flight-cache.ts" + }, "./hex": { "types": "./src/hex.ts", "default": "./src/hex.ts" diff --git a/packages/common/src/single-flight-cache.ts b/packages/common/src/single-flight-cache.ts new file mode 100644 index 00000000..4b21ab0b --- /dev/null +++ b/packages/common/src/single-flight-cache.ts @@ -0,0 +1,93 @@ +/** + * Single-flight + TTL memoization. + * + * Concentrates the "don't refetch what's fresh, and don't stampede the same + * key with concurrent loads" pattern that was hand-rolled (slightly + * differently each time) across the codebase — e.g. `ContactsApi`'s group + * member-list cache and the WebUI update-check. Each copy re-implemented the + * same fiddly trio: a TTL freshness check, an in-flight promise map to + * de-dupe concurrent callers, and `finally`-cleanup of that map. Getting any + * of the three subtly wrong (forgetting the `finally`, caching an error, + * racing the timestamp) is a real hazard — so it lives in one place. + * + * The underlying concern is Tencent risk-control: a busy OneBot client can + * fan out one uncached OIDB fetch per inbound message, and sustained bursts + * trip a ban. TTL + single-flight collapse that fan-out. + */ + +export interface SingleFlightCacheOptions { + /** Freshness window in ms. A cached entry older than this is reloaded. */ + ttlMs: number; + /** Load the value for a key. Rejections propagate and are never cached. */ + load: (key: K) => Promise; + /** + * Decide whether a resolved value should be cached. Default: always. + * Return `false` to leave an entry uncached (e.g. an error-shaped result the + * next call should retry) while still de-duping concurrent in-flight callers. + */ + shouldCache?: (value: V) => boolean; + /** Clock, injectable for tests. Defaults to `Date.now`. */ + now?: () => number; +} + +export class SingleFlightCache { + private readonly ttlMs: number; + private readonly load: (key: K) => Promise; + private readonly shouldCache: (value: V) => boolean; + private readonly now: () => number; + private readonly fresh = new Map(); + private readonly inflight = new Map>(); + + constructor(opts: SingleFlightCacheOptions) { + this.ttlMs = opts.ttlMs; + this.load = opts.load; + this.shouldCache = opts.shouldCache ?? (() => true); + this.now = opts.now ?? Date.now; + } + + /** + * Get the value for `key`. + * + * - Returns a fresh cached value when the last load was within `ttlMs`. + * - Otherwise de-dupes concurrent callers onto a single `load()` and caches + * the result (subject to `shouldCache`). A rejected `load` propagates to + * every joined caller, clears the in-flight slot, and is not cached. + * - `force` bypasses the freshness check but still joins an in-flight load + * rather than starting a second one. + */ + get(key: K, opts: { force?: boolean } = {}): Promise { + if (!opts.force) { + const hit = this.fresh.get(key); + if (hit && this.now() - hit.at < this.ttlMs) return Promise.resolve(hit.value); + } + const existing = this.inflight.get(key); + if (existing) return existing; + const task = (async () => { + try { + const value = await this.load(key); + if (this.shouldCache(value)) this.fresh.set(key, { at: this.now(), value }); + return value; + } finally { + this.inflight.delete(key); + } + })(); + this.inflight.set(key, task); + return task; + } + + /** Drop a cached entry. Does not abort an in-flight load. */ + invalidate(key: K): void { + this.fresh.delete(key); + } + + /** Drop all cached entries. Does not abort in-flight loads. */ + clear(): void { + this.fresh.clear(); + } +} + +export function createSingleFlightCache( + opts: SingleFlightCacheOptions, +): SingleFlightCache { + return new SingleFlightCache(opts); +} diff --git a/packages/common/tests/single-flight-cache.test.ts b/packages/common/tests/single-flight-cache.test.ts new file mode 100644 index 00000000..77233282 --- /dev/null +++ b/packages/common/tests/single-flight-cache.test.ts @@ -0,0 +1,131 @@ +import { describe, it, expect, vi } from 'vitest'; +import { createSingleFlightCache } from '../src/single-flight-cache'; + +/** A promise whose resolve/reject is exposed, for driving single-flight races. */ +function deferred() { + let resolve!: (v: T) => void; + let reject!: (e: unknown) => void; + const promise = new Promise((res, rej) => { resolve = res; reject = rej; }); + return { promise, resolve, reject }; +} + +describe('SingleFlightCache', () => { + it('caches within the TTL and reloads once expired', async () => { + let clock = 1000; + const load = vi.fn(async (k: string) => `${k}@${clock}`); + const cache = createSingleFlightCache({ ttlMs: 100, load, now: () => clock }); + + expect(await cache.get('a')).toBe('a@1000'); + clock = 1050; // still fresh (< 100) + expect(await cache.get('a')).toBe('a@1000'); + expect(load).toHaveBeenCalledTimes(1); + + clock = 1101; // 101ms since store → expired + expect(await cache.get('a')).toBe('a@1101'); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('de-dupes concurrent callers onto a single load (single-flight)', async () => { + const d = deferred(); + const load = vi.fn(() => d.promise); + const cache = createSingleFlightCache({ ttlMs: 1000, load }); + + const p1 = cache.get('k'); + const p2 = cache.get('k'); + const p3 = cache.get('k'); + expect(load).toHaveBeenCalledTimes(1); // only one load in flight + + d.resolve('v'); + expect(await Promise.all([p1, p2, p3])).toEqual(['v', 'v', 'v']); + expect(load).toHaveBeenCalledTimes(1); + }); + + it('keys independently — different keys load separately', async () => { + const load = vi.fn(async (k: number) => k * 2); + const cache = createSingleFlightCache({ ttlMs: 1000, load }); + expect(await cache.get(1)).toBe(2); + expect(await cache.get(2)).toBe(4); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('force bypasses the freshness check but still joins an in-flight load', async () => { + let clock = 0; + const load = vi.fn(async (k: string) => `${k}@${clock}`); + const cache = createSingleFlightCache({ ttlMs: 10_000, load, now: () => clock }); + + expect(await cache.get('a')).toBe('a@0'); // 1 load, cached fresh + clock = 5; // still fresh + expect(await cache.get('a', { force: true })).toBe('a@5'); // force → reload despite fresh + expect(load).toHaveBeenCalledTimes(2); + + // force still single-flights: two concurrent forced gets share one load. + const d = deferred(); + load.mockImplementationOnce(() => d.promise); + const p1 = cache.get('a', { force: true }); + const p2 = cache.get('a', { force: true }); + expect(load).toHaveBeenCalledTimes(3); // not 4 + d.resolve('shared'); + expect(await Promise.all([p1, p2])).toEqual(['shared', 'shared']); + }); + + it('shouldCache=false leaves the entry uncached (next call reloads) but still de-dupes in-flight', async () => { + let n = 0; + const load = vi.fn(async () => ({ error: true as boolean, n: ++n })); + const cache = createSingleFlightCache({ ttlMs: 10_000, load, shouldCache: (v) => !v.error }); + + // concurrent callers still share one load... + const [a, b] = await Promise.all([cache.get('k'), cache.get('k')]); + expect(a).toEqual({ error: true, n: 1 }); + expect(b).toEqual({ error: true, n: 1 }); + expect(load).toHaveBeenCalledTimes(1); + + // ...but nothing was cached, so the next call reloads. + expect(await cache.get('k')).toEqual({ error: true, n: 2 }); + expect(load).toHaveBeenCalledTimes(2); + + // a good result IS cached. + load.mockImplementationOnce(async () => ({ error: false, n: ++n })); + const good = await cache.get('k'); + expect(good).toEqual({ error: false, n: 3 }); + expect(await cache.get('k')).toEqual({ error: false, n: 3 }); // served from cache + expect(load).toHaveBeenCalledTimes(3); + }); + + it('a rejected load propagates to all joined callers, is not cached, and clears in-flight', async () => { + let attempt = 0; + const load = vi.fn(async () => { + attempt++; + if (attempt === 1) throw new Error('boom'); + return 'ok'; + }); + const cache = createSingleFlightCache({ ttlMs: 10_000, load }); + + const p1 = cache.get('k'); + const p2 = cache.get('k'); + await expect(p1).rejects.toThrow('boom'); + await expect(p2).rejects.toThrow('boom'); // same in-flight, same rejection + expect(load).toHaveBeenCalledTimes(1); + + // in-flight cleared + not cached → next call retries and succeeds. + expect(await cache.get('k')).toBe('ok'); + expect(load).toHaveBeenCalledTimes(2); + }); + + it('invalidate drops a cached entry; clear drops all', async () => { + const load = vi.fn(async (k: string) => k.toUpperCase()); + const cache = createSingleFlightCache({ ttlMs: 10_000, load }); + await cache.get('a'); + await cache.get('b'); + expect(load).toHaveBeenCalledTimes(2); + + cache.invalidate('a'); + await cache.get('a'); // reloads + await cache.get('b'); // still cached + expect(load).toHaveBeenCalledTimes(3); + + cache.clear(); + await cache.get('a'); + await cache.get('b'); + expect(load).toHaveBeenCalledTimes(5); + }); +}); diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 24a9618b..6514b216 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -8,6 +8,7 @@ import { FetchUserProfile } from '@snowluma/protocol/oidb-services/contacts/fetc import { FetchUserProfileByUid } from '@snowluma/protocol/oidb-services/contacts/fetch-user-profile-by-uid'; import { GetBuddyRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-buddy-recommend-ark'; import { GetGroupRecommendArk } from '@snowluma/protocol/oidb-services/contacts/get-group-recommend-ark'; +import { createSingleFlightCache, type SingleFlightCache } from '@snowluma/common/single-flight-cache'; import type { FriendInfo, GroupMemberInfo, @@ -55,16 +56,19 @@ const MEMBER_LIST_TTL_MS = 60_000; export class ContactsApi { /** - * Per-group inflight + last-fetch cache for `fetchGroupMemberList`. - * Keyed by groupId, lives for the lifetime of the Bridge. + * Per-group TTL + single-flight cache for `fetchGroupMemberList`, keyed by + * groupId, living for the lifetime of the Bridge. * * Without this, a busy OneBot client (e.g. MaiBot calling * `get_group_member_info` once per inbound message) triggers one * OIDB 0xfe7_3 per chat message — sustained >1k/h, which trips * Tencent risk-control and gets the account banned for 7 days. */ - private memberListInflight = new Map>(); - private memberListLastFetch = new Map(); + private readonly memberListCache: SingleFlightCache = + createSingleFlightCache({ + ttlMs: MEMBER_LIST_TTL_MS, + load: (groupId) => this.fetchGroupMemberListUncached(groupId), + }); constructor(private readonly ctx: BridgeContext) { } @@ -139,28 +143,11 @@ export class ContactsApi { }; } - async fetchGroupMemberList( + fetchGroupMemberList( groupId: number, options: { force?: boolean } = {}, ): Promise { - const now = Date.now(); - const last = this.memberListLastFetch.get(groupId); - if (!options.force && last && now - last.at < MEMBER_LIST_TTL_MS) { - return last.data; - } - const inflight = this.memberListInflight.get(groupId); - if (inflight) return inflight; - const task = (async () => { - try { - const data = await this.fetchGroupMemberListUncached(groupId); - this.memberListLastFetch.set(groupId, { at: Date.now(), data }); - return data; - } finally { - this.memberListInflight.delete(groupId); - } - })(); - this.memberListInflight.set(groupId, task); - return task; + return this.memberListCache.get(groupId, { force: options.force }); } private async fetchGroupMemberListUncached(groupId: number): Promise { diff --git a/packages/core/src/webui/update-check.ts b/packages/core/src/webui/update-check.ts index c1c6da30..1b122b4b 100644 --- a/packages/core/src/webui/update-check.ts +++ b/packages/core/src/webui/update-check.ts @@ -11,6 +11,7 @@ // "无法检查更新" rather than nagging). import { createLogger } from '@snowluma/common/logger'; +import { createSingleFlightCache } from '@snowluma/common/single-flight-cache'; const log = createLogger('Update'); @@ -79,8 +80,22 @@ export function compareVersions(a: string, b: string): number { return pa.pre < pb.pre ? -1 : 1; } -let cache: UpdateCheckResult | null = null; -let inflight: Promise | null = null; +// TTL + single-flight: cache good results for CACHE_TTL_MS (well under GitHub's +// 60 req/hr limit) and collapse concurrent checks onto one fetch. Error results +// are intentionally not cached (shouldCache) so the next check retries. +const updateCache = createSingleFlightCache({ + ttlMs: CACHE_TTL_MS, + shouldCache: (r) => !r.error, + load: async (current) => { + const result = await fetchLatest(current); + if (result.error) { + log.debug('update check failed: %s', result.error); + } else if (result.hasUpdate) { + log.info('a newer release is available: v%s (running v%s)', result.latest, current); + } + return result; + }, +}); async function fetchLatest(current: string): Promise { const base: UpdateCheckResult = { @@ -133,21 +148,7 @@ export async function getUpdateInfo(force = false): Promise { if (!isEnabled()) { return { ...emptyResult(current), error: 'disabled' }; } - if (!force && cache && Date.now() - cache.checkedAt < CACHE_TTL_MS) return cache; - if (inflight) return inflight; - inflight = (async () => { - const result = await fetchLatest(current); - if (result.error) { - log.debug('update check failed: %s', result.error); - } else { - cache = result; // only cache good results so transient errors retry - if (result.hasUpdate) log.info('a newer release is available: v%s (running v%s)', result.latest, current); - } - return result; - })().finally(() => { - inflight = null; - }); - return inflight; + return updateCache.get(current, { force }); } function emptyResult(current: string): UpdateCheckResult { From b6cde5101d9e43e88dff40fc06787f2e31d985bf Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 17:29:25 +0800 Subject: [PATCH 14/30] refactor(common,core): extract mapWithConcurrency util; use in forward enrich MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 2:把「限量+并发分批」的手写循环收进一个 common util。此形状已被复制进 私有 SLE(friend.ts),是已发生的复制漂移;抽出后堵住它、并给未来的富化点一个 现成原语(cap + 并发批 + best-effort 是防 Tencent 风控封号的标准配方)。 - 新增 common/concurrency.ts:mapWithConcurrency(items, concurrency, fn),批处理 语义(每批 Promise.all 等齐再下一批,非 rolling pool,保持 forward 现有行为), 结果按输入顺序返回。7 个单测覆盖顺序/绝对index/峰值≤limit+跨批serialize/ 不整除/单批/空/concurrency<1。 - 迁移 forward.ts residue 昵称富化的并发批循环;cap(slice MAX)/dedup(Set)/ best-effort(fn 内 try/catch) 保留在 callsite。行为严格不变。 对抗性 Agent 逐条对比 HEAD 确认等价。common 50 / core 467 全绿、typecheck 干净。 --- packages/common/package.json | 4 ++ packages/common/src/concurrency.ts | 27 +++++++++ packages/common/tests/concurrency.test.ts | 68 +++++++++++++++++++++++ packages/core/src/bridge/apis/forward.ts | 11 ++-- 4 files changed, 104 insertions(+), 6 deletions(-) create mode 100644 packages/common/src/concurrency.ts create mode 100644 packages/common/tests/concurrency.test.ts diff --git a/packages/common/package.json b/packages/common/package.json index e0cb2dbd..7183555a 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -24,6 +24,10 @@ "types": "./src/single-flight-cache.ts", "default": "./src/single-flight-cache.ts" }, + "./concurrency": { + "types": "./src/concurrency.ts", + "default": "./src/concurrency.ts" + }, "./hex": { "types": "./src/hex.ts", "default": "./src/hex.ts" diff --git a/packages/common/src/concurrency.ts b/packages/common/src/concurrency.ts new file mode 100644 index 00000000..5da07645 --- /dev/null +++ b/packages/common/src/concurrency.ts @@ -0,0 +1,27 @@ +/** + * Map `items` through `fn` in sequential batches of at most `concurrency` + * items, awaiting each batch (`Promise.all`) before starting the next. + * Results come back in input order. + * + * Batched, not a rolling pool: every item in a batch must settle before the + * next batch starts. This caps peak parallelism — used to keep rate-limited + * fan-out (e.g. the per-uin OIDB profile fetches during forward-node + * enrichment) from bursting past a safe width and tripping Tencent + * risk-control. Pair it with a cap on `items` (slice) and per-item error + * handling inside `fn` for a fully bounded, best-effort enrichment — the + * shape that was previously hand-rolled at each such call site. + */ +export async function mapWithConcurrency( + items: readonly T[], + concurrency: number, + fn: (item: T, index: number) => Promise, +): Promise { + const limit = Math.max(1, Math.trunc(concurrency)); + const results = new Array(items.length); + for (let i = 0; i < items.length; i += limit) { + const batch = items.slice(i, i + limit); + const settled = await Promise.all(batch.map((item, j) => fn(item, i + j))); + for (let j = 0; j < settled.length; j++) results[i + j] = settled[j]!; + } + return results; +} diff --git a/packages/common/tests/concurrency.test.ts b/packages/common/tests/concurrency.test.ts new file mode 100644 index 00000000..8706cac3 --- /dev/null +++ b/packages/common/tests/concurrency.test.ts @@ -0,0 +1,68 @@ +import { describe, it, expect } from 'vitest'; +import { mapWithConcurrency } from '../src/concurrency'; + +const tick = () => new Promise((r) => setTimeout(r, 0)); + +describe('mapWithConcurrency', () => { + it('returns results in input order', async () => { + const out = await mapWithConcurrency([1, 2, 3, 4, 5], 2, async (n) => n * 10); + expect(out).toEqual([10, 20, 30, 40, 50]); + }); + + it('passes the absolute index (across batch boundaries)', async () => { + const seen: Array<[number, number]> = []; + await mapWithConcurrency(['a', 'b', 'c', 'd', 'e'], 2, async (item, i) => { + seen.push([i, item.charCodeAt(0)]); + return i; + }); + expect(seen.map(([i]) => i).sort((x, y) => x - y)).toEqual([0, 1, 2, 3, 4]); + }); + + it('never runs more than `concurrency` at once (batched), and serializes across batches', async () => { + let inFlight = 0; + let peak = 0; + const order: number[] = []; + await mapWithConcurrency([0, 1, 2, 3, 4, 5, 6], 3, async (n) => { + inFlight++; + peak = Math.max(peak, inFlight); + await tick(); + order.push(n); + inFlight--; + return n; + }); + expect(peak).toBeLessThanOrEqual(3); + // batched: first 3 (0,1,2) settle before the next batch (3,4,5) starts. + expect(order.slice(0, 3).sort((a, b) => a - b)).toEqual([0, 1, 2]); + expect(order.slice(3, 6).sort((a, b) => a - b)).toEqual([3, 4, 5]); + expect(order[6]).toBe(6); + }); + + it('handles a length not divisible by concurrency (short final batch)', async () => { + const out = await mapWithConcurrency([1, 2, 3, 4, 5], 3, async (n) => n); + expect(out).toEqual([1, 2, 3, 4, 5]); + }); + + it('runs everything in one batch when concurrency >= length', async () => { + let peak = 0, inFlight = 0; + const out = await mapWithConcurrency([1, 2, 3], 10, async (n) => { + inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n; + }); + expect(out).toEqual([1, 2, 3]); + expect(peak).toBe(3); + }); + + it('returns [] for an empty input without calling fn', async () => { + let called = 0; + const out = await mapWithConcurrency([], 4, async (n) => { called++; return n; }); + expect(out).toEqual([]); + expect(called).toBe(0); + }); + + it('treats concurrency < 1 as 1 (fully serial)', async () => { + let peak = 0, inFlight = 0; + await mapWithConcurrency([1, 2, 3], 0, async (n) => { + inFlight++; peak = Math.max(peak, inFlight); await tick(); inFlight--; return n; + }); + expect(peak).toBe(1); + }); +}); diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index 6b6f1f4a..991f9de0 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -1,4 +1,5 @@ import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { mapWithConcurrency } from '@snowluma/common/concurrency'; import type { LongMsgResult, RecvLongMsgReq, @@ -676,14 +677,12 @@ export class ForwardApi { .slice(0, FORWARD_PROFILE_MAX); if (uins.length > 0) { const byUin = new Map(); - for (let i = 0; i < uins.length; i += FORWARD_PROFILE_CONCURRENCY) { - const batch = uins.slice(i, i + FORWARD_PROFILE_CONCURRENCY); - const results = await Promise.all(batch.map(async (uin): Promise => { + const results = await mapWithConcurrency(uins, FORWARD_PROFILE_CONCURRENCY, + async (uin): Promise => { try { return [uin, (await this.ctx.apis.contacts.fetchUserProfile(uin)).nickname] as const; } catch { return [uin, ''] as const; } - })); - for (const [uin, nick] of results) byUin.set(uin, nick); - } + }); + for (const [uin, nick] of results) byUin.set(uin, nick); for (const n of residue) { if (!this.needsName(n)) continue; const nick = byUin.get(n.userUin); From 891a197335e98637215e68cb16b41658a412234e Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 17:49:07 +0800 Subject: [PATCH 15/30] refactor(onebot): collapse action registration into a single barrel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 加一个 action 文件原本要同步改三处手写清单:ApiHandler 的 12 个 register import + 12 行构造调用、各文件的 register footer、action-docs 的 13 import + GROUPS。现收敛 成一个 actions/index.ts barrel 作为「文件→动作 + 分类」的单一真相。 - action-kit:抽 RegisteredActionSpec(describe+register),ActionSpec/ StreamActionSpec extends 它,registerActions 参数放宽到 RegisteredActionSpec[] (它只调 .register),于是 stream 动作也能并入统一注册。 - 新增 actions/index.ts:ACTION_GROUPS(11 组含分类,stream 合并)+ ALL_ACTIONS。 - api-handler:12 import+12 调用 → registerActions(this, context, ALL_ACTIONS); .handle_quick_operation(唯一非 ActionSpec 的裸 handler,需要 h 本身)从 extended 搬进构造器一处显式注册。 - action-docs:改用 barrel 的 ACTION_GROUPS,删本地 GROUPS + 13 import。 - 删 12 个 register footer + 清理因此变 unused 的 ApiHandler/ApiActionContext import。 行为严格不变:注册的动作集合、.handle_quick_operation、文档分类/计数均一致。 onebot 516 全绿、全仓 12 包 typecheck Done;对抗性 Agent 逐条对比 HEAD 确认等价。 --- packages/onebot/src/action-docs.ts | 39 ++------------- packages/onebot/src/action-kit.ts | 22 +++++---- packages/onebot/src/actions/extended.ts | 18 +------ packages/onebot/src/actions/friend.ts | 6 +-- packages/onebot/src/actions/group-admin.ts | 6 +-- packages/onebot/src/actions/group-album.ts | 6 +-- packages/onebot/src/actions/group-file.ts | 6 +-- packages/onebot/src/actions/group-info.ts | 6 +-- packages/onebot/src/actions/index.ts | 48 +++++++++++++++++++ packages/onebot/src/actions/info.ts | 6 +-- packages/onebot/src/actions/message.ts | 7 +-- packages/onebot/src/actions/qzone.ts | 7 +-- packages/onebot/src/actions/request.ts | 6 +-- .../onebot/src/actions/stream-download.ts | 6 +-- packages/onebot/src/actions/stream-file.ts | 6 +-- packages/onebot/src/api-handler.ts | 42 +++++++--------- 16 files changed, 98 insertions(+), 139 deletions(-) create mode 100644 packages/onebot/src/actions/index.ts diff --git a/packages/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts index e55a385e..77f121e4 100644 --- a/packages/onebot/src/action-docs.ts +++ b/packages/onebot/src/action-docs.ts @@ -13,49 +13,18 @@ // Markdown default. Point any renderer at `collectActionDocs()`. import type { ActionDoc } from './action-kit'; -import { actions as infoActions } from './actions/info'; -import { actions as messageActions } from './actions/message'; -import { actions as friendActions } from './actions/friend'; -import { actions as groupInfoActions } from './actions/group-info'; -import { actions as groupAdminActions } from './actions/group-admin'; -import { actions as groupFileActions } from './actions/group-file'; -import { actions as requestActions } from './actions/request'; -import { actions as extendedActions } from './actions/extended'; -import { actions as groupAlbumActions } from './actions/group-album'; -import { actions as qzoneActions } from './actions/qzone'; -import { actions as streamFileActions } from './actions/stream-file'; -import { actions as streamDownloadActions } from './actions/stream-download'; - -// The doc collector only ever calls `describe()`, so any spec carrying it -// qualifies — this admits both `defineAction` (ActionSpec) and -// `defineStreamAction` (StreamActionSpec) results without coupling to either. -type AnySpec = { describe(): ActionDoc }; - -// Source file = domain category. Each doc is tagged so the MCP / UI can group. -const GROUPS: ReadonlyArray<{ category: string; specs: readonly AnySpec[] }> = [ - { category: '信息', specs: infoActions }, - { category: '消息', specs: messageActions }, - { category: '好友', specs: friendActions }, - { category: '群信息', specs: groupInfoActions }, - { category: '群管理', specs: groupAdminActions }, - { category: '群文件', specs: groupFileActions }, - { category: '请求', specs: requestActions }, - { category: '扩展', specs: extendedActions }, - { category: '群相册', specs: groupAlbumActions }, - { category: '空间', specs: qzoneActions }, - { category: '流式接口', specs: [...streamFileActions, ...streamDownloadActions] }, -]; +import { ACTION_GROUPS } from './actions'; /** Every declarative action's doc (with category), sorted by name. */ export function collectActionDocs(): ActionDoc[] { - return GROUPS - .flatMap(({ category, specs }) => specs.map((s) => ({ ...s.describe(), category }))) + return ACTION_GROUPS + .flatMap(({ category, actions }) => actions.map((s) => ({ ...s.describe(), category }))) .sort((a, b) => a.name.localeCompare(b.name)); } /** Distinct categories with action counts. */ export function collectCategories(): Array<{ category: string; count: number }> { - return GROUPS.map(({ category, specs }) => ({ category, count: specs.length })); + return ACTION_GROUPS.map(({ category, actions }) => ({ category, count: actions.length })); } function paramRow(p: ActionDoc['params'][number]): string { diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index ff07281b..a06207ce 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -440,16 +440,24 @@ export interface ActionDoc { type Handler = (params: JsonObject) => Promise; -export interface ActionSpec { +/** + * The narrow shape both `ActionSpec` and `StreamActionSpec` share — enough to + * register a spec onto an `ApiHandler` and to collect its docs. The action + * registry barrel (`actions/index.ts`) is typed against this so it can hold + * both kinds in one flat list without coupling to either concrete generic. + */ +export interface RegisteredActionSpec { + describe(): ActionDoc; + register(h: ApiHandler, ctx: ApiActionContext): void; +} + +export interface ActionSpec extends RegisteredActionSpec { readonly names: string[]; readonly params: S; /** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */ parse(raw: JsonObject): CoerceResult>; /** Bind ctx and produce the `(params) => ApiResponse` for `registerAction`. */ toHandler(ctx: ApiActionContext): Handler; - /** Doc metadata (D4); a renderer walks this. */ - describe(): ActionDoc; - register(h: ApiHandler, ctx: ApiActionContext): void; } interface ActionDef { @@ -558,12 +566,10 @@ interface StreamActionDef { run: (p: InferParams, ctx: ApiActionContext, raw: JsonObject, sink: StreamSink) => Promise | ApiResponse; } -export interface StreamActionSpec { +export interface StreamActionSpec extends RegisteredActionSpec { readonly names: string[]; readonly params: S; parse(raw: JsonObject): CoerceResult>; - describe(): ActionDoc; - register(h: ApiHandler, ctx: ApiActionContext): void; } export function defineStreamAction(def: StreamActionDef): StreamActionSpec { @@ -639,6 +645,6 @@ export function groupUserAction( /** Register many specs onto an ApiHandler. Coexists with legacy * `h.registerAction(name, fn)` in the same `register(h, ctx)`. */ -export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray>): void { +export function registerActions(h: ApiHandler, ctx: ApiActionContext, specs: ReadonlyArray): void { for (const spec of specs) spec.register(h, ctx); } diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 785c6cb9..ea34c725 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,9 +1,9 @@ import { readFile } from 'node:fs/promises'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import type { ApiActionContext } from '../api-handler'; import { asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { JsonObject, RETCODE, failedResponse, okResponse } from '../types'; -import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; +import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; @@ -2261,20 +2261,6 @@ async function fetchFilteredGroupRequests(ctx: ApiActionContext) { } } -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); - - // .handle_quick_operation 仍保留 legacy:它需要把 ApiHandler 本身 (h) 交给 - // executeQuickOperation 去回灌动作,而 action-kit 的 run 只提供 (p, ctx, raw)、不含 h。 - h.registerAction('.handle_quick_operation', async (params) => { - const context = params.context as JsonObject | undefined; - const operation = params.operation as Record | undefined; - if (!context || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); - const { executeQuickOperation } = await import('../network/quick-operation'); - await executeQuickOperation(context, operation, h); - return okResponse(); - }); -} function hexToBytes(hex: string): Uint8Array { const out = new Uint8Array(hex.length / 2); diff --git a/packages/onebot/src/actions/friend.ts b/packages/onebot/src/actions/friend.ts index 49bb4fb2..f9279239 100644 --- a/packages/onebot/src/actions/friend.ts +++ b/packages/onebot/src/actions/friend.ts @@ -1,5 +1,4 @@ -import { defineAction, registerActions, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { defineAction, f } from '../action-kit'; import { okResponse } from '../types'; export const actions = [ @@ -68,6 +67,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/group-admin.ts b/packages/onebot/src/actions/group-admin.ts index 74d625fe..383d6163 100644 --- a/packages/onebot/src/actions/group-admin.ts +++ b/packages/onebot/src/actions/group-admin.ts @@ -1,5 +1,4 @@ -import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; import { okResponse } from '../types'; export const actions = [ @@ -126,6 +125,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/group-album.ts b/packages/onebot/src/actions/group-album.ts index 1c750118..0743b4f2 100644 --- a/packages/onebot/src/actions/group-album.ts +++ b/packages/onebot/src/actions/group-album.ts @@ -1,5 +1,4 @@ -import { groupAction, registerActions, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { groupAction, f } from '../action-kit'; import type { JsonValue } from '../types'; import { okResponse } from '../types'; @@ -168,6 +167,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 434b2df6..9920c260 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -1,5 +1,4 @@ -import { defineAction, groupAction, registerActions, f } from '../action-kit'; -import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { defineAction, groupAction, f } from '../action-kit'; import { RETCODE, failedResponse, okResponse } from '../types'; // NapCat/LLOneBot omit `busid` from their `get_group_file_url` schema entirely, @@ -286,6 +285,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 83a8cc46..34515558 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -1,5 +1,4 @@ -import { defineAction, groupAction, groupUserAction, registerActions, f } from '../action-kit'; -import type { ApiHandler, ApiActionContext } from '../api-handler'; +import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; import { asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; import { WebHonorType } from '@snowluma/protocol/web/group-honor'; @@ -179,6 +178,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/index.ts b/packages/onebot/src/actions/index.ts new file mode 100644 index 00000000..5fbd5e92 --- /dev/null +++ b/packages/onebot/src/actions/index.ts @@ -0,0 +1,48 @@ +// Action registry barrel — the single source of "which files contribute which +// actions", replacing three hand-synced lists that had to stay in lock-step: +// 1. ApiHandler's 12 `register as registerX` imports + 12 constructor calls, +// 2. each file's `export function register(h, ctx)` footer, +// 3. action-docs' own 13 imports + GROUPS array. +// Adding an action file now means editing exactly one place: ACTION_GROUPS. +// +// "Source file = domain category" is the existing convention (see action-docs), +// so the category label lives here too, making ACTION_GROUPS serve both runtime +// registration (via ALL_ACTIONS) and the doc collector (via the groups). + +import type { RegisteredActionSpec } from '../action-kit'; +import { actions as infoActions } from './info'; +import { actions as messageActions } from './message'; +import { actions as friendActions } from './friend'; +import { actions as groupInfoActions } from './group-info'; +import { actions as groupAdminActions } from './group-admin'; +import { actions as groupFileActions } from './group-file'; +import { actions as requestActions } from './request'; +import { actions as extendedActions } from './extended'; +import { actions as groupAlbumActions } from './group-album'; +import { actions as qzoneActions } from './qzone'; +import { actions as streamFileActions } from './stream-file'; +import { actions as streamDownloadActions } from './stream-download'; + +export interface ActionGroup { + /** Domain category (= source file), surfaced to the MCP / UI for grouping. */ + readonly category: string; + readonly actions: readonly RegisteredActionSpec[]; +} + +/** Every action, grouped by domain category. The single source of truth. */ +export const ACTION_GROUPS: readonly ActionGroup[] = [ + { category: '信息', actions: infoActions }, + { category: '消息', actions: messageActions }, + { category: '好友', actions: friendActions }, + { category: '群信息', actions: groupInfoActions }, + { category: '群管理', actions: groupAdminActions }, + { category: '群文件', actions: groupFileActions }, + { category: '请求', actions: requestActions }, + { category: '扩展', actions: extendedActions }, + { category: '群相册', actions: groupAlbumActions }, + { category: '空间', actions: qzoneActions }, + { category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] }, +]; + +/** Flat list of every action spec, for one-shot registration onto an ApiHandler. */ +export const ALL_ACTIONS: readonly RegisteredActionSpec[] = ACTION_GROUPS.flatMap((g) => g.actions); diff --git a/packages/onebot/src/actions/info.ts b/packages/onebot/src/actions/info.ts index a489c7c7..2fa50e2d 100644 --- a/packages/onebot/src/actions/info.ts +++ b/packages/onebot/src/actions/info.ts @@ -1,5 +1,4 @@ -import { defineAction, registerActions } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { defineAction } from '../action-kit'; import { okResponse } from '../types'; // 后续考虑移动到一个统一的地方构建,避免版本信息分散在各个模块中。 @@ -98,6 +97,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index dfa589eb..b1aca91d 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -1,7 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { JsonObject, JsonValue } from '../types'; -import type { ApiHandler, ApiActionContext } from '../api-handler'; -import { defineAction, groupAction, registerActions, f } from '../action-kit'; +import type { ApiActionContext } from '../api-handler'; +import { defineAction, groupAction, f } from '../action-kit'; import { RETCODE, failedResponse, okResponse } from '../types'; const log = createLogger('OneBot'); @@ -119,6 +119,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/qzone.ts b/packages/onebot/src/actions/qzone.ts index 9cfec395..d3924b2b 100644 --- a/packages/onebot/src/actions/qzone.ts +++ b/packages/onebot/src/actions/qzone.ts @@ -1,5 +1,5 @@ -import { defineAction, registerActions, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { defineAction, f } from '../action-kit'; +import type { ApiActionContext } from '../api-handler'; import type { JsonValue } from '../types'; import { okResponse } from '../types'; @@ -204,6 +204,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/request.ts b/packages/onebot/src/actions/request.ts index 18348c76..1a386a3e 100644 --- a/packages/onebot/src/actions/request.ts +++ b/packages/onebot/src/actions/request.ts @@ -1,5 +1,4 @@ -import { defineAction, registerActions, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import { defineAction, f } from '../action-kit'; import { asString } from '../api-handler'; import { okResponse } from '../types'; @@ -37,6 +36,3 @@ export const actions = [ }), ]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - registerActions(h, ctx, actions); -} diff --git a/packages/onebot/src/actions/stream-download.ts b/packages/onebot/src/actions/stream-download.ts index d9ff1fcb..b8a476c6 100644 --- a/packages/onebot/src/actions/stream-download.ts +++ b/packages/onebot/src/actions/stream-download.ts @@ -23,7 +23,7 @@ import net from 'net'; import dns from 'dns/promises'; import { resolveLocalFilePath } from '@snowluma/protocol/highway/utils'; import { defineStreamAction, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import type { ApiActionContext } from '../api-handler'; import { okResponse, type ApiResponse, type JsonObject, type JsonValue } from '../types'; import { type StreamSink, StreamStatus } from '../streaming'; import { STREAM_ROOT } from './stream-file'; @@ -370,9 +370,5 @@ const testDownloadStream = defineStreamAction({ export const actions = [downloadFileStream, downloadFileImageStream, downloadFileRecordStream, testDownloadStream]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - for (const a of actions) a.register(h, ctx); -} - // Exposed for tests. export const __test = { resolveDownload, isWithinStreamRoot, isPrivateIp, assertSafeUrl, streamChunks, runDownload }; diff --git a/packages/onebot/src/actions/stream-file.ts b/packages/onebot/src/actions/stream-file.ts index 889d2a0a..b44d76d5 100644 --- a/packages/onebot/src/actions/stream-file.ts +++ b/packages/onebot/src/actions/stream-file.ts @@ -23,7 +23,7 @@ import fs from 'fs'; import { createHash } from 'crypto'; import { createLogger } from '@snowluma/common/logger'; import { defineAction, defineStreamAction, f } from '../action-kit'; -import type { ApiActionContext, ApiHandler } from '../api-handler'; +import type { ApiActionContext } from '../api-handler'; import { okResponse, type ApiResponse } from '../types'; import { StreamStatus } from '../streaming'; @@ -361,9 +361,5 @@ const cleanStreamTempFile = defineAction({ export const actions = [uploadFileStream, cleanStreamTempFile]; -export function register(h: ApiHandler, ctx: ApiActionContext): void { - for (const a of actions) a.register(h, ctx); -} - // Exposed for tests. export const __test = { uploads, handleUpload, cleanDir, validateStreamId, STREAM_UPLOAD_DIR, MAX_CONCURRENT_STREAMS, MAX_CHUNKS }; diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index b512d0b4..ab121eeb 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,21 +1,11 @@ import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary'; import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; -import { register as registerExtended } from './actions/extended'; -import { register as registerFriend } from './actions/friend'; -import { register as registerGroupAdmin } from './actions/group-admin'; -import { register as registerGroupAlbum } from './actions/group-album'; -import { register as registerGroupFile } from './actions/group-file'; -import { register as registerGroupInfo } from './actions/group-info'; -import { register as registerInfo } from './actions/info'; -import { register as registerMessage } from './actions/message'; -import { register as registerQzone } from './actions/qzone'; -import { register as registerRequest } from './actions/request'; -import { register as registerStreamFile } from './actions/stream-file'; -import { register as registerStreamDownload } from './actions/stream-download'; +import { ALL_ACTIONS } from './actions'; +import { registerActions } from './action-kit'; import type { ForwardPreviewMeta } from './modules/message-actions'; import type { JsonObject, JsonValue, MessageMeta } from './types'; -import { RETCODE, failedResponse } from './types'; +import { RETCODE, failedResponse, okResponse } from './types'; import { type StreamSink, wrapStreamFrame, wrapStreamTerminal } from './streaming'; const moduleLog = createLogger('Bridge.Action'); @@ -112,18 +102,20 @@ export class ApiHandler { constructor(context: ApiActionContext, uin?: number) { this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog; - registerInfo(this, context); - registerMessage(this, context); - registerFriend(this, context); - registerGroupInfo(this, context); - registerGroupAdmin(this, context); - registerGroupFile(this, context); - registerRequest(this, context); - registerExtended(this, context); - registerGroupAlbum(this, context); - registerQzone(this, context); - registerStreamFile(this, context); - registerStreamDownload(this, context); + registerActions(this, context, ALL_ACTIONS); + + // The one non-ActionSpec handler: `.handle_quick_operation` needs the + // ApiHandler itself (to re-drive actions via executeQuickOperation), which + // ActionSpec.run's (params, ctx) signature can't supply — so it's the sole + // raw registration, kept here rather than in an action file's footer. + this.registerAction('.handle_quick_operation', async (params) => { + const opContext = params.context as JsonObject | undefined; + const operation = params.operation as Record | undefined; + if (!opContext || !operation) return failedResponse(RETCODE.BAD_REQUEST, 'context and operation are required'); + const { executeQuickOperation } = await import('./network/quick-operation'); + await executeQuickOperation(opContext, operation, this); + return okResponse(); + }); } registerAction(action: string, handler: ActionHandler): void { From ae17bc0cf561d3131bd777147a08d34aa9e93f40 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 17:58:49 +0800 Subject: [PATCH 16/30] refactor(onebot): extract event envelope builders; collapse message triplets MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 1(零行为改动):消掉 17 个 converter 各手搓的 time/self_id/post_type 信封, 合并 message 三胞胎。 - 新增 event-converter/envelope.ts:notice/request/message 三个信封 builder, converter 只供应各自 post_type 的字段。 - to-notice(12)/to-request(2) 改用 notice()/request()。 - to-message:friend+temp 合成 convertPrivateMessage(subType)(仅 sub_type 差), group 独立;新增 toSegments 收敛 7 参 elementsToJson splat。导出名不变。 行为 byte 级不变(测试 toEqual 顺序无关,key 集合与值逐一保持):event-converter 48 + onebot 全量 516 全绿、typecheck 干净;对抗性 Agent 逐 converter 对比 HEAD 确认 16 个输出等价、无字段增减/值变、无运行时循环。 --- .../onebot/src/event-converter/envelope.ts | 27 ++++++ .../onebot/src/event-converter/to-message.ts | 86 ++++++++----------- .../onebot/src/event-converter/to-notice.ts | 85 ++++++------------ .../onebot/src/event-converter/to-request.ts | 15 ++-- 4 files changed, 91 insertions(+), 122 deletions(-) create mode 100644 packages/onebot/src/event-converter/envelope.ts diff --git a/packages/onebot/src/event-converter/envelope.ts b/packages/onebot/src/event-converter/envelope.ts new file mode 100644 index 00000000..e4479cca --- /dev/null +++ b/packages/onebot/src/event-converter/envelope.ts @@ -0,0 +1,27 @@ +import type { JsonObject } from '../types'; +import type { ConverterContext } from './index'; + +// The OneBot post header every converted event shares: `time` + `self_id` + +// `post_type`. Previously each of the ~17 converters hand-wrote it, so the +// shared shape could drift. These builders concentrate it — a converter just +// supplies its `post_type`-specific fields. + +type Timed = { time: number }; + +/** notice envelope — `{ time, self_id, post_type: 'notice', ...fields }`. */ +export function notice(ctx: ConverterContext, event: Timed, fields: JsonObject): JsonObject { + return { time: event.time, self_id: ctx.selfId, post_type: 'notice', ...fields }; +} + +/** request envelope — `{ time, self_id, post_type: 'request', ...fields }`. */ +export function request(ctx: ConverterContext, event: Timed, fields: JsonObject): JsonObject { + return { time: event.time, self_id: ctx.selfId, post_type: 'request', ...fields }; +} + +/** + * message envelope — `{ time, self_id, post_type, ...fields }`. `postType` is + * 'message' or 'message_sent' (self-echo), decided per-message by the caller. + */ +export function message(ctx: ConverterContext, event: Timed, postType: string, fields: JsonObject): JsonObject { + return { time: event.time, self_id: ctx.selfId, post_type: postType, ...fields }; +} diff --git a/packages/onebot/src/event-converter/to-message.ts b/packages/onebot/src/event-converter/to-message.ts index 5f667a95..d6c48ec6 100644 --- a/packages/onebot/src/event-converter/to-message.ts +++ b/packages/onebot/src/event-converter/to-message.ts @@ -1,31 +1,42 @@ -import type { QQEventVariant } from '@snowluma/protocol/events'; +import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events'; import { segmentsToRawMessage } from '../helper/cq'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; import { elementsToJson } from './to-segment'; import { applyMessageIdResolver } from './utils'; +import { message } from './envelope'; type FriendMessage = Extract; type GroupMessage = Extract; type TempMessage = Extract; -export async function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise { +/** Fill the media/id resolvers from ctx — collapses the 7-arg elementsToJson splat. */ +function toSegments(ctx: ConverterContext, elements: MessageElement[], isGroup: boolean, sessionId: number) { + return elementsToJson( + elements, isGroup, sessionId, + ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink, + ); +} + +/** + * friend_message and temp_message differ only in `sub_type` ('friend' vs + * 'group') — both are private, keyed by senderUin, same sender shape. + */ +async function convertPrivateMessage( + ctx: ConverterContext, + event: FriendMessage | TempMessage, + subType: 'friend' | 'group', +): Promise { const isSelf = event.senderUin === ctx.selfId; const postType = isSelf ? 'message_sent' : 'message'; const messageId = applyMessageIdResolver( ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT, ); - const segments = await elementsToJson( - event.elements, false, event.senderUin, - ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink, - ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: postType, + const segments = await toSegments(ctx, event.elements, false, event.senderUin); + return message(ctx, event, postType, { message_type: 'private', - sub_type: 'friend', + sub_type: subType, message_id: messageId, message_seq: event.msgSeq, user_id: event.senderUin, @@ -38,7 +49,15 @@ export async function convertFriendMessage(ctx: ConverterContext, event: FriendM sex: 'unknown', age: 0, }, - }; + }); +} + +export function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise { + return convertPrivateMessage(ctx, event, 'friend'); +} + +export function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise { + return convertPrivateMessage(ctx, event, 'group'); } export async function convertGroupMessage(ctx: ConverterContext, event: GroupMessage): Promise { @@ -47,14 +66,8 @@ export async function convertGroupMessage(ctx: ConverterContext, event: GroupMes const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, ); - const segments = await elementsToJson( - event.elements, true, event.groupId, - ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink, - ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: postType, + const segments = await toSegments(ctx, event.elements, true, event.groupId); + return message(ctx, event, postType, { message_type: 'group', sub_type: 'normal', message_id: messageId, @@ -73,36 +86,5 @@ export async function convertGroupMessage(ctx: ConverterContext, event: GroupMes age: 0, }, anonymous: null, - }; -} - -export async function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise { - const isSelf = event.senderUin === ctx.selfId; - const postType = isSelf ? 'message_sent' : 'message'; - const messageId = applyMessageIdResolver( - ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT, - ); - const segments = await elementsToJson( - event.elements, false, event.senderUin, - ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink, - ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: postType, - message_type: 'private', - sub_type: 'group', - message_id: messageId, - message_seq: event.msgSeq, - user_id: event.senderUin, - message: segments, - raw_message: segmentsToRawMessage(segments), - font: 0, - sender: { - user_id: event.senderUin, - nickname: event.senderNick, - sex: 'unknown', - age: 0, - }, - }; + }); } diff --git a/packages/onebot/src/event-converter/to-notice.ts b/packages/onebot/src/event-converter/to-notice.ts index a5e0788d..05b8b762 100644 --- a/packages/onebot/src/event-converter/to-notice.ts +++ b/packages/onebot/src/event-converter/to-notice.ts @@ -3,6 +3,7 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; import { applyMessageIdResolver, isSameActor } from './utils'; +import { notice } from './envelope'; type GroupMemberJoin = Extract; type GroupMemberLeave = Extract; @@ -18,16 +19,13 @@ type FriendAdd = Extract; type GroupMsgEmojiLike = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_increase', sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite', group_id: event.groupId, operator_id: event.operatorUin, user_id: event.userUin, - }; + }); } export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject { @@ -42,79 +40,61 @@ export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMembe default: subType = 'leave'; } - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_decrease', sub_type: subType, group_id: event.groupId, operator_id: event.operatorUin, user_id: event.userUin, - }; + }); } export function convertGroupMute(ctx: ConverterContext, event: GroupMute): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_ban', sub_type: event.duration > 0 ? 'ban' : 'lift_ban', group_id: event.groupId, operator_id: event.operatorUin, user_id: event.userUin, duration: event.duration, - }; + }); } export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_admin', sub_type: event.set ? 'set' : 'unset', group_id: event.groupId, user_id: event.userUin, - }; + }); } export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject { const messageId = applyMessageIdResolver( ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT, ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'friend_recall', user_id: event.userUin, message_id: messageId, - }; + }); } export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject { const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_recall', group_id: event.groupId, operator_id: event.operatorUin, user_id: event.authorUin, message_id: messageId, - }; + }); } export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'notify', sub_type: 'poke', user_id: event.userUin, @@ -122,14 +102,11 @@ export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): Jso action: event.action, suffix: event.suffix, action_img_url: event.actionImgUrl, - }; + }); } export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'notify', sub_type: 'poke', group_id: event.groupId, @@ -138,17 +115,14 @@ export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonO action: event.action, suffix: event.suffix, action_img_url: event.actionImgUrl, - }; + }); } export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject { const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'essence', sub_type: event.set ? 'add' : 'delete', group_id: event.groupId, @@ -158,14 +132,11 @@ export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): message_id: messageId, message_seq: event.msgSeq, random: event.random, - }; + }); } export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUpload): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_upload', group_id: event.groupId, user_id: event.userUin, @@ -175,27 +146,21 @@ export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUp size: event.fileSize, busid: event.busId, }, - }; + }); } export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'friend_add', user_id: event.userUin, - }; + }); } export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject { const messageId = applyMessageIdResolver( ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, ); - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'notice', + return notice(ctx, event, { notice_type: 'group_msg_emoji_like', sub_type: event.isAdd ? 'add' : 'remove', group_id: event.groupId, @@ -204,5 +169,5 @@ export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgE message_id: messageId, message_seq: event.msgSeq, likes: [{ emoji_id: event.emojiId, count: event.count }], - }; + }); } diff --git a/packages/onebot/src/event-converter/to-request.ts b/packages/onebot/src/event-converter/to-request.ts index 3ef5024d..08ee45f5 100644 --- a/packages/onebot/src/event-converter/to-request.ts +++ b/packages/onebot/src/event-converter/to-request.ts @@ -1,32 +1,27 @@ import type { QQEventVariant } from '@snowluma/protocol/events'; import type { JsonObject } from '../types'; import type { ConverterContext } from './index'; +import { request } from './envelope'; type FriendRequest = Extract; type GroupInvite = Extract; export function convertFriendRequest(ctx: ConverterContext, event: FriendRequest): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'request', + return request(ctx, event, { request_type: 'friend', user_id: event.fromUin, comment: event.message, flag: event.flag, - }; + }); } export function convertGroupInvite(ctx: ConverterContext, event: GroupInvite): JsonObject { - return { - time: event.time, - self_id: ctx.selfId, - post_type: 'request', + return request(ctx, event, { request_type: 'group', sub_type: event.subType || 'invite', group_id: event.groupId, user_id: event.fromUin, comment: event.message, flag: event.flag, - }; + }); } From 15a6fe3785183fbc14d5ffc58b291c7f2af79a56 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 18:03:02 +0800 Subject: [PATCH 17/30] refactor(onebot): make event converter dispatch an exhaustive registry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 2(零行为改动):把 convertEvent 的 17-arm switch 换成 CONVERTERS: { [K in QQEventVariant['kind']]: ConverterFor | null } 表。mapped type 对事件类型联合 total——新增一个 kind 却漏写 converter 会**编译报错**,而非 像原 switch 那样静默走 default: return null。 - ptt_trans_result(内部语音转文字事件,不对外)在表里显式标 null,与原 default 行为等价。 - 派发一次 localized cast 解 correlated-union,纯类型层、运行时等价。 - 护栏实测有效:删任一 kind 条目即 TS2741 编译失败。 onebot 516 全绿、typecheck 干净;对抗性 Agent 逐一核对 17 映射、独立复现护栏报错。 --- packages/onebot/src/event-converter/index.ts | 70 ++++++++++++-------- 1 file changed, 43 insertions(+), 27 deletions(-) diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 0cd17552..5a0b6cf7 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -49,37 +49,53 @@ export interface ConverterContext { // ─────────────── dispatcher ─────────────── +/** Converter for one event kind — receives the narrowed event for that kind. */ +type ConverterFor = + (ctx: ConverterContext, event: Extract) => JsonObject | Promise; + +/** + * Every event kind → its converter (or `null` for kinds intentionally not + * surfaced to OneBot clients). The mapped type is TOTAL over the union, so a + * new `QQEventVariant` kind that forgets a converter is a compile error here — + * not a silent `null` at runtime. + */ +type ConverterRegistry = { [K in QQEventVariant['kind']]: ConverterFor | null }; + +const CONVERTERS: ConverterRegistry = { + // Messages. + friend_message: convertFriendMessage, + group_message: convertGroupMessage, + temp_message: convertTempMessage, + // Notices. + group_member_join: convertGroupMemberJoin, + group_member_leave: convertGroupMemberLeave, + group_mute: convertGroupMute, + group_admin: convertGroupAdmin, + friend_recall: convertFriendRecall, + group_recall: convertGroupRecall, + friend_poke: convertFriendPoke, + group_poke: convertGroupPoke, + group_essence: convertGroupEssence, + group_file_upload: convertGroupFileUpload, + friend_add: convertFriendAdd, + group_msg_emoji_like: convertGroupMsgEmojiLike, + // Requests. + friend_request: convertFriendRequest, + group_invite: convertGroupInvite, + // Internal-only: async voice-to-text result, correlated by a pending + // fetch_ptt_text; never emitted as an OneBot event. + ptt_trans_result: null, +}; + export async function convertEvent( ctx: ConverterContext, event: QQEventVariant, ): Promise { - switch (event.kind) { - // Messages. - case 'friend_message': return convertFriendMessage(ctx, event); - case 'group_message': return convertGroupMessage(ctx, event); - case 'temp_message': return convertTempMessage(ctx, event); - - // Notices. - case 'group_member_join': return convertGroupMemberJoin(ctx, event); - case 'group_member_leave': return convertGroupMemberLeave(ctx, event); - case 'group_mute': return convertGroupMute(ctx, event); - case 'group_admin': return convertGroupAdmin(ctx, event); - case 'friend_recall': return convertFriendRecall(ctx, event); - case 'group_recall': return convertGroupRecall(ctx, event); - case 'friend_poke': return convertFriendPoke(ctx, event); - case 'group_poke': return convertGroupPoke(ctx, event); - case 'group_essence': return convertGroupEssence(ctx, event); - case 'group_file_upload': return convertGroupFileUpload(ctx, event); - case 'friend_add': return convertFriendAdd(ctx, event); - case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event); - - // Requests. - case 'friend_request': return convertFriendRequest(ctx, event); - case 'group_invite': return convertGroupInvite(ctx, event); - - default: - return null; - } + const converter = CONVERTERS[event.kind]; + if (!converter) return null; + // The registry ties each key to its own event kind, but indexing by a + // runtime `event.kind` loses that correlation — one localized cast restores it. + return (converter as (ctx: ConverterContext, event: QQEventVariant) => JsonObject | Promise)(ctx, event); } export async function elementsToOneBotSegments( From d89b095af5fcb6ac517500701c51e8a5bef31e9d Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 18:30:45 +0800 Subject: [PATCH 18/30] refactor(protocol,proto-defs): fold 1:1 subpath exports into wildcards MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit protocol/package.json 有 273 行专给 91 个 oidb-service(每个 3 行 1:1);加一个 service 忘改 package.json → build 期解析失败。把所有严格 1:1 的目录组折叠成通配符 (moduleResolution:"bundler" 原生支持),消除永久手同步负担。 - protocol:./oidb-services/*(91) + ./highway/*(7) + ./web/*(7) + ./msg-push/*(3); bare ./msg-push / ./highway(exact)与单文件 export 原样保留。 - proto-defs:./oidb-actions/*(10)。 - 净 -467/+15 行;两包均 private:true,通配新暴露的少量内部文件无害(exports 只 gate 跨包解析、无外部消费者、无副作用)。 零源码/import 改动。全套工具链验证:12 包 typecheck Done、protocol/onebot(516)/ core(467)/mcp(22) 测试全绿;对抗性 Agent 端到端解析 136 个真实深导入全部命中、 确认 exact/wildcard 共存正确。 --- packages/proto-defs/package.json | 42 +-- packages/protocol/package.json | 440 +------------------------------ 2 files changed, 15 insertions(+), 467 deletions(-) diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 1dbdc780..bb23b6a0 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -56,45 +56,9 @@ "types": "./src/oidb-action.ts", "default": "./src/oidb-action.ts" }, - "./oidb-actions/base": { - "types": "./src/oidb-actions/base.ts", - "default": "./src/oidb-actions/base.ts" - }, - "./oidb-actions/contact-ark": { - "types": "./src/oidb-actions/contact-ark.ts", - "default": "./src/oidb-actions/contact-ark.ts" - }, - "./oidb-actions/doubt-buddy": { - "types": "./src/oidb-actions/doubt-buddy.ts", - "default": "./src/oidb-actions/doubt-buddy.ts" - }, - "./oidb-actions/group-ext": { - "types": "./src/oidb-actions/group-ext.ts", - "default": "./src/oidb-actions/group-ext.ts" - }, - "./oidb-actions/group-album": { - "types": "./src/oidb-actions/group-album.ts", - "default": "./src/oidb-actions/group-album.ts" - }, - "./oidb-actions/group-file": { - "types": "./src/oidb-actions/group-file.ts", - "default": "./src/oidb-actions/group-file.ts" - }, - "./oidb-actions/flash-transfer": { - "types": "./src/oidb-actions/flash-transfer.ts", - "default": "./src/oidb-actions/flash-transfer.ts" - }, - "./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" - }, - "./oidb-actions/sys-faces": { - "types": "./src/oidb-actions/sys-faces.ts", - "default": "./src/oidb-actions/sys-faces.ts" + "./oidb-actions/*": { + "types": "./src/oidb-actions/*.ts", + "default": "./src/oidb-actions/*.ts" } }, "scripts": { diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 8f174814..04ae27fa 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -44,369 +44,9 @@ "types": "./src/oidb-service.ts", "default": "./src/oidb-service.ts" }, - "./oidb-services/reaction/set-reaction": { - "types": "./src/oidb-services/reaction/set-reaction.ts", - "default": "./src/oidb-services/reaction/set-reaction.ts" - }, - "./oidb-services/reaction/fetch-reaction-summary": { - "types": "./src/oidb-services/reaction/fetch-reaction-summary.ts", - "default": "./src/oidb-services/reaction/fetch-reaction-summary.ts" - }, - "./oidb-services/reaction/get-emoji-likes": { - "types": "./src/oidb-services/reaction/get-emoji-likes.ts", - "default": "./src/oidb-services/reaction/get-emoji-likes.ts" - }, - "./oidb-services/custom-face/delete-custom-face": { - "types": "./src/oidb-services/custom-face/delete-custom-face.ts", - "default": "./src/oidb-services/custom-face/delete-custom-face.ts" - }, - "./oidb-services/custom-face/add-custom-face": { - "types": "./src/oidb-services/custom-face/add-custom-face.ts", - "default": "./src/oidb-services/custom-face/add-custom-face.ts" - }, - "./oidb-services/custom-face/modify-custom-face": { - "types": "./src/oidb-services/custom-face/modify-custom-face.ts", - "default": "./src/oidb-services/custom-face/modify-custom-face.ts" - }, - "./oidb-services/custom-face/move-custom-face": { - "types": "./src/oidb-services/custom-face/move-custom-face.ts", - "default": "./src/oidb-services/custom-face/move-custom-face.ts" - }, - "./oidb-services/custom-face/order-custom-face": { - "types": "./src/oidb-services/custom-face/order-custom-face.ts", - "default": "./src/oidb-services/custom-face/order-custom-face.ts" - }, - "./oidb-services/flash-transfer/get-fileset-detail": { - "types": "./src/oidb-services/flash-transfer/get-fileset-detail.ts", - "default": "./src/oidb-services/flash-transfer/get-fileset-detail.ts" - }, - "./oidb-services/flash-transfer/list-filesets": { - "types": "./src/oidb-services/flash-transfer/list-filesets.ts", - "default": "./src/oidb-services/flash-transfer/list-filesets.ts" - }, - "./oidb-services/flash-transfer/get-download-url": { - "types": "./src/oidb-services/flash-transfer/get-download-url.ts", - "default": "./src/oidb-services/flash-transfer/get-download-url.ts" - }, - "./oidb-services/flash-transfer/delete-file": { - "types": "./src/oidb-services/flash-transfer/delete-file.ts", - "default": "./src/oidb-services/flash-transfer/delete-file.ts" - }, - "./oidb-services/flash-transfer/rename-file": { - "types": "./src/oidb-services/flash-transfer/rename-file.ts", - "default": "./src/oidb-services/flash-transfer/rename-file.ts" - }, - "./oidb-services/flash-transfer/apply-fileset": { - "types": "./src/oidb-services/flash-transfer/apply-fileset.ts", - "default": "./src/oidb-services/flash-transfer/apply-fileset.ts" - }, - "./oidb-services/flash-transfer/commit-file": { - "types": "./src/oidb-services/flash-transfer/commit-file.ts", - "default": "./src/oidb-services/flash-transfer/commit-file.ts" - }, - "./oidb-services/flash-transfer/complete-fileset": { - "types": "./src/oidb-services/flash-transfer/complete-fileset.ts", - "default": "./src/oidb-services/flash-transfer/complete-fileset.ts" - }, - "./oidb-services/flash-transfer/set-status": { - "types": "./src/oidb-services/flash-transfer/set-status.ts", - "default": "./src/oidb-services/flash-transfer/set-status.ts" - }, - "./oidb-services/flash-transfer/apply-upload": { - "types": "./src/oidb-services/flash-transfer/apply-upload.ts", - "default": "./src/oidb-services/flash-transfer/apply-upload.ts" - }, - "./oidb-services/flash-transfer/prepare-upload": { - "types": "./src/oidb-services/flash-transfer/prepare-upload.ts", - "default": "./src/oidb-services/flash-transfer/prepare-upload.ts" - }, - "./oidb-services/flash-transfer/send-flash": { - "types": "./src/oidb-services/flash-transfer/send-flash.ts", - "default": "./src/oidb-services/flash-transfer/send-flash.ts" - }, - "./oidb-services/flash-transfer/get-flash-download": { - "types": "./src/oidb-services/flash-transfer/get-flash-download.ts", - "default": "./src/oidb-services/flash-transfer/get-flash-download.ts" - }, - "./oidb-services/interaction/send-poke": { - "types": "./src/oidb-services/interaction/send-poke.ts", - "default": "./src/oidb-services/interaction/send-poke.ts" - }, - "./oidb-services/interaction/send-like": { - "types": "./src/oidb-services/interaction/send-like.ts", - "default": "./src/oidb-services/interaction/send-like.ts" - }, - "./oidb-services/interaction/set-essence": { - "types": "./src/oidb-services/interaction/set-essence.ts", - "default": "./src/oidb-services/interaction/set-essence.ts" - }, - "./oidb-services/profile/set-profile": { - "types": "./src/oidb-services/profile/set-profile.ts", - "default": "./src/oidb-services/profile/set-profile.ts" - }, - "./oidb-services/profile/set-self-long-nick": { - "types": "./src/oidb-services/profile/set-self-long-nick.ts", - "default": "./src/oidb-services/profile/set-self-long-nick.ts" - }, - "./oidb-services/profile/set-input-status": { - "types": "./src/oidb-services/profile/set-input-status.ts", - "default": "./src/oidb-services/profile/set-input-status.ts" - }, - "./oidb-services/profile/get-like": { - "types": "./src/oidb-services/profile/get-like.ts", - "default": "./src/oidb-services/profile/get-like.ts" - }, - "./oidb-services/profile/get-unidirectional-friend-list": { - "types": "./src/oidb-services/profile/get-unidirectional-friend-list.ts", - "default": "./src/oidb-services/profile/get-unidirectional-friend-list.ts" - }, - "./oidb-services/friend/handle-friend-request": { - "types": "./src/oidb-services/friend/handle-friend-request.ts", - "default": "./src/oidb-services/friend/handle-friend-request.ts" - }, - "./oidb-services/friend/get-doubt-buddy-req": { - "types": "./src/oidb-services/friend/get-doubt-buddy-req.ts", - "default": "./src/oidb-services/friend/get-doubt-buddy-req.ts" - }, - "./oidb-services/friend/approve-doubt-buddy-req": { - "types": "./src/oidb-services/friend/approve-doubt-buddy-req.ts", - "default": "./src/oidb-services/friend/approve-doubt-buddy-req.ts" - }, - "./oidb-services/friend/reject-doubt-buddy-req": { - "types": "./src/oidb-services/friend/reject-doubt-buddy-req.ts", - "default": "./src/oidb-services/friend/reject-doubt-buddy-req.ts" - }, - "./oidb-services/contacts/get-buddy-recommend-ark": { - "types": "./src/oidb-services/contacts/get-buddy-recommend-ark.ts", - "default": "./src/oidb-services/contacts/get-buddy-recommend-ark.ts" - }, - "./oidb-services/contacts/get-group-recommend-ark": { - "types": "./src/oidb-services/contacts/get-group-recommend-ark.ts", - "default": "./src/oidb-services/contacts/get-group-recommend-ark.ts" - }, - "./oidb-services/group-admin/modify-group-ext-info": { - "types": "./src/oidb-services/group-admin/modify-group-ext-info.ts", - "default": "./src/oidb-services/group-admin/modify-group-ext-info.ts" - }, - "./oidb-services/friend/delete-friend": { - "types": "./src/oidb-services/friend/delete-friend.ts", - "default": "./src/oidb-services/friend/delete-friend.ts" - }, - "./oidb-services/friend/set-friend-remark": { - "types": "./src/oidb-services/friend/set-friend-remark.ts", - "default": "./src/oidb-services/friend/set-friend-remark.ts" - }, - "./oidb-services/misc/translate-en-to-zh": { - "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" - }, - "./oidb-services/misc/send-group-sign": { - "types": "./src/oidb-services/misc/send-group-sign.ts", - "default": "./src/oidb-services/misc/send-group-sign.ts" - }, - "./oidb-services/misc/request-decrypt-key": { - "types": "./src/oidb-services/misc/request-decrypt-key.ts", - "default": "./src/oidb-services/misc/request-decrypt-key.ts" - }, - "./oidb-services/web/force-fetch-client-key": { - "types": "./src/oidb-services/web/force-fetch-client-key.ts", - "default": "./src/oidb-services/web/force-fetch-client-key.ts" - }, - "./oidb-services/web/get-pskey": { - "types": "./src/oidb-services/web/get-pskey.ts", - "default": "./src/oidb-services/web/get-pskey.ts" - }, - "./oidb-services/extras/group-todo": { - "types": "./src/oidb-services/extras/group-todo.ts", - "default": "./src/oidb-services/extras/group-todo.ts" - }, - "./oidb-services/extras/get-stranger-status": { - "types": "./src/oidb-services/extras/get-stranger-status.ts", - "default": "./src/oidb-services/extras/get-stranger-status.ts" - }, - "./oidb-services/extras/fetch-ai-voice-list": { - "types": "./src/oidb-services/extras/fetch-ai-voice-list.ts", - "default": "./src/oidb-services/extras/fetch-ai-voice-list.ts" - }, - "./oidb-services/extras/fetch-ai-voice": { - "types": "./src/oidb-services/extras/fetch-ai-voice.ts", - "default": "./src/oidb-services/extras/fetch-ai-voice.ts" - }, - "./oidb-services/contacts/fetch-friend-list-page": { - "types": "./src/oidb-services/contacts/fetch-friend-list-page.ts", - "default": "./src/oidb-services/contacts/fetch-friend-list-page.ts" - }, - "./oidb-services/contacts/fetch-group-detail": { - "types": "./src/oidb-services/contacts/fetch-group-detail.ts", - "default": "./src/oidb-services/contacts/fetch-group-detail.ts" - }, - "./oidb-services/contacts/fetch-group-list": { - "types": "./src/oidb-services/contacts/fetch-group-list.ts", - "default": "./src/oidb-services/contacts/fetch-group-list.ts" - }, - "./oidb-services/contacts/fetch-group-member-list-page": { - "types": "./src/oidb-services/contacts/fetch-group-member-list-page.ts", - "default": "./src/oidb-services/contacts/fetch-group-member-list-page.ts" - }, - "./oidb-services/contacts/fetch-user-profile": { - "types": "./src/oidb-services/contacts/fetch-user-profile.ts", - "default": "./src/oidb-services/contacts/fetch-user-profile.ts" - }, - "./oidb-services/contacts/fetch-user-profile-by-uid": { - "types": "./src/oidb-services/contacts/fetch-user-profile-by-uid.ts", - "default": "./src/oidb-services/contacts/fetch-user-profile-by-uid.ts" - }, - "./oidb-services/contacts/fetch-group-requests": { - "types": "./src/oidb-services/contacts/fetch-group-requests.ts", - "default": "./src/oidb-services/contacts/fetch-group-requests.ts" - }, - "./oidb-services/contacts/fetch-download-rkeys": { - "types": "./src/oidb-services/contacts/fetch-download-rkeys.ts", - "default": "./src/oidb-services/contacts/fetch-download-rkeys.ts" - }, - "./oidb-services/group-admin/mute-member": { - "types": "./src/oidb-services/group-admin/mute-member.ts", - "default": "./src/oidb-services/group-admin/mute-member.ts" - }, - "./oidb-services/group-admin/mute-all": { - "types": "./src/oidb-services/group-admin/mute-all.ts", - "default": "./src/oidb-services/group-admin/mute-all.ts" - }, - "./oidb-services/group-admin/set-add-option": { - "types": "./src/oidb-services/group-admin/set-add-option.ts", - "default": "./src/oidb-services/group-admin/set-add-option.ts" - }, - "./oidb-services/group-admin/set-search": { - "types": "./src/oidb-services/group-admin/set-search.ts", - "default": "./src/oidb-services/group-admin/set-search.ts" - }, - "./oidb-services/group-admin/set-add-request": { - "types": "./src/oidb-services/group-admin/set-add-request.ts", - "default": "./src/oidb-services/group-admin/set-add-request.ts" - }, - "./oidb-services/group-admin/kick-member": { - "types": "./src/oidb-services/group-admin/kick-member.ts", - "default": "./src/oidb-services/group-admin/kick-member.ts" - }, - "./oidb-services/group-admin/kick-members": { - "types": "./src/oidb-services/group-admin/kick-members.ts", - "default": "./src/oidb-services/group-admin/kick-members.ts" - }, - "./oidb-services/group-admin/leave-group": { - "types": "./src/oidb-services/group-admin/leave-group.ts", - "default": "./src/oidb-services/group-admin/leave-group.ts" - }, - "./oidb-services/group-admin/set-admin": { - "types": "./src/oidb-services/group-admin/set-admin.ts", - "default": "./src/oidb-services/group-admin/set-admin.ts" - }, - "./oidb-services/group-admin/set-member-card": { - "types": "./src/oidb-services/group-admin/set-member-card.ts", - "default": "./src/oidb-services/group-admin/set-member-card.ts" - }, - "./oidb-services/group-admin/set-group-name": { - "types": "./src/oidb-services/group-admin/set-group-name.ts", - "default": "./src/oidb-services/group-admin/set-group-name.ts" - }, - "./oidb-services/group-admin/set-special-title": { - "types": "./src/oidb-services/group-admin/set-special-title.ts", - "default": "./src/oidb-services/group-admin/set-special-title.ts" - }, - "./oidb-services/group-admin/set-group-remark": { - "types": "./src/oidb-services/group-admin/set-group-remark.ts", - "default": "./src/oidb-services/group-admin/set-group-remark.ts" - }, - "./oidb-services/group-admin/get-at-all-remain": { - "types": "./src/oidb-services/group-admin/get-at-all-remain.ts", - "default": "./src/oidb-services/group-admin/get-at-all-remain.ts" - }, - "./oidb-services/shared": { - "types": "./src/oidb-services/shared.ts", - "default": "./src/oidb-services/shared.ts" - }, - "./oidb-services/group-file/publish-group-file": { - "types": "./src/oidb-services/group-file/publish-group-file.ts", - "default": "./src/oidb-services/group-file/publish-group-file.ts" - }, - "./oidb-services/group-file/trans-group-file": { - "types": "./src/oidb-services/group-file/trans-group-file.ts", - "default": "./src/oidb-services/group-file/trans-group-file.ts" - }, - "./oidb-services/group-file/get-group-file-count": { - "types": "./src/oidb-services/group-file/get-group-file-count.ts", - "default": "./src/oidb-services/group-file/get-group-file-count.ts" - }, - "./oidb-services/group-file/upload-group-file-request": { - "types": "./src/oidb-services/group-file/upload-group-file-request.ts", - "default": "./src/oidb-services/group-file/upload-group-file-request.ts" - }, - "./oidb-services/group-file/upload-private-file-request": { - "types": "./src/oidb-services/group-file/upload-private-file-request.ts", - "default": "./src/oidb-services/group-file/upload-private-file-request.ts" - }, - "./oidb-services/group-file/finalize-offline-file": { - "types": "./src/oidb-services/group-file/finalize-offline-file.ts", - "default": "./src/oidb-services/group-file/finalize-offline-file.ts" - }, - "./oidb-services/group-file/list-group-files-page": { - "types": "./src/oidb-services/group-file/list-group-files-page.ts", - "default": "./src/oidb-services/group-file/list-group-files-page.ts" - }, - "./oidb-services/group-file/get-group-file-url": { - "types": "./src/oidb-services/group-file/get-group-file-url.ts", - "default": "./src/oidb-services/group-file/get-group-file-url.ts" - }, - "./oidb-services/group-file/get-private-file-url": { - "types": "./src/oidb-services/group-file/get-private-file-url.ts", - "default": "./src/oidb-services/group-file/get-private-file-url.ts" - }, - "./oidb-services/group-file/delete-group-file": { - "types": "./src/oidb-services/group-file/delete-group-file.ts", - "default": "./src/oidb-services/group-file/delete-group-file.ts" - }, - "./oidb-services/group-file/move-group-file": { - "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" - }, - "./oidb-services/group-file/delete-group-folder": { - "types": "./src/oidb-services/group-file/delete-group-folder.ts", - "default": "./src/oidb-services/group-file/delete-group-folder.ts" - }, - "./oidb-services/group-file/rename-group-folder": { - "types": "./src/oidb-services/group-file/rename-group-folder.ts", - "default": "./src/oidb-services/group-file/rename-group-folder.ts" - }, - "./oidb-services/group-file/get-group-ptt-url": { - "types": "./src/oidb-services/group-file/get-group-ptt-url.ts", - "default": "./src/oidb-services/group-file/get-group-ptt-url.ts" - }, - "./oidb-services/group-file/get-private-ptt-url": { - "types": "./src/oidb-services/group-file/get-private-ptt-url.ts", - "default": "./src/oidb-services/group-file/get-private-ptt-url.ts" - }, - "./oidb-services/group-file/get-group-video-url": { - "types": "./src/oidb-services/group-file/get-group-video-url.ts", - "default": "./src/oidb-services/group-file/get-group-video-url.ts" - }, - "./oidb-services/group-file/get-private-video-url": { - "types": "./src/oidb-services/group-file/get-private-video-url.ts", - "default": "./src/oidb-services/group-file/get-private-video-url.ts" + "./oidb-services/*": { + "types": "./src/oidb-services/*.ts", + "default": "./src/oidb-services/*.ts" }, "./bridge-context": { "types": "./src/bridge-context.ts", @@ -424,77 +64,21 @@ "types": "./src/msg-push/index.ts", "default": "./src/msg-push/index.ts" }, - "./msg-push/registry": { - "types": "./src/msg-push/registry.ts", - "default": "./src/msg-push/registry.ts" - }, - "./msg-push/context": { - "types": "./src/msg-push/context.ts", - "default": "./src/msg-push/context.ts" - }, - "./msg-push/decoders/event-0x2dc": { - "types": "./src/msg-push/decoders/event-0x2dc.ts", - "default": "./src/msg-push/decoders/event-0x2dc.ts" + "./msg-push/*": { + "types": "./src/msg-push/*.ts", + "default": "./src/msg-push/*.ts" }, "./highway": { "types": "./src/highway/highway-client.ts", "default": "./src/highway/highway-client.ts" }, - "./highway/utils": { - "types": "./src/highway/utils.ts", - "default": "./src/highway/utils.ts" + "./highway/*": { + "types": "./src/highway/*.ts", + "default": "./src/highway/*.ts" }, - "./highway/sha1-stream": { - "types": "./src/highway/sha1-stream.ts", - "default": "./src/highway/sha1-stream.ts" - }, - "./highway/pipeline": { - "types": "./src/highway/pipeline.ts", - "default": "./src/highway/pipeline.ts" - }, - "./highway/image-upload": { - "types": "./src/highway/image-upload.ts", - "default": "./src/highway/image-upload.ts" - }, - "./highway/ptt-upload": { - "types": "./src/highway/ptt-upload.ts", - "default": "./src/highway/ptt-upload.ts" - }, - "./highway/video-upload": { - "types": "./src/highway/video-upload.ts", - "default": "./src/highway/video-upload.ts" - }, - "./highway/ffmpeg-addon": { - "types": "./src/highway/ffmpeg-addon.ts", - "default": "./src/highway/ffmpeg-addon.ts" - }, - "./web/group-album": { - "types": "./src/web/group-album.ts", - "default": "./src/web/group-album.ts" - }, - "./web/group-essence": { - "types": "./src/web/group-essence.ts", - "default": "./src/web/group-essence.ts" - }, - "./web/group-honor": { - "types": "./src/web/group-honor.ts", - "default": "./src/web/group-honor.ts" - }, - "./web/group-notice": { - "types": "./src/web/group-notice.ts", - "default": "./src/web/group-notice.ts" - }, - "./web/group-signin": { - "types": "./src/web/group-signin.ts", - "default": "./src/web/group-signin.ts" - }, - "./web/qzone": { - "types": "./src/web/qzone.ts", - "default": "./src/web/qzone.ts" - }, - "./web/request-util": { - "types": "./src/web/request-util.ts", - "default": "./src/web/request-util.ts" + "./web/*": { + "types": "./src/web/*.ts", + "default": "./src/web/*.ts" } }, "scripts": { From 85ca20727993949a61625d557c9c7a9667d96b8d Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 18:37:42 +0800 Subject: [PATCH 19/30] refactor(onebot): extract openSqliteDb helper for the three stores MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit message/media/reaction store 构造器各自逐字复制同一段引导(mkdir 父目录 + 打开 DatabaseSync + PRAGMA journal_mode=WAL + PRAGMA synchronous=NORMAL),改一处 PRAGMA 要改三处。抽 openSqliteDb(dbPath) 收敛,schema init 与路径改写留在各调用方。 - message-store 的 .json→.db 改写保留(改写后同目录,mkdir 目标不变,等价)。 - 三文件删掉不再使用的 fs/path import。 行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认 三处引导等价、路径细节无边角、无回归。 --- packages/onebot/src/media-store.ts | 10 ++-------- packages/onebot/src/message-store.ts | 10 ++-------- packages/onebot/src/reaction-store.ts | 9 ++------- packages/onebot/src/sqlite-open.ts | 21 +++++++++++++++++++++ 4 files changed, 27 insertions(+), 23 deletions(-) create mode 100644 packages/onebot/src/sqlite-open.ts diff --git a/packages/onebot/src/media-store.ts b/packages/onebot/src/media-store.ts index fa475747..79ccd5aa 100644 --- a/packages/onebot/src/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -1,7 +1,6 @@ import type { MessageElement } from '@snowluma/protocol/events'; -import fs from 'fs'; import { DatabaseSync, type StatementSync } from 'node:sqlite'; -import path from 'path'; +import { openSqliteDb } from './sqlite-open'; export interface CachedImage { file: string; @@ -77,12 +76,7 @@ export class MediaStore { constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) { this.maxEntriesPerType = Math.max(64, maxEntriesPerType); - const dir = path.dirname(dbPath); - fs.mkdirSync(dir, { recursive: true }); - - this.db = new DatabaseSync(dbPath); - this.db.exec('PRAGMA journal_mode = WAL'); - this.db.exec('PRAGMA synchronous = NORMAL'); + this.db = openSqliteDb(dbPath); this.initSchema(); this.upsertEntry = this.db.prepare( diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index 5b87f7f1..c79da5cc 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -1,7 +1,6 @@ -import fs from 'fs'; import { DatabaseSync, type StatementSync } from 'node:sqlite'; -import path from 'path'; import type { JsonObject, MessageMeta } from './types'; +import { openSqliteDb } from './sqlite-open'; export class MessageStore { private readonly db: DatabaseSync; @@ -15,14 +14,9 @@ export class MessageStore { private readonly stmtListEventsLatest: StatementSync; constructor(dbPath: string) { - const dir = path.dirname(dbPath); - fs.mkdirSync(dir, { recursive: true }); - // Replace .json extension with .db if present const finalPath = dbPath.replace(/\.json$/, '.db'); - this.db = new DatabaseSync(finalPath); - this.db.exec('PRAGMA journal_mode = WAL'); - this.db.exec('PRAGMA synchronous = NORMAL'); + this.db = openSqliteDb(finalPath); this.initSchema(); // Prepare once. Statements survive for the lifetime of the diff --git a/packages/onebot/src/reaction-store.ts b/packages/onebot/src/reaction-store.ts index 388b6715..e46e9011 100644 --- a/packages/onebot/src/reaction-store.ts +++ b/packages/onebot/src/reaction-store.ts @@ -1,6 +1,5 @@ -import fs from 'fs'; import { DatabaseSync, type StatementSync } from 'node:sqlite'; -import path from 'path'; +import { openSqliteDb } from './sqlite-open'; export class ReactionStore { private readonly db: DatabaseSync; @@ -11,11 +10,7 @@ export class ReactionStore { private readonly stmtCountByEmoji: StatementSync; constructor(dbPath: string) { - const dir = path.dirname(dbPath); - fs.mkdirSync(dir, { recursive: true }); - this.db = new DatabaseSync(dbPath); - this.db.exec('PRAGMA journal_mode = WAL'); - this.db.exec('PRAGMA synchronous = NORMAL'); + this.db = openSqliteDb(dbPath); this.initSchema(); this.stmtUpsert = this.db.prepare( diff --git a/packages/onebot/src/sqlite-open.ts b/packages/onebot/src/sqlite-open.ts new file mode 100644 index 00000000..8019c9a8 --- /dev/null +++ b/packages/onebot/src/sqlite-open.ts @@ -0,0 +1,21 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { DatabaseSync } from 'node:sqlite'; + +/** + * Open a SQLite database with the store-wide defaults: ensure the parent + * directory exists, then open with WAL journaling + NORMAL synchronous — the + * durability/throughput balance the message / media / reaction stores all + * want. The caller owns schema init and any path munging. + * + * Concentrates the bootstrap each store previously hand-copied verbatim, so a + * PRAGMA / journal-mode / busy-timeout change lands in one place instead of + * three. + */ +export function openSqliteDb(dbPath: string): DatabaseSync { + fs.mkdirSync(path.dirname(dbPath), { recursive: true }); + const db = new DatabaseSync(dbPath); + db.exec('PRAGMA journal_mode = WAL'); + db.exec('PRAGMA synchronous = NORMAL'); + return db; +} From c1d27c5055e9c5cdd95ec38723f3588cb3e21270 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 18:43:20 +0800 Subject: [PATCH 20/30] refactor(protocol): converge packet-pipeline dispatch tail into finishDispatch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit process() 的 sync 分支、dispatchAfterIdentityRefresh、dispatchGroupInvite 三处逐字 重复同一段收尾(handleSideEffects → printEvent → emit);再加一种需 pre-dispatch 富化的入站事件就得原样抄这三行,漏一行会静默丢日志或丢事件发射。抽 finishDispatch 收敛为一处。 - finishDispatch(event, alreadyRefreshed=false):默认 false 使 sync/group-invite 两路的 finishDispatch(event) 等价于原 handleSideEffects(event);identity-refresh 路透传 refreshed。与 CONTEXT 里已做的 reconcilePipeUp/Down 收敛同构。 行为严格不变:protocol 561 + core 467 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认三处等价、透传正确、三条路径均有测试覆盖。 --- packages/protocol/src/packet-pipeline.ts | 25 +++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/packages/protocol/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts index 5b4f66ab..db452a86 100644 --- a/packages/protocol/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -104,9 +104,7 @@ export class IncomingPacketPipeline { err instanceof Error ? (err.stack ?? err.message) : String(err)); }); } else { - this.handleSideEffects(event); - printEvent(this.eventLog, this.deps.identity, event); - this.emit(event); + this.finishDispatch(event); } } } catch (e) { @@ -121,6 +119,19 @@ export class IncomingPacketPipeline { void this.deps.events.emit(event); } + /** + * Common dispatch tail shared by the sync path and the two async enrichment + * paths: run side effects, log the event, then emit it. `alreadyRefreshed` is + * threaded through to `handleSideEffects` (true only on the identity-refresh + * path, where the roster refresh was already done) — it defaults false, so + * `finishDispatch(event)` matches the old `handleSideEffects(event)` calls. + */ + private finishDispatch(event: QQEventVariant, alreadyRefreshed = false): void { + this.handleSideEffects(event, alreadyRefreshed); + printEvent(this.eventLog, this.deps.identity, event); + this.emit(event); + } + private needsPreDispatchIdentityRefresh(event: QQEventVariant): event is Extract { return event.kind === 'group_member_join' && event.groupId > 0 && event.userUin <= 0 && Boolean(event.userUid); } @@ -155,9 +166,7 @@ export class IncomingPacketPipeline { event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e)); } - this.handleSideEffects(event, refreshed); - printEvent(this.eventLog, this.deps.identity, event); - this.emit(event); + this.finishDispatch(event, refreshed); } private async dispatchGroupInvite(event: Extract): Promise { @@ -218,9 +227,7 @@ export class IncomingPacketPipeline { } } - this.handleSideEffects(event); - printEvent(this.eventLog, this.deps.identity, event); - this.emit(event); + this.finishDispatch(event); } private async prepareGroupMemberJoinIdentity(event: Extract): Promise { From 29a792cfdfcc38a069c1708f05feaf56024b60c1 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 18:53:34 +0800 Subject: [PATCH 21/30] refactor(core): extract sseResponse helper for the three WebUI SSE endpoints MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit /api/debug/stream、/api/state/stream、/api/logs/stream 各自逐字复制同一套 ~40 行 SSE 生命周期骨架(TextEncoder + closed 守卫 + 15s heartbeat + teardown + safe enqueue + abort listener + event-stream headers);改一处 heartbeat 间隔/teardown 顺序/headers 要同步改三处,漏一处会 listener 泄漏。 - 新增 webui/sse-response.ts:sseResponse(c, start) 封装传输壳,给 start 回调一个 channel { raw, encode, send, onClose, isClosed, desiredSize }。各端点特有的订阅/ 背压 framePusher/初始快照留在回调里。 - 三端点收敛:debug/state 用 createFramePusher(背压丢帧) + onClose 注册订阅;logs 直接 ch.send;state 的 503 守卫留在 helper 外。 - 新增 sse-response.test.ts(4 例)为这三个原本无生命周期测试的端点建立安全网。 行为严格不变:core 471 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认 helper 骨架与三端点等价、无时序/守卫回归。 --- packages/core/src/webui/server.ts | 176 ++++++----------------- packages/core/src/webui/sse-response.ts | 69 +++++++++ packages/core/tests/sse-response.test.ts | 62 ++++++++ 3 files changed, 177 insertions(+), 130 deletions(-) create mode 100644 packages/core/src/webui/sse-response.ts create mode 100644 packages/core/tests/sse-response.test.ts diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 13784925..7c8be618 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -23,6 +23,7 @@ import { buildBackup, planRestore, validateBackup } from './backup'; import { collectActionDocs, collectCategories } from '@snowluma/onebot/action-docs'; import { createFramePusher } from './debug-stream'; import { buildStreamInvokeResponse, streamUploadToDisk } from './debug-tools'; +import { sseResponse } from './sse-response'; import { bindStateStream } from './state-stream'; import type { StateBus, StateResource } from './state-bus'; import { startConnectionDiffLoop } from './connection-diff-loop'; @@ -969,45 +970,21 @@ export async function initWebUI( // 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); - }, + app.get('/api/debug/stream', (c) => sseResponse(c, (ch) => { + // Drop-under-backpressure framing (unit-tested in debug-stream.ts). + const pushFrame = createFramePusher({ + desiredSize: ch.desiredSize, + enqueue: ch.raw, + encode: ch.encode, }); - return new Response(stream, { - headers: { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' }, - }); - }); + const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); }; + send({ kind: 'ready' }); + for (const inst of oneBotManager.getInstances()) { + const uin = inst.uin; + ch.onClose(inst.subscribeDebugEvents((event) => send({ kind: 'event', uin, event }))); + ch.onClose(inst.observeActions((rec) => send({ kind: 'action', uin, ...rec }))); + } + })); app.get('/api/qq-list', (c) => { const instances = oneBotManager.getInstances(); @@ -1039,56 +1016,34 @@ export async function initWebUI( return c.text('state stream not configured', 503); } const liveBus = stateBus; - const stream = new ReadableStream({ - start(controller) { - const encoder = new TextEncoder(); - let closed = false; - let binding: { dispose(): void } | undefined; - let heartbeat: NodeJS.Timeout | undefined; - const teardown = () => { - if (closed) return; - closed = true; - if (heartbeat) clearInterval(heartbeat); - binding?.dispose(); - try { controller.close(); } catch { /* ignore */ } - }; - const raw = (chunk: Uint8Array) => { - if (closed) return; - try { controller.enqueue(chunk); } catch { teardown(); } - }; - const pushFrame = createFramePusher({ - desiredSize: () => controller.desiredSize, - enqueue: raw, - encode: (s) => encoder.encode(s), - }); - const send = (payload: unknown) => { if (!closed) pushFrame(payload); }; - send({ kind: 'ready' }); + return sseResponse(c, (ch) => { + const pushFrame = createFramePusher({ + desiredSize: ch.desiredSize, + enqueue: ch.raw, + encode: ch.encode, + }); + const send = (payload: unknown) => { if (!ch.isClosed()) pushFrame(payload); }; + send({ kind: 'ready' }); - const handle = bindStateStream({ - bus: liveBus, - snapshot: async (resource: StateResource): Promise => { - if (resource === 'processes') { - if (!hookManager) return []; - return hookManager.listProcesses(); - } - if (resource === 'qq-list') { - return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); - } - return oneBotManager.getConnectionStatuses(); - }, - send: (frame) => send(frame), - debounceMs: 50, - }); - binding = handle; - // Prime with the initial snapshot; if the client never sees the - // bus publish (idle system) it still has the current state. - void handle.sendAllInitial(); - 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' }, + const handle = bindStateStream({ + bus: liveBus, + snapshot: async (resource: StateResource): Promise => { + if (resource === 'processes') { + if (!hookManager) return []; + return hookManager.listProcesses(); + } + if (resource === 'qq-list') { + return oneBotManager.getInstances().map((inst) => ({ uin: inst.uin, nickname: inst.nickname })); + } + return oneBotManager.getConnectionStatuses(); + }, + send: (frame) => send(frame), + debounceMs: 50, + }); + ch.onClose(() => handle.dispose()); + // Prime with the initial snapshot; if the client never sees the + // bus publish (idle system) it still has the current state. + void handle.sendAllInitial(); }); }); @@ -1111,49 +1066,10 @@ export async function initWebUI( return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); }); - app.get('/api/logs/stream', (c) => { - const stream = new ReadableStream({ - start(controller) { - const encoder = new TextEncoder(); - let closed = false; - let unsubscribe: (() => void) | undefined; - let heartbeat: NodeJS.Timeout | undefined; - const teardown = () => { - if (closed) return; - closed = true; - if (heartbeat) clearInterval(heartbeat); - unsubscribe?.(); - try { controller.close(); } catch { /* ignore */ } - }; - const safeEnqueue = (chunk: Uint8Array) => { - if (closed) return; - try { - controller.enqueue(chunk); - } catch { - // The peer dropped between abort and the next enqueue — - // treat as end-of-stream so we don't leak listeners. - teardown(); - } - }; - const send = (event: unknown) => { - safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); - }; - send({ type: 'ready' }); - unsubscribe = subscribeLogs((entry) => send(entry)); - heartbeat = setInterval(() => { - safeEnqueue(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/logs/stream', (c) => sseResponse(c, (ch) => { + ch.send({ type: 'ready' }); + ch.onClose(subscribeLogs((entry) => ch.send(entry))); + })); app.get('/api/processes', async (c) => { if (!hookManager) return c.json({ list: [] }); diff --git a/packages/core/src/webui/sse-response.ts b/packages/core/src/webui/sse-response.ts new file mode 100644 index 00000000..6f517a8f --- /dev/null +++ b/packages/core/src/webui/sse-response.ts @@ -0,0 +1,69 @@ +import { type Context } from 'hono'; + +/** + * The per-connection channel handed to an SSE endpoint's `start` callback. + * Everything the endpoint needs to talk to the client, without owning the + * transport lifecycle (heartbeat / teardown / abort / headers). + */ +export interface SseChannel { + /** Enqueue a raw chunk. Tears the stream down if the peer is already gone. */ + raw(chunk: Uint8Array): void; + /** Encode a string to bytes (shared TextEncoder). */ + encode(s: string): Uint8Array; + /** Convenience: enqueue one `data: \n\n` frame. */ + send(payload: unknown): void; + /** Register a cleanup to run once on teardown (unsubscribe / dispose). */ + onClose(fn: () => void): void; + /** True after teardown — guard sends from late subscription callbacks. */ + isClosed(): boolean; + /** Underlying controller backpressure signal, for `createFramePusher`. */ + desiredSize(): number | null; +} + +/** + * The SSE HTTP transport shell shared by the WebUI's live endpoints. Owns the + * TextEncoder, a `closed` guard, a 15s `: heartbeat` keep-alive, teardown + * (clear heartbeat → run registered cleanups → close the controller), safe + * enqueue (a throw means the peer dropped → teardown), the abort listener, and + * the `text/event-stream` headers. `start` wires up the endpoint-specific + * subscription + initial sends via the channel. + * + * Each of `/api/debug/stream`, `/api/state/stream`, `/api/logs/stream` + * previously hand-copied this ~40-line skeleton; a heartbeat-interval / + * teardown-order / header change had to be kept in sync across all three. + */ +export function sseResponse(c: Context, start: (ch: SseChannel) => void): Response { + const stream = new ReadableStream({ + start(controller) { + const encoder = new TextEncoder(); + let closed = false; + let heartbeat: ReturnType | undefined; + const cleanups: Array<() => void> = []; + const teardown = () => { + if (closed) return; + closed = true; + if (heartbeat) clearInterval(heartbeat); + for (const fn of cleanups) { try { fn(); } catch { /* ignore */ } } + try { controller.close(); } catch { /* ignore */ } + }; + const raw = (chunk: Uint8Array) => { + if (closed) return; + try { controller.enqueue(chunk); } catch { teardown(); } + }; + const ch: SseChannel = { + raw, + encode: (s) => encoder.encode(s), + send: (payload) => raw(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`)), + onClose: (fn) => { cleanups.push(fn); }, + isClosed: () => closed, + desiredSize: () => controller.desiredSize, + }; + start(ch); + 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' }, + }); +} diff --git a/packages/core/tests/sse-response.test.ts b/packages/core/tests/sse-response.test.ts new file mode 100644 index 00000000..b59b271a --- /dev/null +++ b/packages/core/tests/sse-response.test.ts @@ -0,0 +1,62 @@ +import { describe, it, expect, vi } from 'vitest'; +import { sseResponse } from '../src/webui/sse-response'; + +// A minimal hono-Context stand-in: sseResponse only reads c.req.raw.signal. +function fakeCtx(signal: AbortSignal): Parameters[0] { + return { req: { raw: { signal } } } as unknown as Parameters[0]; +} + +describe('sseResponse', () => { + it('returns an event-stream Response with the SSE headers', () => { + const ac = new AbortController(); + const res = sseResponse(fakeCtx(ac.signal), () => { /* no-op */ }); + expect(res.headers.get('Content-Type')).toBe('text/event-stream'); + expect(res.headers.get('Cache-Control')).toBe('no-cache'); + expect(res.headers.get('Connection')).toBe('keep-alive'); + ac.abort(); // clear the heartbeat timer + }); + + it('ch.send frames JSON as `data: …` and ch.raw enqueues verbatim', async () => { + const ac = new AbortController(); + const res = sseResponse(fakeCtx(ac.signal), (ch) => { + ch.send({ type: 'ready' }); + ch.raw(ch.encode(': heartbeat\n\n')); + }); + const reader = res.body!.getReader(); + const dec = new TextDecoder(); + expect(dec.decode((await reader.read()).value)).toBe('data: {"type":"ready"}\n\n'); + expect(dec.decode((await reader.read()).value)).toBe(': heartbeat\n\n'); + ac.abort(); + await reader.cancel(); + }); + + it('abort runs registered cleanups exactly once, flips isClosed, and closes the stream', async () => { + const ac = new AbortController(); + const cleanupA = vi.fn(); + const cleanupB = vi.fn(); + let channel!: Parameters[1]>[0]; + const res = sseResponse(fakeCtx(ac.signal), (ch) => { + channel = ch; + ch.onClose(cleanupA); + ch.onClose(cleanupB); + }); + expect(channel.isClosed()).toBe(false); + + ac.abort(); + expect(cleanupA).toHaveBeenCalledTimes(1); + expect(cleanupB).toHaveBeenCalledTimes(1); + expect(channel.isClosed()).toBe(true); + + const r = await res.body!.getReader().read(); + expect(r.done).toBe(true); + }); + + it('send after teardown is a silent no-op', () => { + const ac = new AbortController(); + let channel!: Parameters[1]>[0]; + sseResponse(fakeCtx(ac.signal), (ch) => { channel = ch; }); + ac.abort(); + expect(() => channel.send({ x: 1 })).not.toThrow(); + expect(channel.isClosed()).toBe(true); + }); +}); From 298d174640c7e644ee50d1d17557acb188ae4d90 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 18:58:22 +0800 Subject: [PATCH 22/30] refactor(webui): extract openSseChannel for the three EventSource openers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit stateStream / openLogStream / openDebugStream 三个 EventSource opener 近乎逐字重复 (token 守卫 → EventSource → onopen/onerror → onmessage try-parse-catch → close disposer),token/reconnect/畸形帧-跳过 语义各写一遍、易漂。 - 新增私有 openSseChannel(path, onMessage, onStatus?) 收敛骨架;各 opener 塌成 一行调用,consumer 逻辑作为 onMessage 传入(保持「回调在 try 内、抛错当畸形帧 吞掉」语义)。logs 的控制帧过滤(`'type' in parsed`)留在其 onMessage 回调里。 - StreamStatus 提到顶部 import,删掉 openDebugStream 的 inline import。 行为严格不变、对外签名不变:webui typecheck(tsc -b) + vite build 干净;对抗性 Agent 逐字对比 HEAD 确认三 opener 等价、onMessage-在-try-内 语义保留、无漏并入。 --- packages/webui/src/lib/api/client.ts | 76 +++++++++++----------------- 1 file changed, 30 insertions(+), 46 deletions(-) diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index b334c157..1219a085 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -12,6 +12,7 @@ import { type ProcessActionResult, type StateStreamEvent, type StateStreamOptions, + type StreamStatus, type TokenStore, } from './types'; import { localStorageTokenStore } from './token-store'; @@ -363,49 +364,40 @@ class HttpApiClient implements ApiClient { } stateStream(options: StateStreamOptions): () => void { - if (!this.currentToken) { options.onStatus?.('closed'); return () => {}; } - const url = `/api/state/stream?token=${encodeURIComponent(this.currentToken)}`; - const source = new EventSource(url); - // EventSource auto-reconnects on transport drop: `onerror` fires once - // when the connection is lost and the browser is about to retry, so - // a single 'reconnecting' status is sufficient — no manual reconnect - // timer needed. - source.onopen = () => options.onStatus?.('open'); - source.onerror = () => options.onStatus?.('reconnecting'); - source.onmessage = (event) => { - try { - options.onEvent(JSON.parse(event.data) as StateStreamEvent); - } catch { - /* malformed frame — skip; the next one will arrive normally */ - } - }; - return () => { source.close(); options.onStatus?.('closed'); }; + return this.openSseChannel('/api/state/stream', options.onEvent, options.onStatus); } // ---------- SSE ---------- - private openLogStream(options: LogsStreamOptions): () => void { - if (!this.currentToken) { - options.onStatus?.('closed'); - return () => {}; - } - const url = `/api/logs/stream?token=${encodeURIComponent(this.currentToken)}`; + /** + * Open a token-authed SSE channel to `path`, dispatching each parsed frame to + * `onMessage` and surfacing transport state ('open' / 'reconnecting' / + * 'closed') via `onStatus`. EventSource auto-reconnects on drop — `onerror` + * fires once per loss, so a single 'reconnecting' is enough. A malformed + * frame (or a throw from `onMessage`) is swallowed; the next frame arrives + * normally. The returned disposer closes the source and reports 'closed'. + */ + private openSseChannel( + path: string, + onMessage: (data: T) => void, + onStatus?: (s: StreamStatus) => void, + ): () => void { + if (!this.currentToken) { onStatus?.('closed'); return () => {}; } + const url = `${path}?token=${encodeURIComponent(this.currentToken)}`; const source = new EventSource(url); - source.onopen = () => options.onStatus?.('open'); - source.onerror = () => options.onStatus?.('reconnecting'); + source.onopen = () => onStatus?.('open'); + source.onerror = () => onStatus?.('reconnecting'); source.onmessage = (event) => { - try { - const parsed = JSON.parse(event.data) as LogEntry | { type: string }; - if ('type' in parsed) return; // control frame, not a log line - options.onLine(parsed); - } catch { - /* malformed frame, skip */ - } - }; - return () => { - source.close(); - options.onStatus?.('closed'); + try { onMessage(JSON.parse(event.data) as T); } catch { /* malformed frame — skip */ } }; + return () => { source.close(); onStatus?.('closed'); }; + } + + private openLogStream(options: LogsStreamOptions): () => void { + return this.openSseChannel('/api/logs/stream', (parsed) => { + if ('type' in parsed) return; // control frame, not a log line + options.onLine(parsed); + }, options.onStatus); } // Invoke a (stream) action and relay each `data: \n\n` SSE frame. Uses @@ -492,17 +484,9 @@ class HttpApiClient implements ApiClient { private openDebugStream( onMessage: (m: DebugStreamMessage) => void, - onStatus?: (s: import('./types').StreamStatus) => void, + onStatus?: (s: 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'); }; + return this.openSseChannel('/api/debug/stream', onMessage, onStatus); } } From 3db89d0bd08205845f12ab6f23b7872cac43a723 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 19:12:05 +0800 Subject: [PATCH 23/30] refactor(protocol,core): converge self-uid resolution to one impl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 「取自己 uid」原本散成 5 份、3 种错误文案:core/apis/shared.ts::resolveSelfUid、 group-file/message 各内联手抄一份、get-like 跨包再抄一份。收敛成 protocol 单一 resolveSelfUid(ctx: Pick)。 阶段 1(行为不变): - 新增 protocol/self-uid.ts(依赖方向 core→protocol 要求权威实现下沉 protocol; Bridge 与 OIDB service Deps 都满足 Pick 切片)。 - core/apis/shared.ts 改为 re-export 它(现有 resolveSelfUid(bridge) 调用点不变)。 - get-like/group-file/message 三处内联手抄 → 全调权威实现。 - 唯一副作用:message 的错误文案统一为 'self uid is unavailable'(无测试依赖旧文案)。 flash-transfer/forward 的 ?? '' 空串 bug 留待阶段 2;group-admin 合成本地事件保持不动。 全仓 12 包 typecheck Done、protocol/core(471)/onebot(516) 全绿;对抗性 Agent 确认 toInt/Number 边界无实际差异(identity.uin 恒为正整数串)、5 处等价。 --- packages/core/src/bridge/apis/group-file.ts | 9 +----- packages/core/src/bridge/apis/message.ts | 8 ++--- packages/core/src/bridge/apis/shared.ts | 22 +++----------- packages/protocol/package.json | 4 +++ .../src/oidb-services/profile/get-like.ts | 15 ++-------- packages/protocol/src/self-uid.ts | 29 +++++++++++++++++++ 6 files changed, 42 insertions(+), 45 deletions(-) create mode 100644 packages/protocol/src/self-uid.ts diff --git a/packages/core/src/bridge/apis/group-file.ts b/packages/core/src/bridge/apis/group-file.ts index afd1b8fc..bf0923c0 100644 --- a/packages/core/src/bridge/apis/group-file.ts +++ b/packages/core/src/bridge/apis/group-file.ts @@ -366,14 +366,7 @@ export class GroupFileApi { if (!loaded.bytes.length) throw new Error('private file is empty'); const targetUid = await this.ctx.resolveUserUid(userId); - let selfUid = this.ctx.identity.selfUid; - if (!selfUid) { - const selfUin = toInt(this.ctx.identity.uin); - if (selfUin > 0) { - selfUid = await this.ctx.resolveUserUid(selfUin); - } - } - if (!selfUid) throw new Error('self uid is unavailable'); + const selfUid = await resolveSelfUid(this.ctx); const senderUin = toInt(this.ctx.identity.uin); if (senderUin <= 0) throw new Error('invalid self uin for private file upload'); diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index f727090f..3f5cd8b3 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -15,6 +15,7 @@ import { fetchC2cMessageRange, fetchGroupMessageRange } from '@snowluma/protocol import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { createLogger } from '@snowluma/common/logger'; import type { BridgeContext } from '../bridge-context'; +import { resolveSelfUid } from './shared'; // `Bridge` is imported as a type only so we can narrow `ctx` back to // the concrete Bridge instance when passing it to `buildSendElems` // (which still takes `Bridge` because the highway upload helpers it @@ -259,12 +260,7 @@ export class MessageApi { // Resolve our own uid — needed both for the 0xE37_800 finalize and the // `field6` download-routing the receiver reads. - let selfUid = this.ctx.identity.selfUid; - if (!selfUid) { - const selfUin = Number.parseInt(this.ctx.identity.uin ?? '', 10); - if (Number.isFinite(selfUin) && selfUin > 0) selfUid = await this.ctx.resolveUserUid(selfUin); - } - if (!selfUid) throw new Error('self uid unavailable for c2c file send'); + const selfUid = await resolveSelfUid(this.ctx); // The file is already downloadable from the `NotOnlineFile` reference // alone — verified on a live account: a plain c2c file send (no field6) diff --git a/packages/core/src/bridge/apis/shared.ts b/packages/core/src/bridge/apis/shared.ts index 09ff7b8d..71d531a5 100644 --- a/packages/core/src/bridge/apis/shared.ts +++ b/packages/core/src/bridge/apis/shared.ts @@ -1,5 +1,3 @@ -import type { Bridge } from '../bridge'; - export function toInt(value: unknown): number { if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value); if (typeof value === 'bigint') { @@ -26,22 +24,10 @@ export function ensureRetCodeZero(operation: string, code: unknown, msg: unknown throw new Error(`${operation} failed: code=${retCode} msg=${text}`); } -/** - * Look up the bot's own UID. Cached on Identity once warmup populates - * `selfProfile`; forward/profile actions need this fast path before - * warmup completes. - */ -export async function resolveSelfUid(bridge: Bridge): Promise { - let selfUid = bridge.identity.selfUid; - if (selfUid) return selfUid; - - const selfUin = toInt(bridge.identity.uin); - if (selfUin <= 0) { - throw new Error('self uid is unavailable'); - } - selfUid = await bridge.resolveUserUid(selfUin); - return selfUid; -} +// The bot's-own-UID resolver is the single source of truth in @snowluma/protocol +// (a Bridge satisfies its BridgeContext slice). Re-exported here so the existing +// `resolveSelfUid(bridge)` call sites in this package keep importing from shared. +export { resolveSelfUid } from '@snowluma/protocol/self-uid'; /** * Index describing a server-side rich-media object (image / video / diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 04ae27fa..dc636410 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -36,6 +36,10 @@ "types": "./src/element-manifest.ts", "default": "./src/element-manifest.ts" }, + "./self-uid": { + "types": "./src/self-uid.ts", + "default": "./src/self-uid.ts" + }, "./bridge-oidb": { "types": "./src/bridge-oidb.ts", "default": "./src/bridge-oidb.ts" diff --git a/packages/protocol/src/oidb-services/profile/get-like.ts b/packages/protocol/src/oidb-services/profile/get-like.ts index ffa94118..9f273753 100644 --- a/packages/protocol/src/oidb-services/profile/get-like.ts +++ b/packages/protocol/src/oidb-services/profile/get-like.ts @@ -8,6 +8,7 @@ import type { Oidb0x7edReq, Oidb0x7edResp } from '@snowluma/proto-defs/oidb-acti import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { BridgeContext } from '../../bridge-context'; import { invokeOidb, type OidbSender } from '../../oidb-service'; +import { resolveSelfUid } from '../../self-uid'; export interface LikeInfo { [key: string]: import('@snowluma/common/json').JsonValue; @@ -46,7 +47,7 @@ export namespace GetLike { export const serialize = async (ctx: Deps, p: Params): Promise => { const targetUid = p.userId ? await ctx.resolveUserUid(p.userId) - : await resolveSelf(ctx); + : await resolveSelfUid(ctx); if (!targetUid) throw new Error('target uid not found'); return { targetUid, @@ -89,15 +90,3 @@ export namespace GetLike { export const invoke = (deps: Deps, params: Params): Promise => invokeOidb(deps, GetLike, params); } - -async function resolveSelf(deps: Pick): Promise { - // Mirrors `apis/shared.ts::resolveSelfUid` — kept inline here so the - // namespace is self-contained against just the BridgeContext slice. - const cached = deps.identity.selfUid; - if (cached) return cached; - const selfUin = Number(deps.identity.uin); - if (!Number.isFinite(selfUin) || selfUin <= 0) { - throw new Error('self uid is unavailable'); - } - return deps.resolveUserUid(selfUin); -} diff --git a/packages/protocol/src/self-uid.ts b/packages/protocol/src/self-uid.ts new file mode 100644 index 00000000..19896cf6 --- /dev/null +++ b/packages/protocol/src/self-uid.ts @@ -0,0 +1,29 @@ +import type { BridgeContext } from './bridge-context'; + +/** + * Resolve the bot's own UID — the single source of truth for "what is my uid". + * + * Fast path: once warmup populates `selfProfile`, `identity.selfUid` is set and + * returns immediately. Before that, resolve via `resolveUserUid(selfUin)`. + * Throws when there is no self identity at all (uin missing / <= 0). + * + * Callers that put the uid on an outbound packet must route here rather than + * fall back to an empty string: an empty uid ships a broken packet. This used + * to be re-inlined in ContactsApi shared helpers, group-file, message, and + * get-like — the copies had drifted into three error messages and two silent + * `?? ''` empty-uid bugs before being converged here. + * + * Takes just the `BridgeContext` slice it needs, so both a full `Bridge` and a + * bare context (e.g. an OIDB service's Deps) satisfy it. + */ +export async function resolveSelfUid( + ctx: Pick, +): Promise { + const cached = ctx.identity.selfUid; + if (cached) return cached; + const selfUin = Number(ctx.identity.uin); + if (!Number.isFinite(selfUin) || selfUin <= 0) { + throw new Error('self uid is unavailable'); + } + return ctx.resolveUserUid(selfUin); +} From f111ba7129bde2fd592f9c8b76568278398f9387 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 19:18:10 +0800 Subject: [PATCH 24/30] fix(core): resolve self uid instead of shipping an empty one (forward/flash) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 阶段 2:修 self-uid 收口暴露的 2 处静默空串 bug。warmup 未完成时 identity.selfUid 为 null,原 `?? ''` 会把空 uid 放进出网包: - forward.ts:154 responseHead.toUid(转发广播消息坏包) - flash-transfer.ts:279 fileset uploader.uid(空 uid 会被服务端 drop fileset) 均改为 `await resolveSelfUid(...)`:正常路径(selfUid 有值,几乎总是)命中缓存、取值 完全不变;仅在身份未就绪的极端情况从「静默发坏包」变成「明确报错」(fail-loud)。 两处外层函数本就 async。group-admin.ts:64 的 ?? '' 是合成本地事件、best-effort、 非出网,保留不动。 core 471 全绿、typecheck 干净;对抗性 Agent 确认正常路径不变、无测试回归。 --- packages/core/src/bridge/apis/flash-transfer.ts | 5 ++++- packages/core/src/bridge/apis/forward.ts | 4 +++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/packages/core/src/bridge/apis/flash-transfer.ts b/packages/core/src/bridge/apis/flash-transfer.ts index d9dab528..489a70ea 100644 --- a/packages/core/src/bridge/apis/flash-transfer.ts +++ b/packages/core/src/bridge/apis/flash-transfer.ts @@ -2,6 +2,7 @@ // 复用 OIDB 基础设施(invokeOidb),协议层在 @snowluma/protocol/oidb-services/flash-transfer/。 import type { BridgeContext } from '../bridge-context'; +import { resolveSelfUid } from './shared'; import type { FlashFileEntry } from '@snowluma/proto-defs/oidb-actions/flash-transfer'; import { GetFilesetDetail } from '@snowluma/protocol/oidb-services/flash-transfer/get-fileset-detail'; import { ListFilesets } from '@snowluma/protocol/oidb-services/flash-transfer/list-filesets'; @@ -276,7 +277,9 @@ export class FlashTransferApi { const uploader = { uin: this.ctx.identity.uin, nickname: this.ctx.identity.nickname, - uid: this.ctx.identity.selfUid ?? '', + // Resolve our own uid rather than ship an empty one — a blank uploader + // uid drops the fileset if this runs before warmup populated selfUid. + uid: await resolveSelfUid(this.ctx), }; // 读取所有文件,每个分配 fileUuid + 序号 + formatCode const items: { bytes: Uint8Array; fileName: string; fileUuid: string; fileIndex: number; formatCode: number }[] = []; diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index 991f9de0..d04505d8 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -151,7 +151,9 @@ async function buildForwardPushBody( return { responseHead: { fromUin, - toUid: bridge.identity.selfUid ?? '', + // Resolve our own uid rather than ship an empty one — a blank toUid is a + // broken packet if this runs before warmup populated selfUid. + toUid: await resolveSelfUid(bridge), forward: { friendName: nickname, }, From a8f24b8f13bdba0bb84322deaa43da91c50d908e Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 19:55:21 +0800 Subject: [PATCH 25/30] refactor(onebot): converge self-sent message tail into finalizeSend MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit send/forward 路径里「记录自发消息」的尾巴(hashMessageIdInt32 + cacheMessageMeta + cacheSelfSentMessage)逐字复制 6 份(sendPrivate/sendGroup/两个 forward/forwardSingle 的 group+private 分支),每处独立手工配对 isGroup ↔ eventName ↔ hash 事件常量—— 漏改一处会静默产生错 message_id / 错 event 归属。抽 finalizeSend(ref, isGroup, targetId, receipt, elements),由 isGroup 单点派生 eventName + 常量。 6 处塌成 6 行调用;forwardSingle 的 group/private if/else 只剩 send API 本身不同。 receipt 用结构类型覆盖所有调用点(含 line 630 合成的 fallback)。 行为严格不变:onebot 516 全绿、typecheck 干净;对抗性 Agent 逐字对比 HEAD 确认 6 处等价、参数/返回正确。 --- .../onebot/src/modules/message-actions.ts | 153 +++++------------- 1 file changed, 43 insertions(+), 110 deletions(-) diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 1fa44697..dad6b127 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -417,6 +417,43 @@ export async function setEssenceMessage( * inspect it through `/get_msg` can distinguish their own outbound * messages from incoming ones. */ +/** + * The shared "record a self-sent message" tail: derive the OneBot message id + * from (sequence, target, event), then cache both the meta and the self-sent + * copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event + * constant` coupling that was hand-paired in six send/forward paths — a + * mismatch there silently produced a wrong message_id or wrong event + * attribution. Returns the derived message id. + */ +async function finalizeSend( + ref: OneBotInstanceContext, + isGroup: boolean, + targetId: number, + receipt: { sequence: number; clientSequence: number; random: number; timestamp: number }, + elements: MessageElement[], +): Promise { + const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; + const messageId = hashMessageIdInt32(receipt.sequence, targetId, eventName); + ref.cacheMessageMeta(messageId, { + isGroup, + targetId, + sequence: receipt.sequence, + eventName, + clientSequence: receipt.clientSequence, + random: receipt.random, + timestamp: receipt.timestamp, + }); + await cacheSelfSentMessage(ref, { + isGroup, + sessionId: targetId, + messageId, + sequence: receipt.sequence, + timestamp: receipt.timestamp, + elements, + }); + return messageId; +} + async function cacheSelfSentMessage( ref: OneBotInstanceContext, options: { @@ -644,24 +681,7 @@ export async function sendPrivateMessage( } if (!lastReceipt) throw new Error('message is empty'); - const messageId = hashMessageIdInt32(lastReceipt.sequence, userId, PRIVATE_MESSAGE_EVENT); - ref.cacheMessageMeta(messageId, { - isGroup: false, - targetId: userId, - sequence: lastReceipt.sequence, - eventName: PRIVATE_MESSAGE_EVENT, - clientSequence: lastReceipt.clientSequence, - random: lastReceipt.random, - timestamp: lastReceipt.timestamp, - }); - await cacheSelfSentMessage(ref, { - isGroup: false, - sessionId: userId, - messageId, - sequence: lastReceipt.sequence, - timestamp: lastReceipt.timestamp, - elements, - }); + const messageId = await finalizeSend(ref, false, userId, lastReceipt, elements); return { messageId }; } @@ -758,24 +778,7 @@ export async function sendGroupMessage( } if (!lastReceipt) throw new Error('message is empty'); - const messageId = hashMessageIdInt32(lastReceipt.sequence, groupId, GROUP_MESSAGE_EVENT); - ref.cacheMessageMeta(messageId, { - isGroup: true, - targetId: groupId, - sequence: lastReceipt.sequence, - eventName: GROUP_MESSAGE_EVENT, - clientSequence: lastReceipt.clientSequence, - random: lastReceipt.random, - timestamp: lastReceipt.timestamp, - }); - await cacheSelfSentMessage(ref, { - isGroup: true, - sessionId: groupId, - messageId, - sequence: lastReceipt.sequence, - timestamp: lastReceipt.timestamp, - elements, - }); + const messageId = await finalizeSend(ref, true, groupId, lastReceipt, elements); return { messageId }; } @@ -801,25 +804,7 @@ export async function sendGroupForwardMessage( const forwardId = await ref.bridge.apis.forward.upload(nodes, groupId); const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta); const receipt = await ref.bridge.apis.message.sendGroup(groupId, [previewElement]); - const messageId = hashMessageIdInt32(receipt.sequence, groupId, GROUP_MESSAGE_EVENT); - - ref.cacheMessageMeta(messageId, { - isGroup: true, - targetId: groupId, - sequence: receipt.sequence, - eventName: GROUP_MESSAGE_EVENT, - clientSequence: receipt.clientSequence, - random: receipt.random, - timestamp: receipt.timestamp, - }); - await cacheSelfSentMessage(ref, { - isGroup: true, - sessionId: groupId, - messageId, - sequence: receipt.sequence, - timestamp: receipt.timestamp, - elements: [previewElement], - }); + const messageId = await finalizeSend(ref, true, groupId, receipt, [previewElement]); return { messageId, forwardId }; } @@ -837,25 +822,7 @@ export async function sendPrivateForwardMessage( const forwardId = await ref.bridge.apis.forward.upload(nodes, undefined, userId); const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta); const receipt = await ref.bridge.apis.message.sendPrivate(userId, [previewElement]); - const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT); - - ref.cacheMessageMeta(messageId, { - isGroup: false, - targetId: userId, - sequence: receipt.sequence, - eventName: PRIVATE_MESSAGE_EVENT, - clientSequence: receipt.clientSequence, - random: receipt.random, - timestamp: receipt.timestamp, - }); - await cacheSelfSentMessage(ref, { - isGroup: false, - sessionId: userId, - messageId, - sequence: receipt.sequence, - timestamp: receipt.timestamp, - elements: [previewElement], - }); + const messageId = await finalizeSend(ref, false, userId, receipt, [previewElement]); return { messageId, forwardId }; } @@ -904,44 +871,10 @@ export async function forwardSingleMessage( let messageIdOut: number; if (target.groupId) { receipt = await ref.bridge.apis.message.sendGroup(target.groupId, elements); - messageIdOut = hashMessageIdInt32(receipt.sequence, target.groupId, GROUP_MESSAGE_EVENT); - ref.cacheMessageMeta(messageIdOut, { - isGroup: true, - targetId: target.groupId, - sequence: receipt.sequence, - eventName: GROUP_MESSAGE_EVENT, - clientSequence: receipt.clientSequence, - random: receipt.random, - timestamp: receipt.timestamp, - }); - await cacheSelfSentMessage(ref, { - isGroup: true, - sessionId: target.groupId, - messageId: messageIdOut, - sequence: receipt.sequence, - timestamp: receipt.timestamp, - elements, - }); + messageIdOut = await finalizeSend(ref, true, target.groupId, receipt, elements); } else { receipt = await ref.bridge.apis.message.sendPrivate(target.userId!, elements); - messageIdOut = hashMessageIdInt32(receipt.sequence, target.userId!, PRIVATE_MESSAGE_EVENT); - ref.cacheMessageMeta(messageIdOut, { - isGroup: false, - targetId: target.userId!, - sequence: receipt.sequence, - eventName: PRIVATE_MESSAGE_EVENT, - clientSequence: receipt.clientSequence, - random: receipt.random, - timestamp: receipt.timestamp, - }); - await cacheSelfSentMessage(ref, { - isGroup: false, - sessionId: target.userId!, - messageId: messageIdOut, - sequence: receipt.sequence, - timestamp: receipt.timestamp, - elements, - }); + messageIdOut = await finalizeSend(ref, false, target.userId!, receipt, elements); } return { messageId: messageIdOut }; From c822c5dab627f06dbf975666a5fb6eb8435e693f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 20:03:58 +0800 Subject: [PATCH 26/30] refactor(webui): extract useFlashMessage hook for settings panels MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 三个 settings 面板各手写同一套 flash-message 状态机(msg state + setTimeout 自动 消失 + 卸载清 timer)。global-config / notifications 是完整版(逐字相同); system-panel 是退化版(无 timer ref、无 cleanup、rapid flash 累积 timer、卸载后可能 stale setMsg)。抽 useFlashMessage(durationMs=2400) → { msg, flash, setMsg }。 - global-config / notifications:迁移后行为不变(2400ms;flash 瞬时 + setMsg 持久 错误保留)。 - system-panel:保留 4000ms(useFlashMessage(4000)),顺带补上 prior-timer 取消 + 卸载 cleanup(修 timer 泄漏,现代 React 里无害的小改善)。 webui typecheck(tsc -b) + vite build 干净;对抗性 Agent 逐行核对确认 hook 等价、 两面板行为不变、无依赖/import 回归。 --- .../settings/global-config-panel.tsx | 11 +----- .../settings/notifications-panel.tsx | 11 +----- .../src/components/settings/system-panel.tsx | 7 +--- packages/webui/src/hooks/use-flash-message.ts | 37 +++++++++++++++++++ 4 files changed, 43 insertions(+), 23 deletions(-) create mode 100644 packages/webui/src/hooks/use-flash-message.ts diff --git a/packages/webui/src/components/settings/global-config-panel.tsx b/packages/webui/src/components/settings/global-config-panel.tsx index 19ba66f0..eef75ae3 100644 --- a/packages/webui/src/components/settings/global-config-panel.tsx +++ b/packages/webui/src/components/settings/global-config-panel.tsx @@ -11,6 +11,7 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { useApi } from '@/lib/api'; +import { useFlashMessage } from '@/hooks/use-flash-message'; import { cn } from '@/lib/utils'; import type { GlobalSettings } from '@/types'; @@ -30,9 +31,8 @@ export function GlobalConfigPanel() { const [config, setConfig] = useState(null); const [loading, setLoading] = useState(true); const [loadFailed, setLoadFailed] = useState(false); - const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null); + const { msg, flash } = useFlashMessage(); const saveTimer = useRef(null); - const msgTimer = useRef(null); const saveGen = useRef(0); const load = useCallback(async () => { @@ -54,17 +54,10 @@ export function GlobalConfigPanel() { useEffect( () => () => { if (saveTimer.current) clearTimeout(saveTimer.current); - if (msgTimer.current) clearTimeout(msgTimer.current); }, [], ); - const flash = (kind: 'ok' | 'err', text: string) => { - setMsg({ kind, text }); - if (msgTimer.current) clearTimeout(msgTimer.current); - msgTimer.current = window.setTimeout(() => setMsg(null), 2400); - }; - /** Apply locally + debounced auto-save. Deliberately does NOT reconcile the * inputs from the server's normalized response (it would wipe a half-typed * URL); a generation guard just confirms the latest save. */ diff --git a/packages/webui/src/components/settings/notifications-panel.tsx b/packages/webui/src/components/settings/notifications-panel.tsx index 67b0dff3..8ac4e42c 100644 --- a/packages/webui/src/components/settings/notifications-panel.tsx +++ b/packages/webui/src/components/settings/notifications-panel.tsx @@ -11,6 +11,7 @@ import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; import { ToggleSwitch } from '@/components/ui/toggle-switch'; import { useApi } from '@/lib/api'; +import { useFlashMessage } from '@/hooks/use-flash-message'; import { useTheme } from '@/contexts/ThemeContext'; import { cn } from '@/lib/utils'; import type { NotificationChannel, NotificationsConfig } from '@/types'; @@ -41,9 +42,8 @@ export function NotificationsPanel() { const [loading, setLoading] = useState(true); const [dialog, setDialog] = useState({ open: false, index: null, seed: blankChannel([]) }); const [testing, setTesting] = useState(null); - const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null); + const { msg, flash, setMsg } = useFlashMessage(); const saveTimer = useRef(null); - const msgTimer = useRef(null); const saveGen = useRef(0); useEffect(() => { @@ -66,17 +66,10 @@ export function NotificationsPanel() { useEffect( () => () => { if (saveTimer.current) clearTimeout(saveTimer.current); - if (msgTimer.current) clearTimeout(msgTimer.current); }, [], ); - const flash = (kind: 'ok' | 'err', text: string) => { - setMsg({ kind, text }); - if (msgTimer.current) clearTimeout(msgTimer.current); - msgTimer.current = window.setTimeout(() => setMsg(null), 2400); - }; - /** Apply locally + debounced auto-save. A generation guard reconciles with * the server's normalized result only if no newer edit landed meanwhile. */ const commit = (next: NotificationsConfig) => { diff --git a/packages/webui/src/components/settings/system-panel.tsx b/packages/webui/src/components/settings/system-panel.tsx index df264164..87366ea3 100644 --- a/packages/webui/src/components/settings/system-panel.tsx +++ b/packages/webui/src/components/settings/system-panel.tsx @@ -16,6 +16,7 @@ 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 { useFlashMessage } from '@/hooks/use-flash-message'; import { cn } from '@/lib/utils'; import type { SystemSettingsResponse } from '@/types'; @@ -24,7 +25,7 @@ export function SystemPanel() { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [saving, setSaving] = useState(false); - const [msg, setMsg] = useState<{ kind: 'ok' | 'err'; text: string } | null>(null); + const { msg, flash, setMsg } = useFlashMessage(4000); // editable form state const [port, setPort] = useState(''); @@ -60,10 +61,6 @@ export function SystemPanel() { 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); diff --git a/packages/webui/src/hooks/use-flash-message.ts b/packages/webui/src/hooks/use-flash-message.ts new file mode 100644 index 00000000..48699c1f --- /dev/null +++ b/packages/webui/src/hooks/use-flash-message.ts @@ -0,0 +1,37 @@ +import { useEffect, useRef, useState } from 'react'; + +export type FlashKind = 'ok' | 'err'; +export interface FlashMessage { + kind: FlashKind; + text: string; +} + +/** + * Transient status-banner state for a settings panel. + * + * - `flash(kind, text)` shows a message that auto-clears after `durationMs`, + * cancelling any prior auto-clear timer first. + * - `setMsg` sets/clears the message directly (a persistent one that stays + * until the next action — e.g. a load-failure banner). + * - The pending timer is cleared on unmount. + * + * Replaces the per-panel hand-rolled `msg` state + `msgTimer` ref + `flash` + + * unmount cleanup, which had drifted (one panel omitted the ref, the + * prior-timer cancel, and the unmount cleanup entirely — leaking a timer that + * could fire a stale `setMsg` after unmount). + */ +export function useFlashMessage(durationMs = 2400): { + msg: FlashMessage | null; + flash: (kind: FlashKind, text: string) => void; + setMsg: (msg: FlashMessage | null) => void; +} { + const [msg, setMsg] = useState(null); + const timer = useRef(null); + useEffect(() => () => { if (timer.current) clearTimeout(timer.current); }, []); + const flash = (kind: FlashKind, text: string) => { + setMsg({ kind, text }); + if (timer.current) clearTimeout(timer.current); + timer.current = window.setTimeout(() => setMsg(null), durationMs); + }; + return { msg, flash, setMsg }; +} From ade76d3d2f75af2a4ee5bc78bd69431d69292ec4 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 20:14:55 +0800 Subject: [PATCH 27/30] refactor(protocol): reuse tested Sha1Stream in video block-sha1 (drop dup) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit video-upload.ts 有一份 ~110 行手写、**无测试**的流式 SHA1(Sha1StreamState),与 sha1-stream.ts 里已充分测试的 Sha1Stream 逐字节相同(transform 数学等价、中间 state 小端)。删掉该重复,computeVideoSha1Blocks 改用 Sha1Stream 做 1MB 块的中间 state、 Node crypto 做整文件 final(与受测的 computeSha1StateV 同一套路;已实测旧 final() === Node crypto 整文件 sha1)。 - 新增 video-sha1-blocks.test.ts(4 例):golden 值从**旧实现**抓取,锁定重写 byte- identical(两个 1MB 中间 state + overall),并给这个原本无测试的函数永久覆盖。 - 删掉的 tail-update 只影响旧自实现 final,不动任何中间块(tail<64B 不触发 1MB 边界)。 protocol 565 全绿、typecheck 干净;对抗性 Agent 独立复现旧实现确认 golden 逐字节 相同、transform 数学等价无精度问题、无残留引用。 --- packages/protocol/src/highway/video-upload.ts | 147 ++---------------- .../tests/highway/video-sha1-blocks.test.ts | 46 ++++++ 2 files changed, 62 insertions(+), 131 deletions(-) create mode 100644 packages/protocol/tests/highway/video-sha1-blocks.test.ts diff --git a/packages/protocol/src/highway/video-upload.ts b/packages/protocol/src/highway/video-upload.ts index a4904e28..0a285152 100644 --- a/packages/protocol/src/highway/video-upload.ts +++ b/packages/protocol/src/highway/video-upload.ts @@ -18,6 +18,7 @@ import { loadBinarySource, resolveLocalFilePath, } from './utils'; +import { Sha1Stream } from './sha1-stream'; const moduleLog = createLogger('Highway.Video'); @@ -35,6 +36,7 @@ export const GROUP_VIDEO_THUMB_CMD_ID = 1006; export const MAX_VIDEO_SIZE = 100 * 1024 * 1024; const MAX_VIDEO_SIZE_HARD = 1536 * 1024 * 1024; const SHA1_STREAM_BLOCK_SIZE = 1024 * 1024; +const SHA1_BLOCK_SIZE = 64; export function getVideoSourceSize(element: MessageElement): number | null { if (element.fileSize && element.fileSize > 0) return element.fileSize; @@ -123,143 +125,26 @@ interface ThumbPayload { // ─────────────── 1MB-block sha1 (Highway main-video extend) ─────────────── -// Highway expects sha1 computed over each 1 MB block of the file, plus -// the final overall sha1. This is a streaming implementation that doesn't -// reuse Node's crypto because Node only exposes the final digest. - -class Sha1StreamState { - readonly blockSize = 64; - private readonly padding = Buffer.concat([Buffer.from([0x80]), Buffer.alloc(63)]); - private readonly state = new Uint32Array(5); - private readonly count = new Uint32Array(2); - private readonly buffer = Buffer.allocUnsafe(this.blockSize); - private readonly w = new Uint32Array(80); - - constructor() { - this.reset(); - } - - private reset(): void { - this.state[0] = 0x67452301; - this.state[1] = 0xEFCDAB89; - this.state[2] = 0x98BADCFE; - this.state[3] = 0x10325476; - this.state[4] = 0xC3D2E1F0; - this.count[0] = 0; - this.count[1] = 0; - this.buffer.fill(0); - } - - private rotateLeft(value: number, offset: number): number { - return ((value << offset) | (value >>> (32 - offset))) >>> 0; - } - - private transform(chunk: Uint8Array, offset: number): void { - const view = new DataView(chunk.buffer, chunk.byteOffset + offset, this.blockSize); - - for (let i = 0; i < 16; i++) { - this.w[i] = view.getUint32(i * 4, false); - } - for (let i = 16; i < 80; i++) { - this.w[i] = this.rotateLeft(this.w[i - 3] ^ this.w[i - 8] ^ this.w[i - 14] ^ this.w[i - 16], 1); - } - - let a = this.state[0]; - let b = this.state[1]; - let c = this.state[2]; - let d = this.state[3]; - let e = this.state[4]; - - for (let i = 0; i < 80; i++) { - let temp: number; - if (i < 20) { - temp = ((b & c) | (~b & d)) + 0x5A827999; - } else if (i < 40) { - temp = (b ^ c ^ d) + 0x6ED9EBA1; - } else if (i < 60) { - temp = ((b & c) | (b & d) | (c & d)) + 0x8F1BBCDC; - } else { - temp = (b ^ c ^ d) + 0xCA62C1D6; - } - temp += (this.rotateLeft(a, 5) + e + this.w[i]) >>> 0; - e = d; - d = c; - c = this.rotateLeft(b, 30); - b = a; - a = temp >>> 0; - } - - this.state[0] = (this.state[0] + a) >>> 0; - this.state[1] = (this.state[1] + b) >>> 0; - this.state[2] = (this.state[2] + c) >>> 0; - this.state[3] = (this.state[3] + d) >>> 0; - this.state[4] = (this.state[4] + e) >>> 0; - } - - update(data: Uint8Array): void { - let index = (this.count[0] >>> 3) & 0x3F; - const dataLen = data.length; - this.count[0] = (this.count[0] + (dataLen << 3)) >>> 0; - if (this.count[0] < (dataLen << 3)) this.count[1] = (this.count[1] + 1) >>> 0; - this.count[1] = (this.count[1] + (dataLen >>> 29)) >>> 0; - - const partLen = this.blockSize - index; - let i = 0; - - if (dataLen >= partLen) { - this.buffer.set(data.subarray(0, partLen), index); - this.transform(this.buffer, 0); - for (i = partLen; i + this.blockSize <= dataLen; i += this.blockSize) { - this.transform(data, i); - } - index = 0; - } - - if (i < dataLen) { - this.buffer.set(data.subarray(i, dataLen), index); - } - } - - hash(bigEndian = true): Uint8Array { - const digest = Buffer.allocUnsafe(20); - for (let i = 0; i < 5; i++) { - if (bigEndian) digest.writeUInt32BE(this.state[i], i * 4); - else digest.writeUInt32LE(this.state[i], i * 4); - } - return new Uint8Array(digest); - } - - final(): Uint8Array { - const bits = Buffer.allocUnsafe(8); - bits.writeUInt32BE(this.count[1], 0); - bits.writeUInt32BE(this.count[0], 4); - - const index = (this.count[0] >>> 3) & 0x3F; - const padLen = index < 56 ? 56 - index : 120 - index; - this.update(this.padding.subarray(0, padLen)); - this.update(bits); - return this.hash(true); - } -} - -function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] { - const sha1 = new Sha1StreamState(); +// Highway expects the sha1 of each 1 MB block (intermediate un-finalized state, +// little-endian) plus the overall sha1. Reuses the well-tested streaming +// Sha1Stream for the block states and Node crypto for the overall digest (same +// split as computeSha1StateV), replacing a ~110-line hand-rolled, untested +// SHA1 duplicate. +export function computeVideoSha1Blocks(bytes: Uint8Array): Uint8Array[] { + const sha1 = new Sha1Stream(); const blocks: Uint8Array[] = []; let bytesRead = 0; let offset = 0; - - while (offset + sha1.blockSize <= bytes.length) { - const block = bytes.subarray(offset, offset + sha1.blockSize); - sha1.update(block); - offset += sha1.blockSize; - bytesRead += sha1.blockSize; + while (offset + SHA1_BLOCK_SIZE <= bytes.length) { + sha1.update(bytes.subarray(offset, offset + SHA1_BLOCK_SIZE)); + offset += SHA1_BLOCK_SIZE; + bytesRead += SHA1_BLOCK_SIZE; if (bytesRead % SHA1_STREAM_BLOCK_SIZE === 0) { - blocks.push(sha1.hash(false)); + blocks.push(sha1.hash(true)); // little-endian intermediate state } } - - if (offset < bytes.length) sha1.update(bytes.subarray(offset)); - blocks.push(sha1.final()); + // Overall SHA1 (finalized) via Node crypto — the reference impl. + blocks.push(new Uint8Array(crypto.createHash('sha1').update(Buffer.from(bytes)).digest())); return blocks; } diff --git a/packages/protocol/tests/highway/video-sha1-blocks.test.ts b/packages/protocol/tests/highway/video-sha1-blocks.test.ts new file mode 100644 index 00000000..50283a4d --- /dev/null +++ b/packages/protocol/tests/highway/video-sha1-blocks.test.ts @@ -0,0 +1,46 @@ +import { describe, it, expect } from 'vitest'; +import { createHash } from 'node:crypto'; +import { computeVideoSha1Blocks } from '../../src/highway/video-upload'; + +// Deterministic input generator (matches the golden-capture script). +function det(len: number): Uint8Array { + const b = new Uint8Array(len); + for (let i = 0; i < len; i++) b[i] = (i * 31 + 7) & 0xFF; + return b; +} +const hex = (u: Uint8Array): string => Buffer.from(u).toString('hex'); +const nodeSha1 = (b: Uint8Array): string => createHash('sha1').update(Buffer.from(b)).digest('hex'); + +describe('computeVideoSha1Blocks', () => { + // GOLDEN: captured from the previous hand-rolled Sha1StreamState implementation + // before the F3 rewrite (Sha1Stream + Node crypto), so this locks the rewrite + // byte-identical for the block states AND the overall digest. + it('reproduces the pre-refactor golden 1MB-block states + overall sha1', () => { + const input = det(2 * 1024 * 1024 + 12345); // 2 full 1MB blocks + a partial tail + expect(computeVideoSha1Blocks(input).map(hex)).toEqual([ + 'ab9a20fd6c98fc1f8f0c985cd552ff14c6feacfd', // intermediate un-finalized state @1MB (little-endian) + '2ccc5923b75f46ebd8ccb78e8c413c18025178b9', // intermediate un-finalized state @2MB + 'dd9cfd4648ab460260afa820c98bfec1b17655d4', // overall (finalized) + ]); + }); + + it('the final block equals the standard full-file SHA1', () => { + const input = det(2 * 1024 * 1024 + 12345); + const blocks = computeVideoSha1Blocks(input); + expect(hex(blocks[blocks.length - 1]!)).toBe(nodeSha1(input)); + }); + + it('a file shorter than 1MB yields just the overall sha1', () => { + const input = det(1000); + const blocks = computeVideoSha1Blocks(input); + expect(blocks).toHaveLength(1); + expect(hex(blocks[0]!)).toBe(nodeSha1(input)); + }); + + it('a file that is an exact 1MB multiple emits the boundary state then the overall', () => { + const input = det(1024 * 1024); + const blocks = computeVideoSha1Blocks(input); + expect(blocks).toHaveLength(2); + expect(hex(blocks[1]!)).toBe(nodeSha1(input)); // last is the finalized overall + }); +}); From 3932958c3950c90d4e20f5dfc1e12b5f966117eb Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 20:37:02 +0800 Subject: [PATCH 28/30] fix(bridge,common,onebot): reject phantom hook UINs + never crash logging (#162) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 注入的竞态窗口里,native hook 偶发上报 13 位垃圾 UIN(时间戳型,读到 QQ 尚未落定 的内存)。TS 层防御缺失,导致两个连锁问题: 1) 幽灵账号:isRealUin 只查「纯数字且 ≥5 位」、无上限,垃圾值通过后建会话并把 config/onebot_<垃圾>.json 落盘 → OneBot 节点配置里出现随机幽灵账号(跨重启残留)。 2) 进程崩溃:logger 彩色路径 ' '.repeat(SLOT - tagLen),UIN tag(含方括号)超宽 → 负数 → RangeError: Invalid count value → uncaughtException。 跨平台(Win DLL / Linux .so 同逻辑)+「更新 QQ 后消失」都印证是 native 读到那块内存 的偶发垃圾;根修在 SnowLumaNative,此处补齐 TS 防御: - 抽出唯一的 @snowluma/common/uin::isRealUin = /^\d{5,10}$/(真实 QQ ≤ uint32 → 10 位)。删除 bridge/core 两处重复副本(重复正是这次漏加上限的温床)。等价旧逻辑, 仅新增拒 11+ 位。 - logger.ts 加 Math.max(0, …),日志永不崩进程(独立健壮化)。 - 收紧 WebUI UIN_REGEX /^\d{5,12}$/ → /^\d{5,10}$/ 保持一致。 - 启动时 cleanupInvalidPerUinConfigs() 清掉已落盘的幽灵 onebot_.json(只删 UIN 不合法的,绝不碰合法账号/全局配置)。 测试:common +8(uin 6 / logger 2)、onebot +3(cleanup)。typecheck 12 包干净; common 58 / onebot 519 / core 471 / bridge 73 全绿。对抗性 Agent 逐输入核验等价性、 三层 gate 堵死幽灵入口、cleanup 安全时序,无回归。 --- packages/bridge/src/hook-session.ts | 6 +- packages/common/package.json | 4 ++ packages/common/src/logger.ts | 2 +- packages/common/src/uin.ts | 11 ++++ packages/common/tests/logger.test.ts | 45 +++++++++++++++ packages/common/tests/uin.test.ts | 40 +++++++++++++ packages/core/src/bridge/manager.ts | 10 +--- packages/core/src/index.ts | 5 ++ packages/core/src/webui/server.ts | 9 ++- packages/onebot/src/config.ts | 33 +++++++++++ packages/onebot/tests/config-cleanup.test.ts | 60 ++++++++++++++++++++ 11 files changed, 209 insertions(+), 16 deletions(-) create mode 100644 packages/common/src/uin.ts create mode 100644 packages/common/tests/logger.test.ts create mode 100644 packages/common/tests/uin.test.ts create mode 100644 packages/onebot/tests/config-cleanup.test.ts diff --git a/packages/bridge/src/hook-session.ts b/packages/bridge/src/hook-session.ts index 6f18baae..5300d4c6 100644 --- a/packages/bridge/src/hook-session.ts +++ b/packages/bridge/src/hook-session.ts @@ -1,5 +1,6 @@ import { createLogger, type Logger } from '@snowluma/common/logger'; import type { PacketSink } from '@snowluma/common/protocol-types'; +import { isRealUin } from '@snowluma/common/uin'; import { EventEmitter } from 'events'; import { HookPacketClient } from './hook-packet-client'; import type { HookInjectResult } from './injector'; @@ -518,11 +519,6 @@ export class HookSession extends EventEmitter { } } -function isRealUin(uin: string): boolean { - if (!uin || uin === '0') return false; - return /^\d+$/.test(uin) && uin.length >= 5; -} - function errMsg(value: unknown): string { return value instanceof Error ? value.message : String(value); } diff --git a/packages/common/package.json b/packages/common/package.json index 7183555a..0fd848dc 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -55,6 +55,10 @@ "./runtime": { "types": "./src/runtime.ts", "default": "./src/runtime.ts" + }, + "./uin": { + "types": "./src/uin.ts", + "default": "./src/uin.ts" } }, "scripts": { diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index fb29dca4..6ff80ff1 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -175,7 +175,7 @@ function render(level: LogLevel, options: LogOptions, args: unknown[], reqId?: n // Pad first, then color only the visible tag so escape codes don't eat // into the alignment width. const cUin = uinTag - ? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length) + ? ansi(COLOR_DIM, uinTag) + ' '.repeat(Math.max(0, UIN_SLOT_WIDTH - uinTag.length)) : ' '.repeat(UIN_SLOT_WIDTH); const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`); const cReq = reqTag ? `${ansi(COLOR_DIM, reqTag)} ` : ''; diff --git a/packages/common/src/uin.ts b/packages/common/src/uin.ts new file mode 100644 index 00000000..62b8f77f --- /dev/null +++ b/packages/common/src/uin.ts @@ -0,0 +1,11 @@ +// Shared QQ UIN validity check. A "real" UIN is a live QQ account number, not +// a garbage value the native hook can emit during the probe→inject race — e.g. +// a 13-digit millisecond timestamp read from not-yet-populated QQ memory +// (issue #162). No real QQ UIN exceeds 10 digits (they fit in uint32, max +// 4294967295), so a pure digit string of 5..10 chars is the accept window. +// +// Callers rely on a `true` result guaranteeing a BigInt()-safe pure-digit +// string. Keep that contract if the pattern ever changes. +export function isRealUin(uin: string): boolean { + return /^\d{5,10}$/.test(uin); +} diff --git a/packages/common/tests/logger.test.ts b/packages/common/tests/logger.test.ts new file mode 100644 index 00000000..66020f11 --- /dev/null +++ b/packages/common/tests/logger.test.ts @@ -0,0 +1,45 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +// The file transport writes to disk; stub it so the test has no side effects. +vi.mock('../src/log-file-transport', () => ({ + getFileTransport: () => ({ write: () => {} }), +})); + +import { createLogger } from '../src/logger'; + +// Regression for issue #162: a hook-reported garbage UIN (13-digit, timestamp +// shaped) produced a `[…]` tag wider than the fixed UIN slot, and the colored +// render path did `' '.repeat(slot - tagLen)` → RangeError: Invalid count value +// → uncaughtException. The padding must clamp at zero. +describe('logger UIN slot padding', () => { + let prevTTY: boolean | undefined; + let prevNoColor: string | undefined; + + beforeEach(() => { + prevTTY = process.stdout.isTTY; + prevNoColor = process.env.NO_COLOR; + // Force the colored render path (the only one that used .repeat()). + (process.stdout as unknown as { isTTY: boolean }).isTTY = true; + delete process.env.NO_COLOR; + vi.spyOn(process.stdout, 'write').mockReturnValue(true); + vi.spyOn(process.stderr, 'write').mockReturnValue(true); + }); + + afterEach(() => { + (process.stdout as unknown as { isTTY: boolean | undefined }).isTTY = prevTTY; + if (prevNoColor === undefined) delete process.env.NO_COLOR; + else process.env.NO_COLOR = prevNoColor; + vi.restoreAllMocks(); + }); + + it('does not throw when the UIN tag exceeds the slot width', () => { + const log = createLogger('Test').child({ uin: '1701414379536' }); // 13-digit → [..] = 15 chars + expect(() => log.info('phantom account line')).not.toThrow(); + expect(() => log.error('phantom error line')).not.toThrow(); + }); + + it('still renders a normal-width UIN and a no-UIN logger', () => { + expect(() => createLogger('Test').child({ uin: '10001' }).info('ok')).not.toThrow(); + expect(() => createLogger('Test').info('no uin')).not.toThrow(); + }); +}); diff --git a/packages/common/tests/uin.test.ts b/packages/common/tests/uin.test.ts new file mode 100644 index 00000000..7e203076 --- /dev/null +++ b/packages/common/tests/uin.test.ts @@ -0,0 +1,40 @@ +import { describe, expect, it } from 'vitest'; +import { isRealUin } from '../src/uin'; + +describe('isRealUin', () => { + it('accepts real QQ UINs (5..10 digits)', () => { + expect(isRealUin('10001')).toBe(true); // 5-digit floor + expect(isRealUin('123456789')).toBe(true); + expect(isRealUin('4294967295')).toBe(true); // uint32 max, 10 digits + }); + + it('rejects the empty string and "0"', () => { + expect(isRealUin('')).toBe(false); + expect(isRealUin('0')).toBe(false); + }); + + it('rejects too-short UINs (< 5 digits)', () => { + expect(isRealUin('1')).toBe(false); + expect(isRealUin('1234')).toBe(false); + }); + + it('rejects the garbage timestamp-shaped UINs from issue #162 (11+ digits)', () => { + expect(isRealUin('1701414379536')).toBe(false); // 13-digit ms timestamp + expect(isRealUin('1614019567632')).toBe(false); + expect(isRealUin('2014024115056')).toBe(false); + expect(isRealUin('12345678901')).toBe(false); // 11 digits — first rejected width + }); + + it('rejects non-digit strings (path traversal / injection guards)', () => { + expect(isRealUin('12345a')).toBe(false); + expect(isRealUin('12 345')).toBe(false); + expect(isRealUin('../etc')).toBe(false); + expect(isRealUin('123456\n')).toBe(false); + }); + + it('guarantees a BigInt-safe pure-digit string on accept', () => { + const uin = '123456789'; + expect(isRealUin(uin)).toBe(true); + expect(() => BigInt(uin)).not.toThrow(); + }); +}); diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index 8fbc7f25..a635770d 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -1,6 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { PacketSender } from '@snowluma/common/packet-sender'; import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { isRealUin } from '@snowluma/common/uin'; import { IdentityService } from '@snowluma/protocol/identity-service'; import { Bridge } from './bridge'; @@ -72,13 +73,8 @@ export class BridgeManager { } } - private static isRealUin(uin: string): boolean { - if (!uin || uin === '0') return false; - return /^\d+$/.test(uin) && uin.length >= 5; - } - onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { - if (!BridgeManager.isRealUin(uin)) return; + if (!isRealUin(uin)) return; this.pidPacketClients_.set(pid, packetClient); @@ -94,7 +90,7 @@ export class BridgeManager { } onPacket(pkt: PacketInfo): void { - if (!pkt.uin || !BridgeManager.isRealUin(pkt.uin)) return; + if (!pkt.uin || !isRealUin(pkt.uin)) return; const uin = pkt.uin; // Ensure session exists diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c3879331..0bbc74b3 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -3,6 +3,7 @@ import { closeLogger, createLogger } from '@snowluma/common/logger'; import { loadRuntimeConfig } from '@snowluma/common/runtime'; import { OneBotManager } from '@snowluma/onebot/manager'; import { migrateGlobalSettings } from '@snowluma/onebot/global-config'; +import { cleanupInvalidPerUinConfigs } from '@snowluma/onebot/config'; import { BridgeManager } from './bridge/manager'; import { createNotificationManager } from './notifications/manager'; import { createStateWiring } from './webui/state-wiring'; @@ -33,6 +34,10 @@ async function main() { // any session (and thus any per-UIN config rewrite) can drop it. migrateGlobalSettings(); + // One-shot: purge any persisted phantom accounts (onebot_.json) the + // native hook may have created with a timestamp-shaped UIN (issue #162). + cleanupInvalidPerUinConfigs(); + const bridgeManager = new BridgeManager(); const oneBotManager = new OneBotManager(); const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 7c8be618..8280b6e5 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -101,9 +101,12 @@ export const SSE_TOKEN_QUERY_PATHS: ReadonlySet = new Set([ ]); const TOKEN_QUERY_ALLOWLIST = SSE_TOKEN_QUERY_PATHS; -// uin = QQ number; 5–12 digits. Used to construct config file paths, -// so we MUST refuse anything else (path traversal, NUL bytes, etc.). -const UIN_REGEX = /^\d{5,12}$/; +// uin = QQ number; 5–10 digits (real QQ UINs fit in uint32, max 4294967295). +// Used to construct config file paths, so we MUST refuse anything else (path +// traversal, NUL bytes, etc.) — and the 10-digit cap also rejects the garbage +// timestamp-shaped UINs the native hook can emit (issue #162). Mirrors +// isRealUin in @snowluma/common/uin. +const UIN_REGEX = /^\d{5,10}$/; const avatarCache = new Map(); diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index daf088b3..94833dd8 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -1,4 +1,5 @@ import { createLogger } from '@snowluma/common/logger'; +import { isRealUin } from '@snowluma/common/uin'; import { randomBytes } from 'crypto'; import fs from 'fs'; import path from 'path'; @@ -105,6 +106,38 @@ function ensureConfigDir(): void { fs.mkdirSync(CONFIG_DIR, { recursive: true }); } +const PER_UIN_CONFIG = /^onebot_(\d+)\.json$/; + +/** + * Remove per-UIN config files whose UIN is not a real QQ account — leftovers + * from the phantom-account bug where the native hook reported a garbage + * (timestamp-shaped) UIN and a `onebot_.json` got persisted (issue + * #162). Only files matching `onebot_.json` are considered, and only + * those failing isRealUin (i.e. 11+ digits) are deleted — legitimate accounts + * are never touched. Returns the deleted file names. Safe to call at startup. + */ +export function cleanupInvalidPerUinConfigs(): string[] { + let entries: string[]; + try { + entries = fs.readdirSync(CONFIG_DIR); + } catch { + return []; // config dir not created yet — nothing to clean + } + const removed: string[] = []; + for (const name of entries) { + const match = PER_UIN_CONFIG.exec(name); + if (!match || isRealUin(match[1])) continue; + try { + fs.unlinkSync(path.join(CONFIG_DIR, name)); + removed.push(name); + log.warn('removed phantom per-UIN config (invalid UIN): %s', name); + } catch (err) { + log.warn('failed to remove phantom config %s: %s', name, err instanceof Error ? err.message : String(err)); + } + } + return removed; +} + function toJsonObject(config: OneBotConfig): JsonObject { const nets = config.networks; return { diff --git a/packages/onebot/tests/config-cleanup.test.ts b/packages/onebot/tests/config-cleanup.test.ts new file mode 100644 index 00000000..2d4a2515 --- /dev/null +++ b/packages/onebot/tests/config-cleanup.test.ts @@ -0,0 +1,60 @@ +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import { cleanupInvalidPerUinConfigs } from '../src/config'; + +// Issue #162: phantom accounts (garbage timestamp-shaped UIN) got persisted as +// config/onebot_.json. Startup cleanup must delete exactly those and +// never touch legitimate per-UIN configs or the global onebot.json. +describe('cleanupInvalidPerUinConfigs', () => { + let tempDir: string; + let prevCwd: string; + + beforeEach(() => { + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-config-cleanup-')); + prevCwd = process.cwd(); + process.chdir(tempDir); + fs.mkdirSync('config', { recursive: true }); + }); + + afterEach(() => { + process.chdir(prevCwd); + fs.rmSync(tempDir, { recursive: true, force: true }); + }); + + const write = (name: string) => fs.writeFileSync(path.join('config', name), '{}'); + const exists = (name: string) => fs.existsSync(path.join('config', name)); + + it('deletes only per-UIN files whose UIN fails validation', () => { + write('onebot.json'); // global — must survive + write('onebot_123456789.json'); // legit 9-digit — must survive + write('onebot_4294967295.json'); // legit 10-digit — must survive + write('onebot_1701414379536.json'); // 13-digit phantom — must go + write('onebot_12345678901.json'); // 11-digit phantom — must go + write('snowluma.json'); // unrelated global — must survive + + const removed = cleanupInvalidPerUinConfigs().sort(); + + expect(removed).toEqual(['onebot_12345678901.json', 'onebot_1701414379536.json']); + expect(exists('onebot.json')).toBe(true); + expect(exists('onebot_123456789.json')).toBe(true); + expect(exists('onebot_4294967295.json')).toBe(true); + expect(exists('snowluma.json')).toBe(true); + expect(exists('onebot_1701414379536.json')).toBe(false); + expect(exists('onebot_12345678901.json')).toBe(false); + }); + + it('is a no-op when there are no phantom files', () => { + write('onebot.json'); + write('onebot_123456789.json'); + expect(cleanupInvalidPerUinConfigs()).toEqual([]); + expect(exists('onebot_123456789.json')).toBe(true); + }); + + it('does not throw when the config dir is absent', () => { + fs.rmSync('config', { recursive: true, force: true }); + expect(() => cleanupInvalidPerUinConfigs()).not.toThrow(); + expect(cleanupInvalidPerUinConfigs()).toEqual([]); + }); +}); From 63ab7a184627f90176cf8394dea26367ce2234a4 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 21:56:28 +0800 Subject: [PATCH 29/30] fix(protocol): parse Qzone feeds without eval + stop getCookies hanging (#182) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 真机抓包定位到 get_qzone_feeds 的两个问题: 1) feeds3_html_more 的响应体是**JS 对象字面量**(键无引号、单引号字符串、\xNN 转义、数组含 undefined),不是 JSON → JSON.parse 报 "Expected property name at position 66"(报告者看到的「响应结构问题」)。实测调参数(outputhtmlfeed/ format)改不掉这个格式,且 feeds 是纯远程 H5(native i64 里无相关 CGI),没有 干净 JSON 端点。改用**非执行的递归下降解析器** parseJsLiteral 把它当数据解析—— 绝不 eval 远程内容(vm 沙箱不是安全边界,被篡改的响应可逃逸到 RCE)。解析器只认 对象/数组/字符串/数字/true|false|null|undefined,丢弃 __proto__ 键防原型污染; mapFeeds 过滤数组尾部的 undefined 洞。 2) getCookies 卡死:HttpsGetCookies 无超时、无深度上限地递归跟随 302;当某跳目标 不可达(数据中心/Docker 上 qzone.qq.com 裸域超时)→ 永久挂死所有 cookie-backed web 动作。加 8s 超时 + 深度上限(5) + 失败/超时保留已收集 cookie(不再 reject)。 两处修复均在 tempserver 真机验证:getCookies 从卡死 3 分钟变正常返回;抓到的真实 feeds 响应体做成测试 fixture,非执行解析器正确解出 uin/nickname/html(\x3C→<)。 读接口加了 TRACE 原始体日志 + 结构失败错误带响应片段,方便后续排查。 (msglist 的 -10000「使用人数过多」判定为 taotao 服务端风控——同 cookie 下 feeds 能成功、msglist 单独挂,非代码 bug,代码已正确透传。) protocol 572 全绿、typecheck 干净;两轮对抗性 Agent:先揪出 vm 版可 RCE 逼我换非执行 解析器,再确认新解析器构造上不执行代码、无原型污染、真机数据解析正确。 --- packages/protocol/src/web/qzone.ts | 142 +++++++++++++++++- packages/protocol/src/web/request-util.ts | 55 +++---- .../web/fixtures/qzone-feeds-sample.jsonp | 8 + .../tests/web/qzone-feeds-parse.test.ts | 75 +++++++++ packages/protocol/tests/web/qzone.test.ts | 6 +- 5 files changed, 251 insertions(+), 35 deletions(-) create mode 100644 packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp create mode 100644 packages/protocol/tests/web/qzone-feeds-parse.test.ts diff --git a/packages/protocol/src/web/qzone.ts b/packages/protocol/src/web/qzone.ts index fca10501..222f55ce 100644 --- a/packages/protocol/src/web/qzone.ts +++ b/packages/protocol/src/web/qzone.ts @@ -80,6 +80,131 @@ export function parseQzoneJson(text: string): T { return JSON.parse(s.slice(start, end + 1)) as T; } +/** + * Parse the JavaScript OBJECT-LITERAL payload of a Qzone JSONP feeds response + * WITHOUT executing it. feeds3_html_more returns `_preloadCallback({ … })` where + * the `data` value uses unquoted keys, single-quoted strings, `\xNN` escapes and + * literal `undefined`s — it is meant to be eval'd by the browser callback, so + * JSON.parse chokes on it. We ran the alternatives to ground: no param combo + * (outputhtmlfeed/format) makes the CGI emit real JSON, and feeds are pure + * remote H5 (absent from the native client), so there is no cleaner endpoint. + * Rather than eval remote-controlled content (a `vm` sandbox is not a security + * boundary — a tampered body escapes it to RCE), we recursively DESCEND the + * literal as data: it can only ever produce a value, never run code. + * + * Handles the subset the CGI emits: objects (unquoted or quoted keys), arrays + * (incl. `undefined`/elided holes), single/double-quoted strings with JS escapes + * (`\xNN`, `\uNNNN`, `\/`, …), numbers and `true|false|null|undefined`. + * `__proto__` keys are dropped (no prototype pollution). + */ +function parseJsLiteral(src: string): unknown { + let i = 0; + const n = src.length; + const isWs = (c: string): boolean => c === ' ' || c === '\t' || c === '\n' || c === '\r' || c === '\f' || c === '\v'; + const skipWs = (): void => { while (i < n && isWs(src[i]!)) i++; }; + + function parseString(quote: string): string { + i++; // opening quote + let out = ''; + while (i < n) { + const c = src[i]!; + if (c === '\\') { + const e = src[i + 1]; + if (e === 'x') { out += String.fromCharCode(parseInt(src.slice(i + 2, i + 4), 16)); i += 4; continue; } + if (e === 'u') { out += String.fromCharCode(parseInt(src.slice(i + 2, i + 6), 16)); i += 6; continue; } + const simple: Record = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', '0': '\0' }; + out += e !== undefined ? (simple[e] ?? e) : ''; // \/ → /, \' → ', unknown → the char + i += 2; + continue; + } + if (c === quote) { i++; return out; } + out += c; + i++; + } + throw new Error('unterminated string in qzone feeds payload'); + } + + function parseKey(): string { + skipWs(); + const c = src[i]; + if (c === '"' || c === "'") return parseString(c); + let s = ''; + while (i < n && /[A-Za-z0-9_$]/.test(src[i]!)) { s += src[i]; i++; } + if (!s) throw new Error('expected object key in qzone feeds payload'); + return s; + } + + function parseObject(): Record { + i++; // { + const obj: Record = {}; + skipWs(); + if (src[i] === '}') { i++; return obj; } + for (;;) { + const key = parseKey(); + skipWs(); + if (src[i] !== ':') throw new Error('expected ":" in qzone feeds payload'); + i++; + const value = parseValue(); + if (key !== '__proto__') obj[key] = value; + skipWs(); + const ch = src[i]; + if (ch === ',') { i++; skipWs(); if (src[i] === '}') { i++; return obj; } continue; } + if (ch === '}') { i++; return obj; } + throw new Error('expected "," or "}" in qzone feeds payload'); + } + } + + function parseArray(): unknown[] { + i++; // [ + const arr: unknown[] = []; + skipWs(); + if (src[i] === ']') { i++; return arr; } + for (;;) { + arr.push(parseValue()); + skipWs(); + const ch = src[i]; + if (ch === ',') { i++; skipWs(); if (src[i] === ']') { i++; return arr; } continue; } + if (ch === ']') { i++; return arr; } + throw new Error('expected "," or "]" in qzone feeds payload'); + } + } + + function parseValue(): unknown { + skipWs(); + const c = src[i]; + if (c === undefined) throw new Error('unexpected end of qzone feeds payload'); + if (c === '{') return parseObject(); + if (c === '[') return parseArray(); + if (c === '"' || c === "'") return parseString(c); + let token = ''; + while (i < n && !/[,}\]:\s]/.test(src[i]!)) { token += src[i]; i++; } + if (token === 'true') return true; + if (token === 'false') return false; + if (token === 'null') return null; + if (token === 'undefined') return undefined; + if (token !== '') { const num = Number(token); if (!Number.isNaN(num)) return num; } + throw new Error('unexpected token in qzone feeds payload: ' + token.slice(0, 20)); + } + + return parseValue(); +} + +/** + * Extract the object a Qzone feeds JSONP body hands to its callback, parsed as + * data (never executed — see {@link parseJsLiteral}). Slices from the first `{` + * (the callback argument) and parses one balanced value; trailing `);` is + * ignored. Throws if the payload is not an object. + */ +export function parseQzoneCallback(text: string): T { + const start = text.indexOf('{'); + if (start === -1) throw new Error('invalid feeds response from qzone api'); + const value = parseJsLiteral(text.slice(start)); + if (value === null || typeof value !== 'object') { + throw new Error('invalid feeds response from qzone api'); + } + return value as T; +} + function assertRichParams(richType?: number, richval?: string): void { const hasRichType = richType !== undefined; const hasRichval = richval !== undefined && richval.trim() !== ''; @@ -194,6 +319,7 @@ export async function getQzoneMsgList( const text = await RequestUtil.HttpGetText(url, 'GET', '', { Cookie: cookieToString(cookieObject), }); + log.trace('getQzoneMsgList raw body (uin=%s): %s', targetUin, text); const data = parseQzoneJson(text); if (typeof data.code === 'number' && data.code !== 0) { @@ -201,8 +327,8 @@ export async function getQzoneMsgList( throw new Error(`qzone msglist failed: code=${data.code} ${data.message ?? ''}`.trim()); } if (!Array.isArray(data.msglist)) { - log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure', targetUin); - throw new Error('无法获取空间说说列表'); + log.warn('getQzoneMsgList: no msglist in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', targetUin, text.slice(0, 300)); + throw new Error(`无法获取空间说说列表(响应结构异常): ${text.slice(0, 200)}`); } return mapMsgList(data); @@ -262,7 +388,8 @@ export interface QzoneFeedsResult { /** Pure transform from the raw feeds response into the OneBot list. */ export function mapFeeds(data: RawFeedsResponse): QzoneFeedsResult { - const list = data.data?.data ?? []; + // The CGI pads the array with trailing `undefined`/null holes — drop them. + const list = (data.data?.data ?? []).filter((f): f is RawFeedItem => !!f); return { feeds: list.map((f) => ({ uin: Number(f.uin ?? 0), @@ -335,15 +462,18 @@ export async function getQzoneFeeds( const text = await RequestUtil.HttpGetText(url, 'GET', '', { Cookie: cookieToString(cookieObject), }); - const data = parseQzoneJson(text); + log.trace('getQzoneFeeds raw body (uin=%s): %s', selfUin, text); + // feeds3_html_more's payload is a JS object literal, not JSON — parse it as + // inert data (see parseQzoneCallback; never executed) rather than JSON.parse. + const data = parseQzoneCallback(text); if (typeof data.code === 'number' && data.code !== 0) { log.warn('getQzoneFeeds: non-zero code (uin=%s) code=%d msg=%s', selfUin, data.code, data.message); throw new Error(`qzone feeds failed: code=${data.code} ${data.message ?? ''}`.trim()); } if (!Array.isArray(data.data?.data)) { - log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure', selfUin); - throw new Error('无法获取空间好友动态'); + log.warn('getQzoneFeeds: no data array in response (uin=%s) — likely auth/cookie failure or unverified response shape; body head=%s', selfUin, text.slice(0, 300)); + throw new Error(`无法获取空间好友动态(响应结构异常): ${text.slice(0, 200)}`); } return mapFeeds(data); diff --git a/packages/protocol/src/web/request-util.ts b/packages/protocol/src/web/request-util.ts index 92d3d39c..af03b7e3 100644 --- a/packages/protocol/src/web/request-util.ts +++ b/packages/protocol/src/web/request-util.ts @@ -4,41 +4,44 @@ import https from 'node:https'; type RequestBody = string | Buffer | Uint8Array | Record | undefined; export class RequestUtil { - static async HttpsGetCookies(url: string): Promise<{ [key: string]: string; }> { + // Collect Set-Cookie across the ptlogin2 jump's redirect chain. NEVER hangs: + // a per-request timeout + a redirect-depth cap guarantee termination, and any + // failed/slow hop resolves with the cookies gathered so far rather than + // throwing. This matters because the jump's final hop can target a host the + // deployment can't reach (e.g. a datacenter网络 that times out on + // qzone.qq.com) — without the ceiling that would hang every cookie-backed web + // action forever (the essential cookies are already set by the first hop). + static async HttpsGetCookies(url: string, depth = 0): Promise<{ [key: string]: string; }> { const client = url.startsWith('https') ? https : http; - return new Promise((resolve, reject) => { + return new Promise((resolve) => { + const cookies: { [key: string]: string; } = {}; + let settled = false; + const done = (extra?: { [key: string]: string; }) => { + if (settled) return; + settled = true; + resolve(extra ? { ...cookies, ...extra } : cookies); + }; const req = client.get(url, (res) => { - const cookies: { [key: string]: string; } = {}; - - res.on('data', () => { }); // 必须消耗流 - res.on('end', () => { - this.handleRedirect(res, url, cookies) - .then(resolve) - .catch(reject); - }); - if (res.headers['set-cookie']) { this.extractCookies(res.headers['set-cookie'], cookies); } + res.on('data', () => { }); // 必须消耗流 + res.on('end', () => { + const location = res.headers.location; + if ((res.statusCode === 301 || res.statusCode === 302) && location && depth < 5) { + this.HttpsGetCookies(new URL(location, url).href, depth + 1) + .then((rc) => done(rc)) + .catch(() => done()); + } else { + done(); + } + }); }); - - req.on('error', (error: Error) => { - reject(error); - }); + req.setTimeout(8000, () => { req.destroy(); done(); }); + req.on('error', () => done()); }); } - private static async handleRedirect(res: http.IncomingMessage, url: string, cookies: { [key: string]: string; }): Promise<{ [key: string]: string; }> { - if (res.statusCode === 301 || res.statusCode === 302) { - if (res.headers.location) { - const redirectUrl = new URL(res.headers.location, url); - const redirectCookies = await this.HttpsGetCookies(redirectUrl.href); - return { ...cookies, ...redirectCookies }; - } - } - return cookies; - } - private static extractCookies(setCookieHeaders: string[], cookies: { [key: string]: string; }) { setCookieHeaders.forEach((cookie) => { const parts = cookie.split(';')[0]?.split('='); diff --git a/packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp b/packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp new file mode 100644 index 00000000..0ff00769 --- /dev/null +++ b/packages/protocol/tests/web/fixtures/qzone-feeds-sample.jsonp @@ -0,0 +1,8 @@ +_preloadCallback({ + "code":0, + "subcode":0, + "message":"", + "default":0, + "data": +{main:{attach:'',searchtype :'',hasMoreFeeds:false,daylist:'',uinlist:'',error:'',hotkey:'',icGroupData:[],host_level:'',friend_level:'',lastaccesstime:'',lastAccessRelateTime:'',begintime:'1780711209',endtime:'',dayspac:'11',hidedNameList:[], aisortBeginTime:'', aisortEndTime:'', aisortOffset:'', aisortNextTime:'',owner_bitmap:'08009c8802000401',pagenum:'2',externparam:'basetime=1780711209&pagenum=2&dayvalue=11&getadvlast=0&hasgetadv=&lastentertime=0&LastAdvPos=0&UnReadCount=1&UnReadSum=1&LastIsADV=0&UpdatedFollowUins=&UpdatedFollowCount=0&LastRecomBrandID=&TRKPreciList=&gdtadvcookie=eyJsYXN0X2Fkdl9wb3NpdGlvbiI6LTF9'},data:[{ver:'1',appid:'311',typeid:'0',key:'aef23101297f236ae4f10600',flag:'0',dataonly:'0',titleTemp:'',summaryTemp:'',feedno:'0',title:'',summary:'',appiconid:'311',clscFold:'icenter_list_extend',abstime:'1780711209',feedstime:'6月6日 10:00',userHome:'http://user.qzone.qq.com/20050606',namecardLink:'nameCard_20050606',opuin:'20050606',uin:'20050606',ouin:'',foldFeed:'',foldFeedTitle:'',showEbtn:'',scope:'0',hideExtend:'',nickname:'官方Qzone',emoji:[],remark:'',type:'',vip:'novip',bitmap:'989d9de01513c081',yybitmap:'100008000000000b',info_user_name:'',logimg:'http://qlogo3.store.qq.com/qzone/20050606/20050606/50?1450773587',bor:'',lastFeedBor:'',list_bor2:'',info_user_display:'',upernum:'',oprType:'0',moreflag:'',otherflag:'1_0_1_0_0_0_1',rightflag:'',sameuser:{},uper_isfriend:[],uperlist:[],smallstar:'',html:' \t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\t\t\t\t\t\t\t \x3Cli class=\x22f-single f-s-s\x22 id=\x22fct_20050606_311_0_1780711209_0_1\x22>\x3Cdiv class=\x22f-single-head f-aside\x22>\x3Cdiv class=\x22f-adorn-top\x22>\x3C\/div> \x3Cdiv class=\x22user-pto\x22>\x3Ca href=\x22http:\/\/user.qzone.qq.com\/20050606\x22 target=\x22_blank\x22 class=\x22user-avatar q_namecard f-s-a\x22 link=\x22nameCard_20050606\x22 data-clicklog=\x22avatar\x22>\x3Cimg src=\x22https:\/\/qlogo3.store.qq.com\/qzone\/20050606\/20050606\/50?1450773587\x22>\x3C\/a>\x3C\/div>\x3Cdiv class=\x22user-op\x22>\x3Ca href=\x22javascript:;\x22 class=\x22arrow-down\x22 data-cmd=\x22qz_opr_more\x22 data-moreoperate=\x220\x22>\x3Ci class=\x22fui-icon icon-arrow-down\x22>\x3C\/i>\x3C\/a> \x3C\/div>\x3Cdiv class=\x22user-info\x22>\x3Cdiv class=\x22f-nick\x22>\x3Ca target=\x22_blank\x22 href=\x22http:\/\/user.qzone.qq.com\/20050606\x22 data-clicklog=\x22nick\x22 class=\x22f-name q_namecard \x22 link=\x22nameCard_20050606\x22>官方Qzone\x3C\/a> \x3Ca target=\x22_blank\x22 href=\x22http:\/\/page.qq.com\x22 class=\x22user-medal\x22>\x3Cimg class=\x22ui_mr5\x22 src=\x22\/ac\/qzone_v5\/client\/auth_icon.png\x22 title=\x22腾讯认证\x22 alt=\x22腾讯认证\x22 \/>\x3C\/a> \x3C\/div>\x3Cdiv class=\x22info-detail\x22>\t\t\t\t\t\x3Cspan class=\x22 ui-mr8 state\x22 >\t\t6月6日 10:00\t\t\x3C\/span>\t\t\x3Ca href=\x22javascript:;\x22 data-cmd=\x22qz_sign\x22 class=\x22f-sign-show state\x22 title=\x22我也要设置\x22>\x3C\/a>\x3C\/div>\x3C\/div>\x3C\/div>\x3Cdiv class=\x22f-single-content f-wrap\x22>\x3Cdiv class=\x22f-item f-s-i\t\x22 id=\x22feed_20050606_311_0_1780711209_0_1\x22 data-feedsflag=\x22\x22 data-iswupfeed=\x221\x22 data-key=\x22aef23101297f236ae4f10600\x22 data-specialtype=\x22\x22 data-extend-info=\x221_0_1_0_0_0_1|989d9de01513c081|100008000000000b\x22 data-functype=\x22func_friend_feed\x22 data-hasfollowed=\x221\x22>\x3Cdiv class=\x22f-info qz_info_cut\x22>\t\t\t\t\t时间从不说谎,它把你以为的妄想,悄悄兑换成了现实;它把你以为忘了的那些日子,原原本本保存了下来。\x3Cbr\/>21年了,QQ空间也记得。\x3Cbr\/>今天,「那年今日」更新了—— 翻开那些年的说说、照片和动态,被收进时光里的每一个你,都还在。\x3Cbr\/>不用刻意回忆,不用费力寻找,它自己找到你,轻轻拍了拍你的肩。\x3Cbr\/>\t\t \x3Ca href=\x22javascript:;\x22 data-cmd=\x22qz_toggle\x22 data-pos=\x221\x22>展开全文\x3C\/a>\x3Cimg src=\x22http:\/\/qzonestyle.gtimg.cn\/qzone_v6\/img\/feed\/loading.gif\x22 class=\x22load_img none\x22>\x3C\/div>\x3Cdiv class=\x22f-info qz_info_complete none\x22>\x3C\/div>\x3Cdiv class=\x22qz_summary wupfeed\x22 id=\x22hex_20050606_311_0_1780711209_0_1\x22>\x3Ci class=\x22none\x22 name=\x22feed_data\x22 \t data-bitmap=\x22989d9de01513c081\x22\t data-yybitmap=\x22100008000000000b\x22\t data-vipstarbitmap=\x220100004002000080\x22\t\t data-fkey=\x22aef23101297f236ae4f10600\x22\t data-tid=\x22aef23101297f236ae4f10600\x22\t data-uin=\x2220050606\x22\t data-origfkey=\x22\x22\t data-origtid=\x22aef23101297f236ae4f10600\x22\t data-origuin=\x2220050606\x22\t data-subid=\x22\x22\t data-totweet=\x22\x22\t data-issignin=\x22\x22\t data-source=\x22\x22\t data-retweetcount=\x221\x22\t data-stat=\x22exNDgYmCtvjmonh4K6e5PbvTJDuPAUSNib6qlt2tPSxjX2r0nouNT4bs6UTPWfIfxQBQa7z!kH9ELZBD0r25iV6FuCL0P8cG6914CLBsLy297p1QCYK618bKYmDnJRgWOJRuWEuCwKpiEkd3B!O!uSIc!Hpwf5zceJM2h16yaSuK3pjKxpNwq1oLq4MIM4BZMzAkbzg1AwK34lk5dZEXd8aRZL0TQrBX_\x22 \t data-topicid=\x2220050606_aef23101297f236ae4f10600__1\x22 \t \t data-feedstype=\x22100\x22 \t data-abstime=\x221780711209\x22 \t data-iswupfeed=\x221\x22 \t\t\t data-platformid=\x2252\x22 \t\t\t\t\t data-accessright=\x221\x22\t\t\t\t\t\t\t\t\t\t\t\t>\x3C\/i>\x3Cdiv class=\x22f-ct \x22>\x3Cdiv class=\x22f-ct-txtimg fui-txtimg f-ct-video \x22> \x3Cdiv class=\x22txt-box \x22> \t\t\t\t\t\t\t\t\t \x3C\/div> \x3Cdiv class=\x22img-box f-video-wrap play\x22 url3=\x22https:\/\/photovideo.photo.qq.com\/1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca.f20.mp4?dis_k=af9adeffd476b770519e37826170e96a&dis_t=1782911754&vuin=3433035623&owner=MjAwNTA2MDY=\x22 > \x3Ca class=\x22img-item \x22data-cmd=\x22qz_popup\x22 href=\x22https:\/\/user.qzone.qq.com\/20050606\/311\/1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca\x22 data-v_itemid=\x221074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca\x22 data-v_type=\x221\x22 data-v_picinfo_url=\x22https:\/\/m.qpic.cn\/psc?\/eabfd933-2c89-47cc-8138-5b5463dab9e9\/MgefXoixntJCvPruFHdJTSW.iR0yk*dsdY1s2MYZO1w1*EHOCLeibHhhEFGLCO98HKhHMnNLec2Vz6nVgZnqGo9yAiFqlb*K5FC72D3XGY4!\/c&bo=OASABwAAAAABJ7s!\x22 data-v_picinfo_width=\x22512\x22 data-v_picinfo_height=\x22910\x22 data-v_vidiourl=\x22\x22 data-v_vidioswfurl=\x22https:\/\/photovideo.photo.qq.com\/1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca.f20.mp4?dis_k=af9adeffd476b770519e37826170e96a&dis_t=1782911754&vuin=3433035623&owner=MjAwNTA2MDY=\x22 data-v_h265=\x22\x22 data-v_source_website=\x22\x22 data-v_writefrom=\x22\x22 data-videotype= \x22mood\x22 data-clicklog=\x22video\x22 hotclickPath=\x22\x22 hotdomain=\x22\x22 data-weishi_feedid=\x22\x22 data-version=\x223\x22 data-param=\x223&videosrc=https%3A%2F%2Fphotovideo.photo.qq.com%2F1074_0b53eyz7eaicg4ai2kzbwzvdajqe6keaeaca.f20.mp4%3Fdis_k%3Daf9adeffd476b770519e37826170e96a%26dis_t%3D1782911754%26vuin%3D3433035623%26owner%3DMjAwNTA2MDY%3D&type=1&org_vidio_url=\x22 data-src=\x22\/qzone\/app\/mood\/richinfo_view.html\x22 data-width=\x22512\x22 data-height=\x22512\x22 data-type=\x22popup\x22 data-title=\x22\x22 data-config=\x22\x22 data-extendinfo1 =\x22\x22 data-extendinfo2 =\x22\x22 data-extendinfo3 =\x22\x22 data-extendinfo4 =\x22\x22 data-extendinfo11 =\x22\x22> \x3Cdiv class=\x22video-img\x22> \x3Ci class=\x22inner icon-media-play\x22>\x3C\/i> \x3Cimg alt=\x22视频缩略图\x22 style=\x22object-fit: contain; max-width:560px; max-height:560px; width:100%; height: 100%; margin: \x22 src=\x22https:\/\/m.qpic.cn\/psc?\/eabfd933-2c89-47cc-8138-5b5463dab9e9\/MgefXoixntJCvPruFHdJTSW.iR0yk*dsdY1s2MYZO1w1*EHOCLeibHhhEFGLCO98HKhHMnNLec2Vz6nVgZnqGo9yAiFqlb*K5FC72D3XGY4!\/c&bo=OASABwAAAAABJ7s!\x22 \/> \x3C\/div> \x3C\/a> \x3C\/div> \x3C\/div>\x3Cdiv class=\x22f-reprint\x22> \x3Cp class=\x22item\x22> \x3Ci class=\x22fui-icon icon-print-phone\x22>\x3C\/i>\x3Cspan class=\x22ui-mr8 state\x22>来自\t\t\t\t\t\t\t\t\t \t\t\t\t\t\t\t\x3Ca href=\x22http:\/\/z.qzone.com?from=iphonegrzxpl\x22 \t\t\t\t\t\t\t\t\t\t\ttarget=\x22_blank\x22 \t\t\t\t\t\t\t\t\t\t\t\t class=\x22 phone-style state\x22\t>\t\tiPhone\t\t\x3C\/a>\t\t\t \t\t\t\x3C\/span> \x3C\/p> \x3C\/div> \x3C\/div>\x3C\/div>\x3C\/div>\x3C\/div>\x3Cdiv class=\x22f-single-foot\x22>\x3Cdiv class=\x22f-op-detail f-detail \x22>\t\t\x3Cp class=\x22op-list\x22>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\x3Ca \t\t\tclass=\x22item qz_retweet_btn \x22 \t\t\thref=\x22javascript:;\x22 \t\t\tdata-cmd=\x22qz_popup\x22 \t\t\tdata-version=\x224\x22 \t\t\t\t\t\tdata-isnewtype=\x221\x22 \t\t\tdata-type=\x22ForwardingBox\x22 \t\t\tdata-src=\x22\/qzone\/app\/controls\/forwardingBox\/forwardingBoxFacade.js\x22 \t\t\tdata-clicklog=\x22retweet\x22 \t\t\tdata-publicpav=\x22\x22 \t\t\t\t\t>\t\t\t\x3Ci class=\x22fui-icon icon-op-share\x22>\x3C\/i>\t\t\x3C\/a>\t\t\t\t\t\t\t\t\t\t\x3Cspan class=\x22item-line\x22>\x3C\/span>\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t \t\t\t\t\t\x3Ca href=\x22javascript:;\x22 \t\t\t\t\t\t\t\t\t\t\t\t\tdata-version=\x226.3\x22 \t\t\t\t\tdata-cmd=\x22qz_reply\x22 \t\t\t\t\tdata-link=\x221\x22 \t\t\t\t\tdata-clicklog=\x22comment\x22 \t\t\t\t\t\t\t class=\x22 qz_btn_reply item \x22\t>\t\t\t\x3Ci class=\x22fui-icon icon-op-comment\x22>\x3C\/i>\t\t\t\t\t\t\x3C\/a>\t\t\t \t\t\t\t\t\t\t\t\t\t\t\x3Cspan class=\x22item-line\x22>\x3C\/span>\t\t\t\x3Ca class=\x22item qz_like_btn_v3 \x22 \t\t\t\t\t\tdata-islike=\x220\x22 \t\t\t\t\t\tdata-likecnt=\x223173513\x22 \t\t\tdata-showcount=\x220\x22 \t\t\tdata-unikey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 \t\t\tdata-curkey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 \t\t\t\t\t\t\tdata-clicklog=\x22like\x22 \t\t\t\t\t\t\t\t\thref=\x22javascript:;\x22\t\t>\t\t\t\x3Ci class=\x22fui-icon icon-op-praise\x22>\x3C\/i>\t\t\x3C\/a>\t\t\t\t\x3C\/p>\x3Ca href=\x22javascript:;\x22 class=\x22state qz_feed_plugin\x22 data-role=\x22Visitor\x22 data-config=\x22311|aef23101297f236ae4f10600|20050606\x22 data-clicklog=\x22visitor\x22>浏览173581134次\x3C\/a>\x3C\/div> \x3Cdiv class=\x22f-like-list f-like _likeInfo\x22 likeinfo=\x223173513\x22>\x3Cdiv class=\x22icon-btn\x22>\x3Ca href=\x22javascript:;\x22 data-islike=\x220\x22 data-likecnt=\x223173513\x22 data-showcount=\x223173513\x22 data-unikey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 data-curkey=\x22http:\/\/user.qzone.qq.com\/20050606\/mood\/aef23101297f236ae4f10600\x22 data-clicklog=\x22like\x22 class=\x22praise qz_like_prase\x22>\x3Ci class=\x22fui-icon icon-list-praise\x22>\x3C\/i>\x3C\/a>\x3Cdiv class=\x22bubble\x22 style=\x22display:none;\x22>\x3Cdiv class=\x22bd\x22>+1\x3C\/div>\x3Cb class=\x22arrow arrow-down\x22>\x3C\/b>\x3C\/div>\x3C\/div>\x3Cdiv class=\x22user-list\x22>\x3Cspan class=\x22f-like-cnt f-famous-qzone\x22>3173513\x3C\/span>人觉得很赞\x3C\/div>\x3C\/div>\x3Cdiv class=\x22mod-comments\x22 style=\x22padding:0\x22>\x3Cdiv class=\x22mod-commnets-poster feedClickCmd comment_default_inputentry\x22 data-cmd=\x22qz_reply\x22 data-version=\x226\x22 data-action=\x22http:\/\/taotao.qq.com\/cgi-bin\/emotion_cgi_re_feeds\x22 data-param=\x22t1_source=&t1_uin=20050606&t1_tid=aef23101297f236ae4f10600&signin=0&sceneid=100\x22 data-charset=\x22utf-8\x22 data-maxLength=\x22\x22 data-tuin=\x2220050606\x22 data-config=\x221|1|1|1,b52,with_fwd,同时转发;0|1,taotaoact.qzone.qq.com,@InputReply|1,taotaoact.qzone.qq.com,@ClickReply|1,taotaoact.qzone.qq.com,commentPresentClick\x22 data-tid=\x22\x22 >\x3Cdiv class=\x22comments-poster-bd comments-poster-default\x22>\x3Cdiv class=\x22comments-box\x22 data-clicklog=\x22comment\x22>\x3Cdiv class=\x22textinput textinput-default bor2\x22 contenteditable=\x22true\x22 alt=\x22replybtn\x22 placeholder=\x22评论\x22>\x3Ca class=\x22c_tx3\x22 href=\x22javascript:void(0);\x22 alt=\x22replybtn\x22>评论\x3C\/a>\x3C\/div>\x3Cdiv class=\x22mod-insert-img\x22>\x3Ca href=\x22javascript:;\x22 data-cmd=\x22qz_quick_upload_img\x22 class=\x22btn-insert-img bg\x22>\x3Ci class=\x22icon-camera-16\x22>\x3C\/i>\x3C\/a>\x3C\/div>\x3C\/div>\x3C\/div>\x3C\/div>\x3C\/div> \x3C\/div>\x3C\/li>\t', mergeData:[undefined], likecnt:'', relycnt:'', commentcnt:''},undefined]}} +); diff --git a/packages/protocol/tests/web/qzone-feeds-parse.test.ts b/packages/protocol/tests/web/qzone-feeds-parse.test.ts new file mode 100644 index 00000000..7511f14a --- /dev/null +++ b/packages/protocol/tests/web/qzone-feeds-parse.test.ts @@ -0,0 +1,75 @@ +import { describe, it, expect } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { mapFeeds, parseQzoneCallback } from '@snowluma/protocol/web/qzone'; + +// Real feeds3_html_more response captured live (issue #182). Its `data` value +// is a JS object literal (unquoted keys, single-quoted strings, \xNN escapes, +// trailing `undefined`) — JSON.parse throws on it; parseQzoneCallback must not. +const SAMPLE = readFileSync( + fileURLToPath(new URL('./fixtures/qzone-feeds-sample.jsonp', import.meta.url)), + 'utf8', +); + +interface RawFeeds { + code?: number; + data?: { data?: unknown[]; hasmore?: number | string }; +} + +describe('qzone feeds JS-literal parsing (issue #182)', () => { + it('JSON.parse chokes on the real body (regression baseline)', () => { + const inner = SAMPLE.slice(SAMPLE.indexOf('{'), SAMPLE.lastIndexOf('}') + 1); + expect(() => JSON.parse(inner)).toThrow(); + }); + + it('parseQzoneCallback evaluates the JS-literal payload', () => { + const data = parseQzoneCallback(SAMPLE); + expect(data.code).toBe(0); + expect(Array.isArray(data.data?.data)).toBe(true); + // The array carries a trailing `undefined` hole alongside the real feed. + expect(data.data!.data!.length).toBe(2); + expect(data.data!.data!.some((x) => x === undefined)).toBe(true); + }); + + it('mapFeeds drops the undefined hole and normalises the feed', () => { + const data = parseQzoneCallback(SAMPLE); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const result = mapFeeds(data as any); + expect(result.feeds).toHaveLength(1); + const f = result.feeds[0]!; + expect(f.uin).toBe(20050606); + expect(f.nickname).toBe('官方Qzone'); + expect(f.appid).toBe(311); + expect(f.time).toBe(1780711209); + expect(f.key).toBe('aef23101297f236ae4f10600'); + // \xNN escapes decoded by the JS eval, html passed through verbatim. + expect(f.html).toContain('
  • { + // The parser has no notion of globals, member access, or calls: any such + // token is rejected, so a tampered body cannot reach `process`/`Function` + // etc. (the whole reason we do NOT eval this payload). + expect(() => parseQzoneCallback('_preloadCallback({x: process})')).toThrow(); + expect(() => parseQzoneCallback('_preloadCallback({x: callback.constructor})')).toThrow(); + expect(() => parseQzoneCallback('_preloadCallback({x: (function(){return 1})()})')).toThrow(); + expect(() => parseQzoneCallback('_preloadCallback(eval("1+1"))')).toThrow(); + }); + + it('does not pollute Object.prototype via a __proto__ key', () => { + parseQzoneCallback('_preloadCallback({"__proto__":{"polluted":1},"code":0})'); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + expect(({} as any).polluted).toBeUndefined(); + }); + + it('decodes JS string escapes (\\xNN, \\/) literally, not as markup', () => { + const d = parseQzoneCallback<{ s?: string }>("_preloadCallback({s:'\\x3Cb\\x3E&\\/x'})"); + expect(d.s).toBe('&/x'); + }); + + it('rejects a body that captures no object', () => { + expect(() => parseQzoneCallback('_preloadCallback(42)')).toThrow('invalid feeds response'); + expect(() => parseQzoneCallback('void 0')).toThrow('invalid feeds response'); + }); +}); diff --git a/packages/protocol/tests/web/qzone.test.ts b/packages/protocol/tests/web/qzone.test.ts index d45d4629..83790511 100644 --- a/packages/protocol/tests/web/qzone.test.ts +++ b/packages/protocol/tests/web/qzone.test.ts @@ -175,17 +175,17 @@ describe('qzone / getQzoneFeeds (HTTP layer)', () => { }); it('returns an empty list (not a throw) for a genuinely empty feed', async () => { - vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{"data":[],"hasmore":0}}'); + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":0,"data":{"data":[],"hasmore":0}});'); await expect(getQzoneFeeds(cookies, '10000')).resolves.toEqual({ feeds: [], has_more: false }); }); it('throws on a non-zero qzone code', async () => { - vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":-3000,"message":"need login"}'); + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":-3000,"message":"need login"});'); await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('code=-3000'); }); it('throws when the data array is absent (cookie failure), not an empty list', async () => { - vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('{"code":0,"data":{}}'); + vi.spyOn(RequestUtil, 'HttpGetText').mockResolvedValue('_preloadCallback({"code":0,"data":{}});'); await expect(getQzoneFeeds(cookies, '10000')).rejects.toThrow('无法获取空间好友动态'); }); }); From 72aedbc6121c8370267bcc692937adcb8d2ef83e Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Wed, 1 Jul 2026 22:15:01 +0800 Subject: [PATCH 30/30] chore(release): v1.11.1 --- package.json | 2 +- packages/bridge/package.json | 2 +- packages/common/package.json | 2 +- packages/core/package.json | 2 +- packages/mcp/package.json | 2 +- packages/onebot/package.json | 2 +- packages/proto-defs/package.json | 2 +- packages/protocol/package.json | 2 +- packages/proton/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 14 files changed, 14 insertions(+), 14 deletions(-) diff --git a/package.json b/package.json index a8de2337..c83b5e0c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.11.0", + "version": "1.11.1", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index ced5c0fc..20be2547 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.11.0", + "version": "1.11.1", "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).", diff --git a/packages/common/package.json b/packages/common/package.json index 0fd848dc..f0c5ac07 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.11.0", + "version": "1.11.1", "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).", diff --git a/packages/core/package.json b/packages/core/package.json index b3932d3a..58373dc7 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.11.0", + "version": "1.11.1", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/mcp/package.json b/packages/mcp/package.json index fb901dad..c22e59fe 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.11.0", + "version": "1.11.1", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/onebot/package.json b/packages/onebot/package.json index aba2fc1c..2f9b28bb 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.11.0", + "version": "1.11.1", "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..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/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index bb23b6a0..466bc522 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.11.0", + "version": "1.11.1", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` 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).", diff --git a/packages/protocol/package.json b/packages/protocol/package.json index dc636410..b1b8e2a9 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.11.0", + "version": "1.11.1", "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/'` collapses to `import { … } from '@snowluma/protocol/'`.", diff --git a/packages/proton/package.json b/packages/proton/package.json index 11757c82..30e33528 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.11.0", + "version": "1.11.1", "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.", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 56018e8f..f27b3255 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.11.0", + "version": "1.11.1", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 167311e2..2fa236b1 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.11.0", + "version": "1.11.1", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index ccab21bd..6fba313f 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.11.0", + "version": "1.11.1", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index 8a9b46f5..32a4b50a 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.11.0", + "version": "1.11.1", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index a577b1eb..8d94d726 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.11.0", + "version": "1.11.1", "type": "module", "scripts": { "dev": "vite",