diff --git a/package.json b/package.json index 38cb82ba..552fe793 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.12.0", + "version": "1.12.1", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index 10c0f48b..8152f2a2 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.12.0", + "version": "1.12.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 66196198..197ab253 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.12.0", + "version": "1.12.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 3e8b79c3..f0e8c696 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.12.0", + "version": "1.12.1", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 521b994e..ec94647e 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -235,6 +235,12 @@ export class ContactsApi { return this.ctx.identity.getGroupInviteCardSequence(groupId); } + /** Resolve the group for a private invite-card msgseq. Numeric OneBot flags + * use this path because the card sequence is absent from 0x10C0. */ + findGroupInviteCardGroupBySequence(sequence: number): number | undefined { + return this.ctx.identity.findGroupInviteCardGroupBySequence(sequence); + } + async fetchDownloadRKeys(): Promise { const resp = await FetchDownloadRkeys.invoke(this.ctx); diff --git a/packages/core/src/bridge/apis/forward.ts b/packages/core/src/bridge/apis/forward.ts index af071639..285f2b4d 100644 --- a/packages/core/src/bridge/apis/forward.ts +++ b/packages/core/src/bridge/apis/forward.ts @@ -1,5 +1,6 @@ import type { PacketInfo } from '@snowluma/common/protocol-types'; import { mapWithConcurrency } from '@snowluma/common/concurrency'; +import { createLogger } from '@snowluma/common/logger'; import type { LongMsgResult, RecvLongMsgReq, @@ -9,7 +10,8 @@ import type { } from '@snowluma/proto-defs/longmsg'; import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message'; import { buildSendElems } from '@snowluma/protocol/element-builder'; -import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events'; +import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events'; +import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; import { parseMsgPush } from '@snowluma/protocol/msg-push'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { randomUUID } from 'crypto'; @@ -25,6 +27,14 @@ function asBridge(ctx: BridgeContext): Bridge { return ctx as unknown as Bridge; // resolve a forward immediately after receiving the parent message. const forwardResCache = new Map(); +const log = createLogger('Bridge.Forward'); + +// Forward bodies are gzip-compressed by QQ. Bound decompression while zlib is +// producing output so a small server response cannot expand until the process +// exhausts its heap. 32 MiB leaves ample room for legitimate merged forwards +// while making the maximum per-fetch allocation explicit. +const FORWARD_LONG_MSG_MAX_OUTPUT_BYTES = 32 * 1024 * 1024; + /** QQ's placeholder when it doesn't hand back a real sender name — treated as * "missing" so #174's enrichment resolves the real nickname. */ const FORWARD_NAME_PLACEHOLDER = 'QQ用户'; @@ -233,8 +243,8 @@ function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElemen }; } -function stripFileSource(element: MessageElement): MessageElement { - const next: MessageElement = { ...element }; +function stripFileSource(element: MessageElementOf<'file'>): MessageElementOf<'file'> { + const next: MessageElementOf<'file'> = { ...element }; delete next.url; return next; } @@ -258,10 +268,28 @@ function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta): return (element.fileName ?? cached?.fileName ?? '').trim(); } +function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void { + for (const node of nodes) { + const fileCount = node.elements.filter((element) => element.type === 'file').length; + if (fileCount > 1) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'a private forward node can contain at most one file element', + 'file', + ); + } + if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward); + } +} + export class ForwardApi { constructor(private readonly ctx: BridgeContext) { } async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { + // A c2c RichText owns exactly one msgContent/FileExtra payload. Validate + // the entire recursive tree before any file/media/long-message upload so a + // second file cannot be uploaded and then silently discarded. + if (groupId === undefined) assertPrivateForwardFileCapacity(nodes); const { resId } = await this.uploadRecursive(nodes, groupId, userId); return resId; } @@ -281,7 +309,7 @@ export class ForwardApi { name: string, groupId?: number, userId?: number, - ): Promise { + ): Promise> { if (groupId !== undefined) { const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false); if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id'); @@ -577,7 +605,27 @@ export class ForwardApi { throw new Error('download forward message payload is empty'); } - const inflate = gunzipSync(Buffer.from(payload)); + let inflate: Buffer; + try { + inflate = gunzipSync(Buffer.from(payload), { + maxOutputLength: FORWARD_LONG_MSG_MAX_OUTPUT_BYTES, + }); + } catch (cause) { + const reason = cause instanceof Error ? cause.message : String(cause); + log.warn( + 'forward long-msg decompression failed: res_id=%s compressed_bytes=%d max_output_bytes=%d error=%s', + resId, + payload.byteLength, + FORWARD_LONG_MSG_MAX_OUTPUT_BYTES, + reason, + ); + throw new Error( + `download forward message decompression failed ` + + `(res_id=${resId}, compressed_bytes=${payload.byteLength}, ` + + `max_output_bytes=${FORWARD_LONG_MSG_MAX_OUTPUT_BYTES}): ${reason}`, + { cause }, + ); + } const longMsg = protobuf_decode(inflate); const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : []; const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg'); diff --git a/packages/core/src/bridge/apis/message.ts b/packages/core/src/bridge/apis/message.ts index 3f5cd8b3..cfc63baa 100644 --- a/packages/core/src/bridge/apis/message.ts +++ b/packages/core/src/bridge/apis/message.ts @@ -219,6 +219,54 @@ export class MessageApi { return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; } + /** + * Reply into an existing group temp session (临时会话). Wire primitive only — + * it does NOT gate; the caller verifies the session before calling. Routes + * through `grpTmp` (RoutingHead field 3) with { groupUin, toUid } and a normal + * c2c content head. + */ + async sendGroupTempMessage( + userUin: number, + groupUin: number, + elements: MessageElement[], + ): Promise { + if (elements.length === 0) throw new Error('message is empty'); + + const userUid = await this.ctx.resolveUserUid(userUin); + const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid }); + const random = this.ctx.nextMessageRandom(); + const clientSeq = this.ctx.nextClientSequence(); + + const request = protobuf_encode({ + routingHead: { + grpTmp: { groupUin: BigInt(groupUin), toUid: userUid }, + }, + contentHead: { type: 1, subType: 0, c2cCmd: 11 }, + messageBody: { richText: { elems: protoElems } }, + clientSequence: clientSeq, + random, + syncCookie: new Uint8Array(0), + via: 0, + dataStatist: 0, + ctrl: { msgFlag: Math.floor(Date.now() / 1000) }, + multiSendSeq: 0, + }); + + const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request); + if (!result.success || !result.gotResponse || !result.responseData) { + throw new Error(`send temp message failed: ${result.errorMessage || 'no response'}`); + } + const response = protobuf_decode(result.responseData); + if (!response) throw new Error('failed to decode SendMessageResponse'); + if (response.result != null && response.result !== 0) { + throw new Error(`send temp message rejected: result=${response.result} err=${response.errMsg ?? ''}`); + } + const seq = response.privateSequence ?? 0; + const messageId = (random & 0x7FFFFFFF) || seq; + const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000); + return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp }; + } + /** * Send a c2c file as a chat message. * diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index f9d99eb1..8af920c4 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -19,10 +19,15 @@ const log = createLogger('Bridge'); export class Bridge implements BridgeInterface { readonly identity: IdentityService; private pids_ = new Set(); + /** Packet senders keyed by their owning QQ process. Keeping the sender and + * PID together is what makes disconnect fallback deterministic: a sender + * can never outlive the PID that supplied it. */ + private readonly packetClientsByPid_ = new Map(); readonly events = new BridgeEventBus(); readonly apis: ApiHub; private readonly pipeline: IncomingPacketPipeline; private packetClient_: PacketSender | null = null; + private packetClientPid_: number | null = null; private static readonly UPLOADED_FILE_CACHE_MAX = 1024; private uploadedFileMeta_ = new Map(); private clientSeq_ = 100000000 + (Date.now() % 1000000000); @@ -52,17 +57,38 @@ export class Bridge implements BridgeInterface { } }, resolveGroupJoinRequest: async (groupId, uid, subType) => { - try { - const requests = await this.apis.contacts.fetchGroupRequests(); - const match = requests.find(r => { - if (r.groupId !== groupId) return false; - return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid; - }); - if (!match) return null; - return { comment: match.comment, sequence: match.sequence }; - } catch { - return null; + const [main, filtered] = await Promise.allSettled([ + this.apis.contacts.fetchGroupRequests(false), + this.apis.contacts.fetchGroupRequests(true), + ]); + if (main.status === 'rejected') { + log.warn('group-request enrichment main inbox failed: group=%d uid=%s err=%s', + groupId, uid, main.reason instanceof Error ? main.reason.message : String(main.reason)); } + if (filtered.status === 'rejected') { + log.warn('group-request enrichment filtered inbox failed: group=%d uid=%s err=%s', + groupId, uid, filtered.reason instanceof Error ? filtered.reason.message : String(filtered.reason)); + } + if (main.status === 'rejected' && filtered.status === 'rejected') { + throw new Error('failed to fetch group requests from both inboxes'); + } + const requests = [ + ...(main.status === 'fulfilled' ? main.value : []), + ...(filtered.status === 'fulfilled' ? filtered.value : []), + ]; + return requests.find(r => { + if (r.groupId !== groupId) return false; + return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid; + }) ?? null; + }, + resolveGroupInviteCardSequence: async (groupId) => { + const deadline = Date.now() + 1_000; + do { + const sequence = this.apis.contacts.getGroupInviteCardSequence(groupId); + if (sequence) return sequence; + await new Promise(resolve => setTimeout(resolve, 25)); + } while (Date.now() < deadline); + return null; }, }); this.pipeline.registerCmd(MSG_PUSH_CMD, (pkt, identity) => parseMsgPush(pkt, identity, this.sysMsgDedup_)); @@ -70,12 +96,28 @@ export class Bridge implements BridgeInterface { } dispose(): void { - this.identity.close(); - this.events.clear(); + this.pids_.clear(); + this.packetClientsByPid_.clear(); + this.packetClient_ = null; + this.packetClientPid_ = null; + try { + this.identity.close(); + } finally { + // A close failure must remain visible to the caller, but must not leave + // event subscribers attached to a Bridge that Manager already removed. + this.events.clear(); + } } + /** Legacy two-step setter retained for external compatibility. It assigns + * the sender to the most recently attached PID when one exists. New + * BridgeManager code uses bindPid() for an atomic transition. */ setPacketClient(client: PacketSender): void { this.packetClient_ = client; + const pids = [...this.pids_]; + const pid = pids.length > 0 ? pids[pids.length - 1]! : null; + this.packetClientPid_ = pid; + if (pid !== null) this.packetClientsByPid_.set(pid, client); } registerCmd(cmd: string, parser: CmdParser): void { @@ -86,17 +128,54 @@ export class Bridge implements BridgeInterface { return this.pipeline.handlesCmd(cmd); } + /** Attach a process without a sender. Retained for compatibility; the + * manager uses bindPid() for the atomic PID+sender transition. Re-attaching + * deliberately refreshes recency. */ attachPid(pid: number): void { + this.pids_.delete(pid); this.pids_.add(pid); } + + /** Atomically attach a process and make its sender the active sender. + * Set insertion order is the recency order used for fallback. */ + bindPid(pid: number, client: PacketSender): void { + this.attachPid(pid); + this.packetClientsByPid_.set(pid, client); + this.packetClient_ = client; + this.packetClientPid_ = pid; + } + + /** @internal BridgeManager lookup used when an incoming packet is the first + * observation that a live PID changed UIN. */ + packetClientForPid(pid: number): PacketSender | null { + return this.packetClientsByPid_.get(pid) ?? null; + } + detachPid(pid: number): void { this.pids_.delete(pid); + this.packetClientsByPid_.delete(pid); + + if (this.packetClientPid_ !== pid) { + // An unscoped legacy sender cannot be associated with a particular PID. + // It is safe to retain while another PID exists, but never after the + // Bridge becomes empty. + if (this.pids_.size === 0) { + this.packetClient_ = null; + this.packetClientPid_ = null; + } + return; + } + + this.selectFallbackPacketClient(pid); } hasPid(pid: number): boolean { return this.pids_.has(pid); } get empty(): boolean { return this.pids_.size === 0; } get activePid(): number | null { - for (const pid of this.pids_) return pid; - return null; + if (this.packetClientPid_ !== null && this.pids_.has(this.packetClientPid_)) { + return this.packetClientPid_; + } + const pids = [...this.pids_]; + return pids.length > 0 ? pids[pids.length - 1]! : null; } onPacket(pkt: PacketInfo): void { this.pipeline.process(pkt); @@ -159,6 +238,36 @@ export class Bridge implements BridgeInterface { } return result; } + + private selectFallbackPacketClient(detachedPid: number): void { + const pids = [...this.pids_]; + for (let index = pids.length - 1; index >= 0; index -= 1) { + const fallbackPid = pids[index]!; + const fallback = this.packetClientsByPid_.get(fallbackPid); + if (!fallback) continue; + + this.packetClient_ = fallback; + this.packetClientPid_ = fallbackPid; + log.debug( + 'packet sender fallback: UIN=%s detached PID=%d fallback PID=%d', + this.identity.uin, + detachedPid, + fallbackPid, + ); + return; + } + + this.packetClient_ = null; + this.packetClientPid_ = null; + if (this.pids_.size > 0) { + log.warn( + 'packet sender unavailable after PID detach: UIN=%s detached PID=%d remaining PIDs=%d', + this.identity.uin, + detachedPid, + this.pids_.size, + ); + } + } async resolveUserUid(uin: number, groupId?: number): Promise { return this.identity.resolveUid(uin, groupId); } @@ -203,4 +312,3 @@ export interface ClientKeyInfo { } export { AiVoiceChatType }; export type { AiVoiceCategory, StrangerStatus }; - diff --git a/packages/core/src/bridge/manager.ts b/packages/core/src/bridge/manager.ts index a635770d..263d4d2e 100644 --- a/packages/core/src/bridge/manager.ts +++ b/packages/core/src/bridge/manager.ts @@ -17,7 +17,6 @@ const log = createLogger('Bridge'); export class BridgeManager { private sessions_ = new Map(); private pidToUin_ = new Map(); - private pidPacketClients_ = new Map(); private sessionStartedListeners_: SessionStartedCallback[] = []; private sessionClosedListeners_: SessionClosedCallback[] = []; @@ -55,33 +54,16 @@ export class BridgeManager { } onPidDisconnected(pid: number): void { - this.pidPacketClients_.delete(pid); const uin = this.pidToUin_.get(pid); if (!uin) return; - this.pidToUin_.delete(pid); - const session = this.sessions_.get(uin); - if (!session) return; - - session.bridge.detachPid(pid); - if (session.bridge.empty) { - this.sessions_.delete(uin); - log.debug('session closed: UIN=%s', uin); - // Fire before dispose() so listeners can still read bridge.identity. - this.fireSessionClosed(uin, session.bridge); - session.bridge.dispose(); - } + this.detachPidFromSession(pid, uin); } onHookLogin(pid: number, uin: string, packetClient: PacketSender): void { if (!isRealUin(uin)) return; - this.pidPacketClients_.set(pid, packetClient); - - const { session, created } = this.ensureSession(uin); - session.bridge.attachPid(pid); - session.bridge.setPacketClient(packetClient); - this.pidToUin_.set(pid, uin); + const { session, created } = this.bindPid(pid, uin, packetClient, 'login'); if (created) { log.debug('session started: UIN=%s', uin); @@ -93,17 +75,13 @@ export class BridgeManager { if (!pkt.uin || !isRealUin(pkt.uin)) return; const uin = pkt.uin; - // Ensure session exists - const { session, created } = this.ensureSession(uin); - - // Attach PID if known - if (pkt.pid && this.pidPacketClients_.has(pkt.pid)) { - session.bridge.attachPid(pkt.pid); - this.pidToUin_.set(pkt.pid, uin); - - const client = this.pidPacketClients_.get(pkt.pid); - if (client) session.bridge.setPacketClient(client); - } + // A packet may be the first trustworthy observation that a live PID moved + // to another UIN. Apply the exact same ownership transition as login so a + // PID can never remain attached to two Bridges. + const client = pkt.pid > 0 ? this.packetClientForPid(pkt.pid) : null; + const { session, created } = client + ? this.bindPid(pkt.pid, uin, client, 'packet') + : this.ensureSession(uin); // Notify session started on first real packet if (created) { @@ -115,6 +93,91 @@ export class BridgeManager { session.bridge.onPacket(pkt); } + /** Bind PID + sender as one state transition. If the PID changed accounts, + * the old Bridge is fully detached (and, when empty, closed) before the new + * Bridge is created. */ + private bindPid( + pid: number, + uin: string, + packetClient: PacketSender, + source: 'login' | 'packet', + ): { session: QQSession; created: boolean } { + const previousUin = this.pidToUin_.get(pid); + if (previousUin && previousUin !== uin) { + log.warn( + 'PID ownership changed: PID=%d UIN=%s -> UIN=%s source=%s', + pid, + previousUin, + uin, + source, + ); + this.detachPidFromSession(pid, previousUin); + } + + const result = this.ensureSession(uin); + result.session.bridge.bindPid(pid, packetClient); + this.pidToUin_.set(pid, uin); + return result; + } + + private packetClientForPid(pid: number): PacketSender | null { + const uin = this.pidToUin_.get(pid); + if (!uin) return null; + + const session = this.sessions_.get(uin); + if (!session) { + const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; + log.error(message); + throw new Error(message); + } + + const packetClient = session.bridge.packetClientForPid(pid); + if (packetClient) return packetClient; + + const message = `BridgeManager invariant violated: PID=${pid} has no sender in UIN=${uin} session`; + log.error(message); + throw new Error(message); + } + + private detachPidFromSession(pid: number, uin: string): void { + const mappedUin = this.pidToUin_.get(pid); + if (mappedUin !== uin) { + const message = `BridgeManager invariant violated: PID=${pid} detach expected UIN=${uin}, mapped UIN=${mappedUin ?? 'none'}`; + log.error(message); + throw new Error(message); + } + + const session = this.sessions_.get(uin); + if (!session) { + const message = `BridgeManager invariant violated: PID=${pid} references missing UIN=${uin} session`; + log.error(message); + throw new Error(message); + } + + if (!session.bridge.hasPid(pid)) { + const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge does not own the PID`; + log.error(message); + throw new Error(message); + } + if (!session.bridge.packetClientForPid(pid)) { + const message = `BridgeManager invariant violated: PID=${pid} is mapped to UIN=${uin}, but Bridge has no sender for the PID`; + log.error(message); + throw new Error(message); + } + + // Validation is complete. Mutate both sides only after the ownership + // invariant is known to hold, so a fail-fast error preserves the evidence. + this.pidToUin_.delete(pid); + session.bridge.detachPid(pid); + if (!session.bridge.empty) return; + + this.sessions_.delete(uin); + log.debug('session closed: UIN=%s', uin); + // Fire before dispose() so listeners can still read bridge.identity. + this.fireSessionClosed(uin, session.bridge); + session.bridge.dispose(); + } + private ensureSession(uin: string): { session: QQSession; created: boolean } { let session = this.sessions_.get(uin); if (session) return { session, created: false }; diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 0bbc74b3..7996e7d3 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -82,14 +82,32 @@ async function main() { // Graceful shutdown: dispose managers, await log flush, then exit. // SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path. + let shutdownStarted = false; const shutdown = (signal: string) => async () => { + if (shutdownStarted) return; + shutdownStarted = true; log.warn(`Shutting down (${signal})...`); - oneBotManager.dispose(); - notificationManager.dispose(); - hookManager.dispose(); - stateWiring.dispose(); + let exitCode = 0; + try { + await oneBotManager.dispose(); + } catch (error) { + exitCode = 1; + log.error('OneBot shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); + } + try { notificationManager.dispose(); } catch (error) { + exitCode = 1; + log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); + } + try { hookManager.dispose(); } catch (error) { + exitCode = 1; + log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); + } + try { stateWiring.dispose(); } catch (error) { + exitCode = 1; + log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error)); + } await closeLogger(); - process.exit(0); + process.exit(exitCode); }; process.on('SIGINT', shutdown('SIGINT')); process.on('SIGTERM', shutdown('SIGTERM')); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 8280b6e5..0f33bb71 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -2,7 +2,11 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; import type { HookManager, HookProcessInfo } from '@snowluma/bridge'; import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; -import { loadOneBotConfig, saveOneBotConfig } from '@snowluma/onebot/config'; +import { + loadOneBotConfig, + OneBotConfigValidationError, + saveOneBotConfig, +} from '@snowluma/onebot/config'; import { loadGlobalSettings, saveGlobalSettings } from '@snowluma/onebot/global-config'; import type { OneBotManager } from '@snowluma/onebot/manager'; import type { OneBotConfig, JsonObject as OneBotJsonObject } from '@snowluma/onebot/types'; @@ -347,10 +351,11 @@ export async function initWebUI( // `pickComparable` strips `adapter.detail` — that's a localised human // string assembled with HH:MM:SS timestamps from the last webhook // delivery; including it in the diff would make every webhook event - // produce a publish (defeating the diff). We compare ONLY name + kind + - // status, which captures every transition the dashboard actually - // renders differently. The SSE handler still ships the FULL snapshot - // (with `detail`) — it's only the diff key that's pruned. + // produce a publish (defeating the diff). We compare name + kind + status, + // plus the structured `lastErrorAt`: a new apply failure must refresh its + // error/time even when the adapter was already degraded. The SSE handler + // still ships the FULL snapshot (with `detail` and `lastError`) — it's only + // the diff key that's pruned. // // Trade-off: the rendered detail string (e.g. "3 个客户端", "上次推送 // 14:53:01") only refreshes on the next SSE push or on the 30s REST @@ -375,9 +380,9 @@ export async function initWebUI( // if the snapshot shape ever drifts. adapters: Array.isArray(acc.adapters) ? acc.adapters.map((a: unknown) => { - const o = a as { name?: string; kind?: string; status?: string }; - return { name: o.name, kind: o.kind, status: o.status }; - }) + const o = a as { name?: string; kind?: string; status?: string; lastErrorAt?: number }; + return { name: o.name, kind: o.kind, status: o.status, lastErrorAt: o.lastErrorAt }; + }) : [], })); }, @@ -1134,19 +1139,69 @@ export async function initWebUI( app.post('/api/config/:uin', async (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); + let body: unknown; try { - const body = (await c.req.json()) as OneBotConfig; - saveOneBotConfig(uin, body); - const reloaded = oneBotManager.reloadConfig(uin); - log.info('Updated OneBot config for UIN: %s%s', uin, reloaded ? ' and reloaded' : ''); + body = await c.req.json(); + } catch { + return c.json({ success: false, saved: false, applied: false, message: '请求格式错误' }, 400); + } + + try { + saveOneBotConfig(uin, body as OneBotConfig); + } catch (err) { + const message = err instanceof Error ? err.message : String(err); + if (err instanceof OneBotConfigValidationError) { + log.warn('reject invalid config for uin=%s: %s', uin, message); + return c.json({ success: false, saved: false, applied: false, message }, 400); + } + log.error('persist config for uin=%s failed: %s', uin, message); + return c.json({ success: false, saved: false, applied: false, message: '配置保存失败,请检查服务器日志' }, 500); + } + + try { + // Apply the exact validated value that was persisted above. Re-reading + // the path here would race concurrent POSTs (request A could load B and + // falsely report that A was applied). + const apply = await oneBotManager.reloadConfig(uin, body as OneBotConfig); + const message = !apply.online + ? '配置保存成功,当前会话未在线,将在下次连接时生效。' + : apply.applied + ? '配置保存成功,已热重载当前会话。' + : '配置已保存,但部分网络节点未能应用;旧节点已尽力恢复,请查看错误详情。'; + log.info( + 'Updated OneBot config for UIN=%s saved=true online=%s applied=%s failures=%d', + uin, + String(apply.online), + String(apply.applied), + apply.errors.length, + ); return c.json({ success: true, - reloaded, - message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。', + saved: true, + applied: apply.applied, + online: apply.online, + errors: apply.errors, + adapters: apply.adapters, + config: body, + // Legacy compatibility: this field used to mean "a live instance was + // asked to reload". It now only claims success after the awaitable + // reconcile actually completed. + reloaded: apply.online && apply.applied, + message, }); } catch (err) { - log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err)); - return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400); + const message = err instanceof Error ? err.message : String(err); + log.error('config saved but apply crashed for uin=%s: %s', uin, message); + return c.json({ + success: true, + saved: true, + applied: false, + online: oneBotManager.getInstance(uin) !== null, + reloaded: false, + errors: [{ name: 'network-manager', phase: 'reload', message, at: Date.now() }], + config: body, + message: '配置已保存,但热重载失败,请检查服务器日志。', + }); } }); diff --git a/packages/core/tests/actions/forward-file.test.ts b/packages/core/tests/actions/forward-file.test.ts index 408de67a..caf74128 100644 --- a/packages/core/tests/actions/forward-file.test.ts +++ b/packages/core/tests/actions/forward-file.test.ts @@ -267,6 +267,38 @@ describe('actions/forward — file segment inside forward node', () => { })]); }); + it('rejects two files in one private forward node before uploading either file', async () => { + buildSendElemsMock.mockClear(); + const uploadPrivate = vi.fn(); + const sendRawPacket = vi.fn(); + const bridge = mockBridge({ + sendRawPacket: sendRawPacket as any, + apis: { + ...mockBridge().apis, + groupFile: { + ...mockBridge().apis.groupFile, + uploadPrivate, + }, + }, + }); + + await expect(new ForwardApi(bridge as any).upload([{ + userUin: 10001, + nickname: 'alice', + elements: [ + { type: 'file', url: 'base64://AQID', fileName: 'one.txt' }, + { type: 'file', url: 'base64://BAUG', fileName: 'two.txt' }, + ] as any, + }], undefined, 67890)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'file', + }); + + expect(uploadPrivate).not.toHaveBeenCalled(); + expect(buildSendElemsMock).not.toHaveBeenCalled(); + expect(sendRawPacket).not.toHaveBeenCalled(); + }); + it('private file forward keeps the long-msg upload under the self uid namespace', async () => { buildSendElemsMock.mockClear(); let captured: Uint8Array | undefined; diff --git a/packages/core/tests/actions/forward.test.ts b/packages/core/tests/actions/forward.test.ts index 0eec208c..df76dacc 100644 --- a/packages/core/tests/actions/forward.test.ts +++ b/packages/core/tests/actions/forward.test.ts @@ -51,7 +51,11 @@ function recvLongMsgResp(bodies: PushMsgBody[]) { action: [{ actionCommand: 'MultiMsg', actionData: { msgBody: bodies } }], }; const gz = gzipSync(Buffer.from(protobuf_encode(longMsg))); - const resp = protobuf_encode({ result: { payload: new Uint8Array(gz) } }); + return recvCompressedLongMsgResp(gz); +} + +function recvCompressedLongMsgResp(payload: Uint8Array) { + const resp = protobuf_encode({ result: { payload } }); return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.from(resp) }; } @@ -169,6 +173,21 @@ describe('actions/forward', () => { .rejects.toThrow(/download forward message failed|down/); }); + it('bounds long-message gunzip output and reports decompression context', async () => { + // This is one byte beyond the production 32 MiB ceiling but compresses to + // a small response, modelling an otherwise cheap gzip bomb from QQ. + const expandedBytes = (32 * 1024 * 1024) + 1; + const payload = gzipSync(Buffer.alloc(expandedBytes, 0x61)); + const resId = 'oversized-compressed-forward'; + const bridge = mockBridge({ + sendRawPacket: vi.fn(async () => recvCompressedLongMsgResp(payload)) as any, + }); + + await expect(new ForwardApi(bridge as any).fetch(resId)).rejects.toThrow( + /download forward message decompression failed .*res_id=oversized-compressed-forward.*max_output_bytes=33554432/, + ); + }); + it('uploadForwardNodes recursively uploads nested innerForward chains (NapCat piggyback model)', async () => { // Regression: nested forward needs the inner chain to be uploaded // first (so we have its res_id for the outer ARK preview), AND diff --git a/packages/core/tests/actions/group-admin.test.ts b/packages/core/tests/actions/group-admin.test.ts index c951f8e1..6d263ee0 100644 --- a/packages/core/tests/actions/group-admin.test.ts +++ b/packages/core/tests/actions/group-admin.test.ts @@ -143,12 +143,11 @@ describe('apis/group-admin', () => { expect(nameEnv.body).toMatchObject({ groupUin: 1, body: { targetName: 'newName' } }); const titleEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[2]![1]); - // expireTime is proto int_32 with -1 sentinel; after wire round-trip the - // proton decoder surfaces it as the unsigned reinterpretation (-1 ≡ 0xFFFFFFFF). + // expireTime is proto int_32 and preserves the signed -1 sentinel. expect(titleEnv.body?.groupUin).toBe(1); expect(titleEnv.body?.body?.targetUid).toBe('resolved-uid'); expect(titleEnv.body?.body?.specialTitle).toBe('newTitle'); - expect(titleEnv.body?.body?.expireTime).toBe(0xFFFFFFFF); + expect(titleEnv.body?.body?.expireTime).toBe(-1); const remarkEnv = protobuf_decode>(bridge.sendRawPacket.mock.calls[3]![1]); expect(remarkEnv.body?.inner).toMatchObject({ groupId: 1n, remark: 'newRemark' }); diff --git a/packages/core/tests/bridge-event-bus.test.ts b/packages/core/tests/bridge-event-bus.test.ts index 39c64bdd..6f381a8f 100644 --- a/packages/core/tests/bridge-event-bus.test.ts +++ b/packages/core/tests/bridge-event-bus.test.ts @@ -17,7 +17,7 @@ function makeFriendMessage(): FriendMessage { function makeGroupMessage(): GroupMessage { return { - kind: 'group_message', + kind: 'group_message', groupName: '', time: 1700000000, selfUin: 10001, groupId: 99999, diff --git a/packages/core/tests/bridge-manager-ownership.test.ts b/packages/core/tests/bridge-manager-ownership.test.ts new file mode 100644 index 00000000..9acc8b02 --- /dev/null +++ b/packages/core/tests/bridge-manager-ownership.test.ts @@ -0,0 +1,277 @@ +import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender'; +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { IdentityService } from '@snowluma/protocol/identity-service'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { BridgeManager } from '../src/bridge/manager'; + +const OK_RESULT: SendPacketResult = { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.alloc(0), +}; + +function makeSender() { + const sendPacket = vi.fn(async () => OK_RESULT); + return { + client: { sendPacket } satisfies PacketSender, + sendPacket, + }; +} + +function packet(pid: number, uin: string): PacketInfo { + return { + pid, + uin, + serviceCmd: 'Test.Unhandled', + seqId: 1, + retCode: 0, + fromClient: false, + body: Buffer.alloc(0), + }; +} + +describe('BridgeManager PID ownership', () => { + beforeEach(() => { + vi.spyOn(IdentityService, 'openForUin') + .mockImplementation((uin) => IdentityService.memory(uin)); + }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('detaches a PID from its old UIN before starting its replacement session', () => { + const manager = new BridgeManager(); + const first = makeSender(); + const second = makeSender(); + const lifecycle: string[] = []; + manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`)); + manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`)); + + manager.onHookLogin(101, '10001', first.client); + const oldBridge = manager.getSession('10001')!.bridge; + const dispose = vi.spyOn(oldBridge, 'dispose'); + + manager.onHookLogin(101, '20002', second.client); + + expect(lifecycle).toEqual([ + 'started:10001', + 'closed:10001', + 'started:20002', + ]); + expect(manager.getSession('10001')).toBeNull(); + expect(oldBridge.hasPid(101)).toBe(false); + expect(dispose).toHaveBeenCalledOnce(); + expect(manager.getSession('20002')!.bridge.hasPid(101)).toBe(true); + }); + + it('keeps a multi-PID UIN alive and falls back to the remaining sender', async () => { + const manager = new BridgeManager(); + const first = makeSender(); + const second = makeSender(); + const closed = vi.fn(); + manager.addSessionClosedListener(closed); + + manager.onHookLogin(101, '10001', first.client); + manager.onHookLogin(202, '10001', second.client); + const bridge = manager.getSession('10001')!.bridge; + + expect(bridge.activePid).toBe(202); + await bridge.sendRawPacket('Test.BeforeDisconnect', new Uint8Array([1])); + expect(second.sendPacket).toHaveBeenCalledOnce(); + expect(first.sendPacket).not.toHaveBeenCalled(); + + manager.onPidDisconnected(202); + + expect(manager.getSession('10001')!.bridge).toBe(bridge); + expect(bridge.activePid).toBe(101); + expect(closed).not.toHaveBeenCalled(); + await bridge.sendRawPacket('Test.AfterDisconnect', new Uint8Array([2])); + expect(first.sendPacket).toHaveBeenCalledOnce(); + expect(second.sendPacket).toHaveBeenCalledOnce(); + + manager.onPidDisconnected(101); + expect(manager.getSession('10001')).toBeNull(); + expect(closed).toHaveBeenCalledOnce(); + await expect(bridge.sendRawPacket('Test.NoSender', new Uint8Array([3]))) + .resolves.toMatchObject({ + success: false, + gotResponse: false, + errorCode: -1, + errorMessage: 'no packet sender attached', + }); + }); + + it('prefers the most recently rebound live PID, then falls back by recency', async () => { + const manager = new BridgeManager(); + const first = makeSender(); + const second = makeSender(); + const third = makeSender(); + const reboundFirst = makeSender(); + const started = vi.fn(); + manager.addSessionStartedListener(started); + + manager.onHookLogin(101, '10001', first.client); + manager.onHookLogin(202, '10001', second.client); + manager.onHookLogin(303, '10001', third.client); + manager.onHookLogin(101, '10001', reboundFirst.client); + const bridge = manager.getSession('10001')!.bridge; + + expect(started).toHaveBeenCalledOnce(); + expect(bridge.activePid).toBe(101); + await bridge.sendRawPacket('Test.Rebound', new Uint8Array([1])); + expect(reboundFirst.sendPacket).toHaveBeenCalledOnce(); + + manager.onPidDisconnected(101); + expect(bridge.activePid).toBe(303); + await bridge.sendRawPacket('Test.Fallback', new Uint8Array([2])); + expect(third.sendPacket).toHaveBeenCalledOnce(); + + manager.onPidDisconnected(303); + expect(bridge.activePid).toBe(202); + await bridge.sendRawPacket('Test.SecondFallback', new Uint8Array([3])); + expect(second.sendPacket).toHaveBeenCalledOnce(); + }); + + it('applies the same ownership transition when a packet reveals a new UIN', async () => { + const manager = new BridgeManager(); + const sender = makeSender(); + const lifecycle: string[] = []; + manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`)); + manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`)); + + manager.onHookLogin(101, '10001', sender.client); + manager.onPacket(packet(101, '20002')); + + expect(lifecycle).toEqual([ + 'started:10001', + 'closed:10001', + 'started:20002', + ]); + expect(manager.getSession('10001')).toBeNull(); + const replacement = manager.getSession('20002')!.bridge; + expect(replacement.hasPid(101)).toBe(true); + await replacement.sendRawPacket('Test.AfterPacketRebind', new Uint8Array([1])); + expect(sender.sendPacket).toHaveBeenCalledOnce(); + }); + + it('keeps the old UIN alive when its active PID moves and a fallback remains', async () => { + const manager = new BridgeManager(); + const fallback = makeSender(); + const moving = makeSender(); + const rebound = makeSender(); + const lifecycle: string[] = []; + manager.addSessionStartedListener((uin) => lifecycle.push(`started:${uin}`)); + manager.addSessionClosedListener((uin) => lifecycle.push(`closed:${uin}`)); + + manager.onHookLogin(101, '10001', fallback.client); + manager.onHookLogin(202, '10001', moving.client); + const oldBridge = manager.getSession('10001')!.bridge; + expect(oldBridge.activePid).toBe(202); + + manager.onHookLogin(202, '20002', rebound.client); + + expect(lifecycle).toEqual(['started:10001', 'started:20002']); + expect(manager.getSession('10001')!.bridge).toBe(oldBridge); + expect(oldBridge.hasPid(202)).toBe(false); + expect(oldBridge.activePid).toBe(101); + await oldBridge.sendRawPacket('Test.OldUinFallback', new Uint8Array([1])); + expect(fallback.sendPacket).toHaveBeenCalledOnce(); + + const newBridge = manager.getSession('20002')!.bridge; + expect(newBridge.activePid).toBe(202); + await newBridge.sendRawPacket('Test.NewUinSender', new Uint8Array([2])); + expect(rebound.sendPacket).toHaveBeenCalledOnce(); + + manager.onPidDisconnected(202); + expect(lifecycle).toEqual([ + 'started:10001', + 'started:20002', + 'closed:20002', + ]); + manager.onPidDisconnected(101); + expect(lifecycle).toEqual([ + 'started:10001', + 'started:20002', + 'closed:20002', + 'closed:10001', + ]); + }); + + it('does not emit another started edge when a PID joins an existing UIN', async () => { + const manager = new BridgeManager(); + const first = makeSender(); + const second = makeSender(); + const reboundFirst = makeSender(); + const started = vi.fn(); + const closed = vi.fn(); + manager.addSessionStartedListener(started); + manager.addSessionClosedListener(closed); + + manager.onHookLogin(101, '10001', first.client); + manager.onHookLogin(202, '20002', second.client); + const targetBridge = manager.getSession('20002')!.bridge; + + manager.onHookLogin(101, '20002', reboundFirst.client); + + expect(started).toHaveBeenCalledTimes(2); + expect(closed).toHaveBeenCalledOnce(); + expect(closed).toHaveBeenCalledWith('10001', expect.anything()); + expect(manager.getSession('10001')).toBeNull(); + expect(manager.getSession('20002')!.bridge).toBe(targetBridge); + expect(targetBridge.activePid).toBe(101); + + manager.onPidDisconnected(101); + expect(targetBridge.activePid).toBe(202); + await targetBridge.sendRawPacket('Test.ExistingTargetFallback', new Uint8Array([1])); + expect(second.sendPacket).toHaveBeenCalledOnce(); + expect(closed).toHaveBeenCalledOnce(); + + manager.onPidDisconnected(202); + expect(closed).toHaveBeenCalledTimes(2); + }); + + it('emits exactly one started/closed pair per real lifecycle', () => { + const manager = new BridgeManager(); + const sender = makeSender(); + const started = vi.fn(); + const closed = vi.fn(); + manager.addSessionStartedListener(started); + manager.addSessionClosedListener(closed); + + manager.onHookLogin(101, '10001', sender.client); + manager.onHookLogin(101, '10001', sender.client); + manager.onPacket(packet(101, '10001')); + manager.onPacket(packet(101, '10001')); + + expect(started).toHaveBeenCalledOnce(); + manager.onPidDisconnected(101); + manager.onPidDisconnected(101); + expect(closed).toHaveBeenCalledOnce(); + + manager.onHookLogin(101, '10001', sender.client); + manager.onPidDisconnected(101); + expect(started).toHaveBeenCalledTimes(2); + expect(closed).toHaveBeenCalledTimes(2); + }); + + it('fails fast when Manager ownership references a PID whose Bridge sender is missing', () => { + const manager = new BridgeManager(); + const sender = makeSender(); + manager.onHookLogin(101, '10001', sender.client); + + // Deliberately violate the private ownership invariant through Bridge's + // compatibility surface: Manager still maps PID 101 to this UIN, while + // Bridge no longer owns either the PID or its sender. + manager.getSession('10001')!.bridge.detachPid(101); + + expect(() => manager.onPacket(packet(101, '10001'))).toThrowError( + 'BridgeManager invariant violated: PID=101 has no sender in UIN=10001 session', + ); + expect(() => manager.onPidDisconnected(101)).toThrowError( + 'BridgeManager invariant violated: PID=101 is mapped to UIN=10001, but Bridge does not own the PID', + ); + }); +}); diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 9f78bc6f..3c992d13 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -28,6 +28,8 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({ })); import { buildSendElems } from '@snowluma/protocol/element-builder'; +import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; +import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload'; const fakeBridge = {} as any; @@ -131,6 +133,55 @@ describe('element-builder / commonElem.businessType per scene', () => { }); }); +describe('element-builder / all-message validation preflight', () => { + it('does not upload an early image when a later segment is unsendable', async () => { + vi.mocked(uploadImageMsgInfo).mockClear(); + + await expect(buildSendElems([ + { type: 'image', url: 'file:///tmp/valid-before-invalid.png' }, + { type: 'poke', subType: 1 }, + ] as any, { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'poke', + }); + + expect(uploadImageMsgInfo).not.toHaveBeenCalled(); + }); + + it('accepts a received imageUrl-only element for re-send', async () => { + vi.mocked(uploadImageMsgInfo).mockClear(); + await buildSendElems( + [{ type: 'image', imageUrl: 'https://gchat.qpic.cn/received.jpg' }], + { bridge: fakeBridge, groupId: 12345 }, + ); + expect(uploadImageMsgInfo).toHaveBeenCalledWith( + fakeBridge, + true, + 12345, + expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }), + ); + }); + + it('does not upload an early image when a later fast-only media element lacks hashes', async () => { + vi.mocked(uploadImageMsgInfo).mockClear(); + + await expect(buildSendElems([ + { type: 'image', url: 'file:///tmp/valid-before-invalid.png' }, + { + type: 'image', + url: 'file:///tmp/must-not-fallback.png', + noByteFallback: true, + }, + ] as any, { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({ + code: 'MISSING_FIELD', + elementType: 'image', + field: 'md5Hex', + }); + + expect(uploadImageMsgInfo).not.toHaveBeenCalled(); + }); +}); + describe('element-builder / file element is no longer carried in elems[]', () => { // Regression for the `result=79` class: previously the element-builder // emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments @@ -141,8 +192,8 @@ describe('element-builder / file element is no longer carried in elems[]', () => // segment is split off. The element-builder therefore must NOT emit // any element for `{type:'file'}` anymore — if it does, the message // ships with a transElem(24) payload and result=79 returns. - it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => { - const result = await buildSendElems( + it('fails fast when a live {type:"file"} reaches the element builder', async () => { + await expect(buildSendElems( [{ type: 'file', fileId: 'fid-abc', @@ -152,8 +203,11 @@ describe('element-builder / file element is no longer carried in elems[]', () => sha1Hex: '0102030405060708090a0b0c0d0e0f1011121314', } as any], { bridge: fakeBridge, groupId: 12345 }, - ); - expect(result).toEqual([]); + )).rejects.toMatchObject({ + name: 'MessageElementValidationError', + code: 'UNSENDABLE_TYPE', + elementType: 'file', + }); }); }); @@ -228,15 +282,10 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', () expect(JSON.parse(json.extra).tsum).toBe(3); }); - it('drops the forward element when resId is missing (preview unrenderable, fail open)', async () => { - // The dispatcher's `case 'forward': if (elem.resId) ...` short- - // circuits when resId is empty so a malformed segment from the - // OneBot client doesn't blow up the whole send. Receiver sees - // no forward bubble — same outcome as omitting the segment. - const out = await buildSendElems( + it('rejects a forward element when resId is missing', async () => { + await expect(buildSendElems( [{ type: 'forward' } as any], { bridge: fakeBridge, groupId: 12345 }, - ); - expect(out).toEqual([]); + )).rejects.toBeInstanceOf(MessageElementValidationError); }); }); diff --git a/packages/core/tests/group-history-walkback.test.ts b/packages/core/tests/group-history-walkback.test.ts index b98c1f79..97ff47a7 100644 --- a/packages/core/tests/group-history-walkback.test.ts +++ b/packages/core/tests/group-history-walkback.test.ts @@ -18,7 +18,7 @@ const mockFetch = vi.mocked(fetchGroupMessageRange); // eslint-disable-next-line @typescript-eslint/no-explicit-any function gm(seq: number): any { return { - kind: 'group_message', time: 0, selfUin: 0, senderUin: 1, msgSeq: seq, + kind: 'group_message', groupName: '', time: 0, selfUin: 0, senderUin: 1, msgSeq: seq, msgId: seq, elements: [], groupId: 9999, senderNick: '', senderCard: '', senderRole: '', }; } diff --git a/packages/core/tests/highway/highway-client.test.ts b/packages/core/tests/highway/highway-client.test.ts index e3b85043..f45a627d 100644 --- a/packages/core/tests/highway/highway-client.test.ts +++ b/packages/core/tests/highway/highway-client.test.ts @@ -1,23 +1,24 @@ // highway-client.uploadHighwayHttp 的连接生命周期测试。 // -// 回归覆盖:当上传数据 > HIGHWAY_BLOCK_SIZE (1 MiB) 时,旧实现会复用 -// 同一个 TCP socket 在 keep-alive 模式下连续 POST,但 QQ highway 的 -// 边缘节点经常在第一次响应后立刻 FIN 关闭,导致第二次 POST 报 -// `connection closed before response`。用户上报的 1.19 MB 图片 -// (onebot retcode=1200)就是这个分支。 +// 方案 3(#211):单连接、按 offset 顺序、流水线上传,跨 chunk 复用同一个 +// TCP 连接(HTTP keep-alive)。要点: +// - 顺序发送 → 天然保序,避开 QQ highway 对乱序块的 error_code=102902; +// - 复用连接 → TCP 拥塞窗口全程保持,省掉每块新建连接的 slow-start。 +// 边缘节点可能在响应后 FIN(#118);此时自适应地丢弃 socket + 重连 + 重发 +// 同一块(重发幂等),最坏退化成“每块一连接”,不比旧实现差,且仍然保序。 // -// 修复方案:每个 chunk 独立建一个新的 TCP 连接。本测试通过 mock -// `net.createConnection` 计数建连次数,断言每个 chunk 一连接的不变量。 +// 本测试用两种 mock 服务端行为锁定这套自适应逻辑: +// - keepalive:每个 POST 回一个响应,连接保持 → 整个文件 1 个连接; +// - closeafter:每个响应后半关闭(readableEnded/emit close)→ 退化成每块 +// 一连接,但仍全部成功。 -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { EventEmitter } from 'events'; // highway-client 解析响应只关心 errorCode === 0 —— 一个完全空的 -// RespDataHighwayHead protobuf 体(0 字节)会被解为 ,errorCode -// 是 undefined,走 falsy 通过分支。 -// -// HTTP body 是 highway frame: -// 0x28 | head_len(BE32) | body_len(BE32) | head | body | 0x29 +// RespDataHighwayHead protobuf 体(0 字节)会被解为 errorCode=undefined, +// 走 falsy 通过分支。 +// highway frame:0x28 | head_len(BE32) | body_len(BE32) | head | body | 0x29 function buildEmptyHighwayResponseFrame(): Buffer { const frame = Buffer.alloc(10); frame[0] = 0x28; @@ -27,59 +28,113 @@ function buildEmptyHighwayResponseFrame(): Buffer { return frame; } -function buildHttpResponse(frameBody: Buffer): Buffer { - const headers = [ - 'HTTP/1.1 200 OK', - `Content-Length: ${frameBody.length}`, - 'Connection: close', - '', - '', - ].join('\r\n'); - return Buffer.concat([Buffer.from(headers, 'ascii'), frameBody]); +// errorCode 帧:RespDataHighwayHead.field3 (errorCode) = 921。tag(field3, +// varint)=0x18,varint(921)=0x99 0x07。定义即拒绝(不重试)。 +function buildErrorCodeFrame(): Buffer { + const head = Buffer.from([0x18, 0x99, 0x07]); + const frame = Buffer.alloc(9 + head.length + 1); + frame[0] = 0x28; + frame.writeUInt32BE(head.length, 1); + frame.writeUInt32BE(0, 5); + head.copy(frame, 9); + frame[9 + head.length] = 0x29; + return frame; } -// FakeSocket 模拟 net.Socket 的最小子集。highway-client 用到: -// - 'data' / 'error' / 'close' 事件 -// - .write(data, cb) cb 会被 socketWrite 等待 -// - .destroy() -// - .setTimeout / .once / .removeListener (继承自 EventEmitter) +function httpWrap(frame: Buffer): Buffer { + const headers = ['HTTP/1.1 200 OK', `Content-Length: ${frame.length}`, '', ''].join('\r\n'); + return Buffer.concat([Buffer.from(headers, 'ascii'), frame]); +} + +type ServerMode = 'keepalive' | 'closeafter'; + +// FakeSocket 模拟 net.Socket 的最小子集,支持在一个连接上顺序处理多个 POST。 +// 累积写入的字节,按 `\r\n\r\n` + Content-Length 切出每个完整 POST,逐个回 +// 响应。`mode` 控制响应后是否半关闭;`failOnPost` 用于模拟链路中途断开。 class FakeSocket extends EventEmitter { destroyed = false; - // 每个 POST = 2 次 write(HTTP header + body)。第二次 write 落地后 - // 异步回放响应并立刻 close —— 复现 QQ highway 真实行为:响应一发完 - // 就 FIN,旧实现的下一次 POST 必然撞上已关闭的 socket。 - private writeCount = 0; - private response: Buffer; - - constructor(response: Buffer) { + readableEnded = false; + writable = true; + posts = 0; + private buf = Buffer.alloc(0); + constructor( + private readonly responseFrame: Buffer, + private readonly mode: ServerMode, + private readonly failOnPost = -1, + private readonly truncateOnPost = -1, + ) { super(); - this.response = response; } - setTimeout(_ms: number) { /* no-op */ } + setTimeout(_ms?: number) { /* no-op */ } - write(_data: unknown, cb?: (err?: Error) => void): boolean { - this.writeCount += 1; - if (this.writeCount === 2) { - setImmediate(() => { - this.emit('data', this.response); - this.emit('close'); - }); + write(data: unknown, cb?: (err?: Error) => void): boolean { + if (this.destroyed || !this.writable) { + const err = new Error('write after socket end'); + if (cb) cb(err); + setImmediate(() => this.emit('error', err)); + return false; } + this.buf = Buffer.concat([this.buf, Buffer.from(data as Uint8Array)]); + this.drainPosts(); if (cb) cb(); return true; } + private drainPosts(): void { + for (;;) { + const s = this.buf.toString('latin1'); + const he = s.indexOf('\r\n\r\n'); + if (he < 0) return; + const m = s.slice(0, he).match(/content-length:\s*(\d+)/i); + const cl = m ? parseInt(m[1], 10) : 0; + const total = he + 4 + cl; + if (this.buf.length < total) return; + this.buf = this.buf.subarray(total); + this.posts += 1; + const thisPost = this.posts; + setImmediate(() => { + if (this.destroyed) return; + if (thisPost === this.failOnPost) { + this.writable = false; + this.readableEnded = true; + this.emit('error', new Error('ECONNRESET')); + this.emit('close'); + return; + } + if (thisPost === this.truncateOnPost) { + // Send the HTTP header + only part of the declared body, then FIN — + // a truncated response. Dropping the last 3 body bytes keeps the + // header intact so Content-Length parses but is never satisfied. + const full = httpWrap(this.responseFrame); + this.emit('data', full.subarray(0, full.length - 3)); + this.writable = false; + this.readableEnded = true; + this.emit('close'); + return; + } + this.emit('data', httpWrap(this.responseFrame)); + if (this.mode === 'closeafter') { + this.readableEnded = true; + this.writable = false; + this.emit('end'); + this.emit('close'); + } + }); + } + } + destroy() { this.destroyed = true; + this.writable = false; } } -// vitest 把 vi.mock 工厂 hoist 到文件顶部,所以工厂里不能引用普通的 -// 顶层 const —— 那会触发 "Cannot access X before initialization"。 -// 用 vi.hoisted 让这两个值跟着 mock 一起被 hoist。 -const { createdSockets, createConnectionMock } = vi.hoisted(() => ({ - createdSockets: [] as FakeSocket[], +// vitest 把 vi.mock 工厂 hoist 到文件顶部,所以工厂里不能引用普通的顶层 +// const。用 vi.hoisted 让这些值跟着 mock 一起 hoist。 +const { createdSockets, socketFactoryRef, createConnectionMock } = vi.hoisted(() => ({ + createdSockets: [] as unknown[], + socketFactoryRef: { make: null as null | ((idx: number) => unknown) }, createConnectionMock: vi.fn(), })); @@ -88,15 +143,18 @@ vi.mock('net', () => ({ createConnection: createConnectionMock, })); -import { uploadHighwayHttp, BufferChunkSource, type HighwaySession } from '@snowluma/protocol/highway'; +import { + uploadHighwayHttp, + BufferChunkSource, + type ChunkSource, + type HighwaySession, +} from '@snowluma/protocol/highway'; import type { BridgeContext } from '@snowluma/protocol/bridge-context'; const HIGHWAY_BLOCK_SIZE = 1024 * 1024; function makeBridge(): BridgeContext { - return { - identity: { uin: '10001' } as unknown, - } as unknown as BridgeContext; + return { identity: { uin: '10001' } as unknown } as unknown as BridgeContext; } function makeSession(): HighwaySession { @@ -108,61 +166,141 @@ function makeSession(): HighwaySession { }; } -describe('uploadHighwayHttp connection lifecycle', () => { - beforeEach(() => { - createdSockets.length = 0; - createConnectionMock.mockReset(); - createConnectionMock.mockImplementation((_opts: unknown, listener?: () => void) => { - const sock = new FakeSocket(buildHttpResponse(buildEmptyHighwayResponseFrame())); - createdSockets.push(sock); - // net.createConnection 在握手成功后调用 listener。同步触发即可, - // tcpConnect 的 Promise 会立刻 resolve。 - if (listener) setImmediate(listener); - return sock as unknown as ReturnType; - }); +// 安装一个 socket 工厂:createConnection 每次调用按序号创建一个 FakeSocket。 +function installFactory(make: (idx: number) => FakeSocket): void { + createdSockets.length = 0; + socketFactoryRef.make = make as (idx: number) => unknown; + createConnectionMock.mockReset(); + createConnectionMock.mockImplementation((_opts: unknown, listener?: () => void) => { + const idx = createdSockets.length; + const sock = socketFactoryRef.make!(idx) as FakeSocket; + createdSockets.push(sock); + if (listener) setImmediate(listener); // 握手成功后异步回调 → tcpConnect resolve + return sock as unknown as ReturnType; + }); +} + +// 顺序读取记录:offset/length + 关闭时机,用于数据完整性与 close 语义。 +class RecordingChunkSource implements ChunkSource { + reads: Array<{ offset: number; length: number }> = []; + inFlight = 0; + closeCount = 0; + closedWhileReading = false; + constructor(readonly size: number) {} + async read(offset: number, length: number): Promise { + this.inFlight += 1; + this.reads.push({ offset, length }); + await Promise.resolve(); + this.inFlight -= 1; + return new Uint8Array(length); + } + async close(): Promise { + if (this.inFlight > 0) this.closedWhileReading = true; + this.closeCount += 1; + } +} + +describe('uploadHighwayHttp single-connection pipelined upload (#211)', () => { + afterEach(() => vi.restoreAllMocks()); + + it('reuses ONE connection for a multi-block payload when keep-alive holds', async () => { + installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks + await uploadHighwayHttp( + makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), + ); + // The whole file went over a single warm connection — the #211 win. + expect(createConnectionMock).toHaveBeenCalledTimes(1); }); - afterEach(() => { - vi.restoreAllMocks(); - }); - - it('uses a single TCP connection for a sub-block payload', async () => { - // 0.5 MiB → 1 chunk。覆盖 PTT / 小图的常见场景。 - const bytes = new Uint8Array(512 * 1024); + it('single sub-block payload uses one connection', async () => { + installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const bytes = new Uint8Array(512 * 1024); // 1 block (PTT / small image) await uploadHighwayHttp( makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), ); expect(createConnectionMock).toHaveBeenCalledTimes(1); - expect(createdSockets[0]!.destroyed).toBe(true); - }); - - it('uses a fresh TCP connection per chunk for multi-block payloads', async () => { - // 1.5 MiB → ceil(1.5) = 2 chunks。这正是用户上报的 1.19 MB 图片 - // 触发的代码路径:旧实现复用 socket 时第二次 POST 撞上 keep-alive - // 关闭,新实现必须为每个 chunk 各开一个 socket。 - const bytes = new Uint8Array(Math.floor(1.5 * HIGHWAY_BLOCK_SIZE)); - await uploadHighwayHttp( - makeBridge(), makeSession(), 1003, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), - ); - expect(createConnectionMock).toHaveBeenCalledTimes(2); - expect(createdSockets).toHaveLength(2); - for (const sock of createdSockets) { - expect(sock.destroyed).toBe(true); - } - }); - - it('opens N connections for N chunks (3 chunks here)', async () => { - const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); - await uploadHighwayHttp( - makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), - ); - expect(createConnectionMock).toHaveBeenCalledTimes(3); }); it('a zero-length source opens ZERO connections (empty-input invariant)', async () => { + installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); await uploadHighwayHttp( makeBridge(), makeSession(), 1003, new BufferChunkSource(new Uint8Array(0)), new Uint8Array(16), new Uint8Array(0), ); expect(createConnectionMock).not.toHaveBeenCalled(); }); + + it('degrades to one connection per block when the server FINs after every response (#118 regime)', async () => { + installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'closeafter')); + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks + await uploadHighwayHttp( + makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), + ); + // Server closes after each response → adaptively reconnects per block, but + // the upload still completes. No worse than the old one-conn-per-chunk. + expect(createConnectionMock).toHaveBeenCalledTimes(3); + }); + + it('reconnects and re-sends the SAME block on a mid-stream transport error', async () => { + // First connection dies while handling its first POST; a fresh connection + // must re-send that same block (offset unchanged, idempotent) and finish. + installFactory((idx) => + idx === 0 + ? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', /* failOnPost */ 1) + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'), + ); + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks + await uploadHighwayHttp( + makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), + ); + // Connection #0 failed on block 0 → reconnect (#1) resumes and keep-alives + // the rest: exactly two connections total. + expect(createConnectionMock).toHaveBeenCalledTimes(2); + }); + + it('reconnects and re-sends the block when a response body is truncated mid-stream', async () => { + // Peer FINs after the HTTP header but before the highway body is complete. + // That truncation must be treated as a retryable transport failure (reject + // in readHttpResponseBody), NOT resolved as a partial frame — otherwise + // unpackHighwayFrame throws OUTSIDE the retry loop and fails the upload. + installFactory((idx) => + idx === 0 + ? new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive', -1, /* truncateOnPost */ 1) + : new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive'), + ); + const bytes = new Uint8Array(Math.floor(2.5 * HIGHWAY_BLOCK_SIZE)); // 3 blocks + await uploadHighwayHttp( + makeBridge(), makeSession(), 1004, new BufferChunkSource(bytes), new Uint8Array(16), new Uint8Array(0), + ); + // conn #0 truncated block 0 → reconnect (#1) re-sends it and finishes. + expect(createConnectionMock).toHaveBeenCalledTimes(2); + }); + + it('reads every offset exactly once, in order, and closes the source once (data safety)', async () => { + installFactory(() => new FakeSocket(buildEmptyHighwayResponseFrame(), 'keepalive')); + const size = 4 * HIGHWAY_BLOCK_SIZE + 4321; // 4 full + 1 ragged + const source = new RecordingChunkSource(size); + await uploadHighwayHttp( + makeBridge(), makeSession(), 1004, source, new Uint8Array(16), new Uint8Array(0), + ); + const offsets = source.reads.map((r) => r.offset); + // Strictly increasing, gap-free, exactly-once coverage of [0, size). + expect(offsets).toEqual([0, HIGHWAY_BLOCK_SIZE, 2 * HIGHWAY_BLOCK_SIZE, 3 * HIGHWAY_BLOCK_SIZE, 4 * HIGHWAY_BLOCK_SIZE]); + expect(source.reads[source.reads.length - 1]!.length).toBe(4321); // ragged tail + expect(source.reads.reduce((n, r) => n + r.length, 0)).toBe(size); + expect(source.closeCount).toBe(1); + expect(source.closedWhileReading).toBe(false); + }); + + it('rejects on a definitive server error_code and closes the source once (no retry)', async () => { + installFactory(() => new FakeSocket(buildErrorCodeFrame(), 'keepalive')); + const source = new RecordingChunkSource(3 * HIGHWAY_BLOCK_SIZE); + await expect(uploadHighwayHttp( + makeBridge(), makeSession(), 1004, source, new Uint8Array(16), new Uint8Array(0), + )).rejects.toThrow(/error_code=921/); + expect(source.closeCount).toBe(1); + expect(source.closedWhileReading).toBe(false); + // Definitive reject on block 0 → stop immediately, don't PUT later blocks. + expect(source.reads.length).toBeLessThan(3); + }); }); diff --git a/packages/core/tests/highway/image-upload.test.ts b/packages/core/tests/highway/image-upload.test.ts index 82bb36fa..68d1ef69 100644 --- a/packages/core/tests/highway/image-upload.test.ts +++ b/packages/core/tests/highway/image-upload.test.ts @@ -23,6 +23,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({ })); import * as pipeline from '@snowluma/protocol/highway/pipeline'; +import * as utils from '@snowluma/protocol/highway/utils'; import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload'; import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/protocol/highway'; @@ -30,6 +31,7 @@ describe('image-upload', () => { beforeEach(() => { vi.mocked(pipeline.runNtv2Upload).mockClear(); vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear(); + vi.mocked(utils.loadBinarySource).mockClear(); }); it('group: uses 0x11C4_100 + GROUP_IMAGE_CMD_ID and tags scene as group', async () => { @@ -58,6 +60,19 @@ describe('image-upload', () => { expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined(); }); + it('uses receive-side imageUrl when url/fileId are absent', async () => { + await uploadImageMsgInfo( + {} as any, + true, + 12345, + { type: 'image', imageUrl: 'https://gchat.qpic.cn/received.jpg' }, + ); + expect(utils.loadBinarySource).toHaveBeenCalledWith( + 'https://gchat.qpic.cn/received.jpg', + 'image', + ); + }); + it('encodes the detected picFormat and image dimensions into fileInfo', async () => { await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x' } as any); const fileInfo = (vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo[0] as any).fileInfo; diff --git a/packages/core/tests/identity-service.test.ts b/packages/core/tests/identity-service.test.ts index a1ee2ac9..0c15b296 100644 --- a/packages/core/tests/identity-service.test.ts +++ b/packages/core/tests/identity-service.test.ts @@ -1,6 +1,8 @@ import { afterEach, describe, expect, it, vi } from 'vitest'; import fs from 'fs'; +import { DatabaseSync } from 'node:sqlite'; import path from 'path'; +import { subscribeLogs } from '@snowluma/common/logger'; import { IdentityService } from '@snowluma/protocol/identity-service'; import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info'; @@ -25,6 +27,19 @@ function cleanupDb(dbPath: string): void { } } +function holdWriteLock(dbPath: string): () => void { + const locker = new DatabaseSync(dbPath); + locker.exec('PRAGMA busy_timeout = 0'); + locker.exec('BEGIN IMMEDIATE'); + let released = false; + return () => { + if (released) return; + released = true; + locker.exec('ROLLBACK'); + locker.close(); + }; +} + function makeGroup(): QQGroupInfo { return { groupId: GROUP_ID, @@ -52,6 +67,7 @@ function makeMember(uin: number, uid: string, card = ''): GroupMemberInfo { } afterEach(() => { + vi.useRealTimers(); for (const dbPath of dbs.splice(0)) cleanupDb(dbPath); }); @@ -80,6 +96,540 @@ describe('IdentityService', () => { } }); + it('keeps updateGroupMember changes after reopening the persistent cache', () => { + const dbPath = tempDbPath('update-member'); + const member = makeMember(33333, 'u_member', 'old-card'); + + { + const identity = new IdentityService(SELF_UIN, dbPath); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMembers(GROUP_ID, [member]); + identity.updateGroupMember(GROUP_ID, { ...member, card: 'new-card' }); + + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('new-card'); + identity.close(); + } + + { + const identity = new IdentityService(SELF_UIN, dbPath); + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('new-card'); + identity.close(); + } + }); + + it('persists an explicitly cleared member card instead of restoring the old value', () => { + const dbPath = tempDbPath('clear-member-card'); + const member = makeMember(33333, 'u_member', 'old-card'); + + { + const identity = new IdentityService(SELF_UIN, dbPath); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMembers(GROUP_ID, [member]); + identity.updateGroupMember(GROUP_ID, { ...member, card: '' }); + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe(''); + identity.close(); + } + + { + const identity = new IdentityService(SELF_UIN, dbPath); + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe(''); + identity.close(); + } + }); + + it('keeps a failed observation in memory, reports degraded, and retries to healthy', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('retry-recovery'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + let closed = false; + + try { + identity.rememberFriends([{ + uin: 22222, + uid: 'u_retry', + nickname: 'retry-friend', + remark: '', + }]); + + expect(identity.findFriend(22222)?.uid).toBe('u_retry'); + expect(identity.persistenceStatus).toMatchObject({ + state: 'degraded', + pendingWrites: 1, + lastFailedLabel: 'friends', + retryAttempt: 1, + }); + expect(identity.persistenceStatus.lastError).toMatch(/locked/i); + expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(100); + + await vi.advanceTimersByTimeAsync(100); + expect(identity.persistenceStatus).toMatchObject({ + state: 'degraded', + pendingWrites: 1, + retryAttempt: 2, + }); + expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(500); + + releaseLock(); + await vi.advanceTimersByTimeAsync(500); + + expect(identity.persistenceStatus).toMatchObject({ + state: 'healthy', + pendingWrites: 0, + retryAttempt: 0, + nextRetryAt: null, + }); + identity.close(); + closed = true; + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findFriend(22222)?.uid).toBe('u_retry'); + reopened.close(); + } finally { + releaseLock(); + if (!closed) identity.close(); + } + }); + + it('replays pending observations in their original order', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('retry-order'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + let closed = false; + + try { + identity.rememberFriends([{ + uin: 11111, + uid: 'u_first', + nickname: 'first', + remark: '', + }]); + identity.rememberFriends([{ + uin: 22222, + uid: 'u_second', + nickname: 'second', + remark: '', + }]); + + expect(identity.persistenceStatus.pendingWrites).toBe(2); + expect(identity.findFriend(11111)).toBeNull(); + expect(identity.findFriend(22222)?.uid).toBe('u_second'); + + releaseLock(); + await vi.runOnlyPendingTimersAsync(); + identity.close(); + closed = true; + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findFriend(11111)).toBeNull(); + expect(reopened.findFriend(22222)?.uid).toBe('u_second'); + reopened.close(); + } finally { + releaseLock(); + if (!closed) identity.close(); + } + }); + + it('replays the snapshot accepted at observation time when caller input later mutates', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('retry-snapshot'); + const identity = new IdentityService(SELF_UIN, dbPath); + const member = makeMember(33333, 'u_member', 'before'); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMembers(GROUP_ID, [member]); + const releaseLock = holdWriteLock(dbPath); + const observed = { ...member, card: 'accepted' }; + + try { + identity.updateGroupMember(GROUP_ID, observed); + observed.card = 'caller-mutated'; + + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted'); + releaseLock(); + await vi.runOnlyPendingTimersAsync(); + identity.close(); + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findGroupMember(GROUP_ID, member.uin)?.card).toBe('accepted'); + reopened.close(); + } finally { + releaseLock(); + identity.close(); + } + }); + + it('does not let a group refresh restore stale SQLite members over a pending member update', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('pending-member-group-refresh'); + const identity = new IdentityService(SELF_UIN, dbPath); + const member = makeMember(33333, 'u_member', 'persisted-card'); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMembers(GROUP_ID, [member]); + const releaseLock = holdWriteLock(dbPath); + + try { + identity.updateGroupMember(GROUP_ID, { ...member, card: 'pending-card' }); + identity.rememberGroups([{ ...makeGroup(), groupName: 'refreshed-group' }]); + + expect(identity.findGroup(GROUP_ID)?.groupName).toBe('refreshed-group'); + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('pending-card'); + + releaseLock(); + await vi.runOnlyPendingTimersAsync(); + identity.close(); + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findGroup(GROUP_ID)?.groupName).toBe('refreshed-group'); + expect(reopened.findGroupMember(GROUP_ID, member.uin)?.card).toBe('pending-card'); + reopened.close(); + } finally { + releaseLock(); + identity.close(); + } + }); + + it('rejects stale SQLite fallbacks after pending UID and UIN rebinds', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('pending-rebind'); + const identity = new IdentityService(SELF_UIN, dbPath); + identity.rememberRequestIdentity({ uid: 'u_old_for_uin', uin: 22001 }); + identity.rememberRequestIdentity({ uid: 'u_stable', uin: 22002 }); + const releaseLock = holdWriteLock(dbPath); + + try { + identity.rememberRequestIdentity({ uid: 'u_new_for_uin', uin: 22001 }); + identity.rememberRequestIdentity({ uid: 'u_stable', uin: 22999 }); + + expect(identity.findUidByUin(22001)).toBe('u_new_for_uin'); + expect(identity.findUinByUid('u_stable')).toBe(22999); + expect(identity.findUinByUid('u_old_for_uin')).toBeNull(); + expect(identity.findUidByUin(22002)).toBeNull(); + + releaseLock(); + await vi.runOnlyPendingTimersAsync(); + identity.close(); + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findUidByUin(22001)).toBe('u_new_for_uin'); + expect(reopened.findUinByUid('u_stable')).toBe(22999); + reopened.close(); + } finally { + releaseLock(); + identity.close(); + } + }); + + it('fails fast before accepting an observation when the retry queue is full', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('retry-capacity'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + + try { + const capacity = identity.persistenceStatus.queueCapacity; + expect(capacity).toBeGreaterThan(0); + + for (let i = 0; i < capacity; i += 1) { + identity.rememberRequestIdentity({ + uid: `u_pending_${i}`, + uin: 100_000 + i, + source: 'capacity-test', + }); + } + expect(identity.persistenceStatus.pendingWrites).toBe(capacity); + + expect(() => identity.rememberRequestIdentity({ + uid: 'u_overflow', + uin: 999_999, + source: 'capacity-test', + })).toThrow(/persistence retry queue full/i); + + expect(identity.findUinByUid('u_overflow')).toBeNull(); + expect(identity.persistenceStatus).toMatchObject({ + state: 'degraded', + pendingWrites: capacity, + lastFailedLabel: 'request identity', + }); + expect(identity.persistenceStatus.lastError).toMatch(/queue full/i); + } finally { + releaseLock(); + await vi.runOnlyPendingTimersAsync(); + identity.close(); + } + }); + + it('suspends SQLite persistence after five failed retries and only recovers after restart', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('retry-exhausted'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + const seen: Array<{ level: string; message: string }> = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'Identity' && entry.uin === Number(SELF_UIN)) seen.push(entry); + }); + + try { + identity.rememberFriends([{ + uin: 22222, + uid: 'u_abandoned_friend', + nickname: 'abandoned', + remark: '', + }]); + identity.rememberRequestIdentity({ uid: 'u_abandoned_request', uin: 33333 }); + + for (const delay of [100, 500, 2_000, 10_000, 30_000]) { + await vi.advanceTimersByTimeAsync(delay); + } + + expect(identity.persistenceStatus).toMatchObject({ + state: 'degraded', + suspended: true, + pendingWrites: 0, + retryAttempt: 6, + nextRetryAt: null, + abandonedWrites: 2, + skippedWrites: 0, + }); + expect(vi.getTimerCount()).toBe(0); + expect(seen).toContainEqual(expect.objectContaining({ + level: 'error', + message: expect.stringMatching( + /persistence suspended.*uin=10001.*label=friends.*pending=2.*retry=6.*abandoned=2/i, + ), + })); + const suspendedFailureAt = identity.persistenceStatus.lastFailureAt; + await vi.advanceTimersByTimeAsync(1); + + expect(() => identity.rememberRequestIdentity({ + uid: 'u_skipped_after_suspend', + uin: 44444, + })).not.toThrow(); + expect(identity.findUinByUid('u_skipped_after_suspend')).toBe(44444); + expect(identity.persistenceStatus).toMatchObject({ + state: 'degraded', + suspended: true, + pendingWrites: 0, + abandonedWrites: 3, + skippedWrites: 1, + lastFailedLabel: 'friends', + lastError: expect.stringMatching(/locked/i), + lastFailureAt: suspendedFailureAt, + }); + + releaseLock(); + identity.close(); + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.persistenceStatus).toMatchObject({ + state: 'healthy', + suspended: false, + abandonedWrites: 0, + skippedWrites: 0, + }); + expect(reopened.findUinByUid('u_abandoned_request')).toBeNull(); + expect(reopened.findUinByUid('u_skipped_after_suspend')).toBeNull(); + reopened.rememberRequestIdentity({ uid: 'u_after_restart', uin: 55555 }); + reopened.close(); + + const persisted = new IdentityService(SELF_UIN, dbPath); + expect(persisted.findUinByUid('u_after_restart')).toBe(55555); + persisted.close(); + } finally { + unsubscribe(); + releaseLock(); + identity.close(); + } + }); + + it('flushes pending writes synchronously during close when SQLite has recovered', () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('close-flush'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + + identity.rememberFriends([{ + uin: 22222, + uid: 'u_close_flush', + nickname: 'close-flush', + remark: '', + }]); + expect(identity.persistenceStatus.pendingWrites).toBe(1); + + releaseLock(); + identity.close(); + + expect(identity.persistenceStatus).toMatchObject({ + state: 'closed', + pendingWrites: 0, + abandonedWrites: 0, + nextRetryAt: null, + }); + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findFriend(22222)?.uid).toBe('u_close_flush'); + reopened.close(); + }); + + it('warns and releases pending retry work when close cannot flush SQLite', () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('close-pending'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + const seen: Array<{ level: string; message: string }> = []; + const unsubscribe = subscribeLogs((entry) => { + if (entry.scope === 'Identity' && entry.uin === Number(SELF_UIN)) seen.push(entry); + }); + + try { + identity.rememberFriends([{ + uin: 22222, + uid: 'u_close_pending', + nickname: 'close-pending', + remark: '', + }]); + expect(identity.persistenceStatus.pendingWrites).toBe(1); + + identity.close(); + + expect(identity.persistenceStatus).toMatchObject({ + state: 'closed', + pendingWrites: 0, + abandonedWrites: 1, + lastFailedLabel: 'friends', + nextRetryAt: null, + }); + expect(vi.getTimerCount()).toBe(0); + expect(seen).toContainEqual(expect.objectContaining({ + level: 'warn', + message: expect.stringMatching(/close with pending writes.*uin=10001.*label=friends.*pending=1/i), + })); + } finally { + unsubscribe(); + releaseLock(); + identity.close(); + } + }); + + it('stays open and preserves pending writes when SQLite close throws', async () => { + vi.useFakeTimers(); + const dbPath = tempDbPath('close-failure'); + const identity = new IdentityService(SELF_UIN, dbPath); + const releaseLock = holdWriteLock(dbPath); + const database = (identity as unknown as { db: DatabaseSync }).db; + const closeSpy = vi.spyOn(database, 'close').mockImplementationOnce(() => { + throw new Error('injected close failure'); + }); + + try { + identity.rememberFriends([{ + uin: 22222, + uid: 'u_close_retry_friend', + nickname: 'close-retry', + remark: '', + }]); + expect(identity.persistenceStatus.pendingWrites).toBe(1); + + expect(() => identity.close()).toThrow(/injected close failure/); + expect(identity.persistenceStatus).toMatchObject({ + state: 'degraded', + pendingWrites: 1, + abandonedWrites: 0, + retryAttempt: 2, + }); + expect(vi.getTimerCount()).toBe(1); + expect(identity.persistenceStatus.nextRetryAt! - Date.now()).toBe(500); + + expect(() => identity.rememberRequestIdentity({ + uid: 'u_after_close_failure', + uin: 33333, + })).not.toThrow(); + expect(identity.persistenceStatus.pendingWrites).toBe(2); + + closeSpy.mockRestore(); + releaseLock(); + await vi.runOnlyPendingTimersAsync(); + expect(identity.persistenceStatus).toMatchObject({ + state: 'healthy', + pendingWrites: 0, + }); + identity.close(); + + const reopened = new IdentityService(SELF_UIN, dbPath); + expect(reopened.findFriend(22222)?.uid).toBe('u_close_retry_friend'); + expect(reopened.findUinByUid('u_after_close_failure')).toBe(33333); + reopened.close(); + } finally { + closeSpy.mockRestore(); + releaseLock(); + identity.close(); + } + }); + + it('fails fast on every observation entry point after close', () => { + const identity = IdentityService.memory(SELF_UIN); + const member = makeMember(33333, 'u_member', 'before-close'); + identity.rememberGroups([makeGroup()]); + identity.rememberGroupMembers(GROUP_ID, [member]); + identity.close(); + + const profile: UserProfileInfo = { + uin: 44444, + uid: 'u_profile', + nickname: 'profile', + remark: '', + qid: '', + sex: 'unknown', + age: 0, + sign: '', + avatar: '', + level: 0, + }; + const request = { + groupId: GROUP_ID, + groupName: 'group', + targetUid: 'u_target', + targetUin: 55555, + targetName: 'target', + invitorUid: 'u_invitor', + invitorUin: 66666, + invitorName: 'invitor', + operatorUid: 'u_operator', + operatorUin: 77777, + operatorName: 'operator', + sequence: 1, + state: 0, + eventType: 1, + comment: '', + filtered: false, + }; + const observations: Array<[string, () => void]> = [ + ['nickname', () => { identity.nickname = 'after-close'; }], + ['self profile', () => identity.setSelfProfile(profile)], + ['group member update', () => identity.updateGroupMember(GROUP_ID, { ...member, card: 'after-close' })], + ['friends', () => identity.rememberFriends([{ uin: 22222, uid: 'u_friend', nickname: '', remark: '' }])], + ['groups', () => identity.rememberGroups([])], + ['forget group', () => identity.forgetGroup(GROUP_ID)], + ['group members', () => identity.rememberGroupMembers(GROUP_ID, [])], + ['user profile', () => identity.rememberUserProfile(profile)], + ['group invite sequence', () => identity.rememberGroupInviteCardSequence(GROUP_ID, 123)], + ['group requests', () => identity.rememberGroupRequests([request])], + ['request identity', () => identity.rememberRequestIdentity({ uid: 'u_request', uin: 88888 })], + ['group member identity', () => identity.rememberGroupMemberIdentity(GROUP_ID, { uid: 'u_new', uin: 99999 })], + ['group member inactive', () => identity.markGroupMemberInactive(GROUP_ID, { uid: member.uid, uin: member.uin })], + ]; + + for (const [label, observe] of observations) { + expect(observe, label).toThrow(/IdentityService is closed/); + } + + expect(identity.nickname).toBe(''); + expect(identity.findGroup(GROUP_ID)).not.toBeNull(); + expect(identity.findGroupMember(GROUP_ID, member.uin)?.card).toBe('before-close'); + expect(identity.findFriend(22222)).toBeNull(); + expect(identity.findUinByUid('u_request')).toBeNull(); + }); + it('marks missing members inactive only after a successful full refresh', () => { const dbPath = tempDbPath('inactive-refresh'); const first = makeMember(33333, 'u_first'); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 91fcda6c..92bea428 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -23,7 +23,7 @@ Add to your MCP client (Claude Desktop, Cline, …) — no endpoint, no executio ### Docs tools -- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly`). +- `list_actions({ category? })` — lightweight index (name / category / summary / aliases / `readOnly` / `stream`). - `get_action({ name })` — full doc for one action incl. `inputSchema` and `readOnly` (accepts aliases). - `search_actions({ query })` — fuzzy match over name / summary / aliases. - `list_categories()` — categories and their action counts. @@ -38,12 +38,15 @@ Point the server at a running SnowLuma instance's **OneBot HTTP endpoint** (the - `query_action({ action, params? })` — calls a **read-only** action (e.g. `get_*`, `can_*`) and returns the full OneBot response. Annotated `readOnlyHint`. Refuses write actions (points you to `invoke_action`). -- `invoke_action({ action, params? })` — calls **any known** action, including ones +- `invoke_action({ action, params?, execution? })` — calls **any known** action, including ones with side effects (send a message, change a group, …). Annotated `destructiveHint` - + `openWorldHint`. **Only available in write mode.** + + `openWorldHint`. **Only available in write mode.** For automatic local-file + upload, pass `execution: { input_file: "/path/on/the/mcp/host" }` with + `action: "upload_file_stream"`; this option is never forwarded as OneBot params. -Both pass the OneBot envelope through verbatim — a logical failure (`retcode≠0`) -comes back as data with its `wording`; only a transport failure is an error. +Ordinary actions pass the OneBot envelope through verbatim — a logical failure +(`retcode≠0`) comes back as data with its `wording`. Stream protocol failures are +reported as MCP errors because they mean no complete stream result was committed. ### Configuration (env) @@ -51,8 +54,11 @@ comes back as data with its `wording`; only a transport failure is an error. | --- | --- | | `SNOWLUMA_MCP_ENDPOINT` | OneBot HTTP endpoint, e.g. `http://127.0.0.1:3000/`. **Absent → docs-only** (execution tools hidden). | | `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. | -| `SNOWLUMA_MCP_TIMEOUT_MS` | Per-request timeout (default `30000`). | -| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. | +| `SNOWLUMA_MCP_TIMEOUT_MS` | Ordinary-action request timeout; for Stream Actions, connection timeout **and per-read idle timeout** (the idle deadline resets after every body read). Default `30000`. Invalid values fail startup. | +| `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. Invalid values fail startup. | +| `SNOWLUMA_MCP_STREAM_DIR` | Directory on the MCP host for completed Stream Action downloads. Created and validated at startup. Default: `os.tmpdir()/snowluma-mcp/downloads`. | +| `SNOWLUMA_MCP_UPLOAD_ROOT` | Existing directory on the MCP host from which automatic uploads may read. Automatic upload is disabled when absent. | +| `SNOWLUMA_MCP_MAX_STREAM_BYTES` | Per-file download/upload ceiling in bytes. Positive integer up to 4 GiB; default `4294967296`. Invalid values fail server startup. | **Read mode** — the LLM can query read-only actions, but cannot perform any write: @@ -83,13 +89,62 @@ groups, etc.). Enable deliberately: "env": { "SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/", "SNOWLUMA_MCP_TOKEN": "your-access-token", - "SNOWLUMA_MCP_MODE": "write" + "SNOWLUMA_MCP_MODE": "write", + "SNOWLUMA_MCP_STREAM_DIR": "/var/tmp/snowluma-mcp-downloads", + "SNOWLUMA_MCP_UPLOAD_ROOT": "/home/me/mcp-share" } } } } ``` +### Stream Actions + +The existing `query_action` / `invoke_action` tools automatically select the +ordinary or Stream Action HTTP transport from the generated catalog. No separate +MCP tool is needed. + +- File downloads (`download_file_stream`, `download_file_image_stream`, and + `download_file_record_stream`) are parsed frame-by-frame. Base64 chunks are + decoded directly into a randomly named `.part` file under the controlled + download directory, hashed incrementally, and atomically renamed only after a + valid `file_complete` terminal frame. The MCP result contains only + `file_path`, `file_size`, `sha256`, `frame_count`, and `terminal`; the file path + is on the **MCP host**. +- A client admits at most four top-level active Stream Actions. Download files + share a directory quota of `2 * SNOWLUMA_MCP_MAX_STREAM_BYTES`; an unknown-size + download reserves the full per-file limit while active. Successfully committed + files are **not automatically deleted** by MCP and continue consuming quota; + the operator must move or delete them when no longer needed. +- Non-file streams such as `test_download_stream` return a bounded frame summary. + Frame count, summary text, individual wire-frame size, total file bytes, and + file chunk count are capped. A malformed frame, disconnect, timeout, size + violation, caller cancellation, idle timeout, or invalid terminal cancels the + response and removes the partial file. `file_chunk` / `file_complete` frames + are never admitted without a preceding `file_info` header. +- Automatic upload reads `execution.input_file` only after resolving it inside + `SNOWLUMA_MCP_UPLOAD_ROOT` (symlink escapes are rejected), hashes and sends it + in fixed-size chunks, and asks SnowLuma to verify the final SHA-256. Transfer + fields such as `stream_id`, `chunk_data`, and `chunk_index` are MCP-owned and + must not also be supplied in `params`. The returned `file_path` is on the + **SnowLuma/OneBot host** and can be passed to a normal send-file action. +- Automatic upload reset is best-effort **before commit**. If SnowLuma commits + the file but the `file_complete` response is lost, the upload state has already + gone and reset cannot remove that committed file. Keep `file_retention` + non-zero (the default is `300000` ms) so SnowLuma eventually reclaims it. +- Stream Actions remain classified as write operations by the current catalog, + so they require `SNOWLUMA_MCP_MODE=write` and `invoke_action`. + +Example automatic upload: + +```json +{ + "action": "upload_file_stream", + "params": { "file_retention": 300000 }, + "execution": { "input_file": "/home/me/mcp-share/report.pdf" } +} +``` + ### Safety model - **Read/write is classified per action** in the source specs (by what the action @@ -99,6 +154,9 @@ groups, etc.). Enable deliberately: `invoke_action` outside write mode is refused even if a client sends it directly. - **Unknown actions are rejected** by both tools (only catalog actions are callable), so typos and non-catalog internal actions can't be driven. +- Stream downloads never put file Base64 into the model result. Downloads use a + `.part` + atomic-rename commit; automatic uploads require an explicit realpath- + fenced root and attempt a pre-commit remote reset if transfer fails. - A well-behaved client can auto-approve `query_action` (read-only) and prompt for `invoke_action` (destructive) using the MCP tool annotations. diff --git a/packages/mcp/package.json b/packages/mcp/package.json index f394027a..316a5ff7 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.12.0", + "version": "1.12.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/mcp/src/client.ts b/packages/mcp/src/client.ts index 155a52c1..c80b0595 100644 --- a/packages/mcp/src/client.ts +++ b/packages/mcp/src/client.ts @@ -8,7 +8,60 @@ // `tsc`-built stdio bin. The wire shape — not a shared client type — is the seam // (ADR-0005); tests inject a fake `ActionClient` (or a fake `fetch`). +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createHash, randomUUID } from 'node:crypto'; + const DEFAULT_TIMEOUT_MS = 30_000; +const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024; +const DEFAULT_STREAM_DIR = path.join(os.tmpdir(), 'snowluma-mcp', 'downloads'); +const MAX_GENERIC_FRAMES = 256; +const MAX_GENERIC_TEXT_BYTES = 256 * 1024; +// OneBot permits a 16 MiB decoded download chunk. Base64 expands that to +// ~21.34 MiB; 24 MiB leaves room for the JSON envelope without allowing an +// unterminated peer to grow our parser buffer without bound. +const MAX_WIRE_FRAME_BYTES = 24 * 1024 * 1024; +const UPLOAD_CHUNK_BYTES = 512 * 1024; +const MAX_FILE_CHUNKS = 200_000; +const RESET_TIMEOUT_MS = 5_000; +const MAX_ACTIVE_STREAMS = 4; +const INTERNAL_STREAM_CALL = Symbol('snowluma.mcp.internalStreamCall'); +const MCP_UPLOAD_OWNED_FIELDS = [ + 'stream_id', 'chunk_data', 'chunk_index', 'total_chunks', 'file_size', + 'expected_sha256', 'is_complete', 'reset', 'verify_only', +] as const; +const FILE_DOWNLOAD_ACTIONS = new Set([ + 'download_file_stream', + 'download_file_image_stream', + 'download_file_record_stream', +]); + +export function parseMaxStreamBytes(raw: string | undefined): number | undefined { + if (raw === undefined) return undefined; + const value = raw.trim(); + if (!/^[1-9]\d*$/.test(value)) { + throw new Error(`SNOWLUMA_MCP_MAX_STREAM_BYTES must be an integer between 1 and ${DEFAULT_MAX_STREAM_BYTES}`); + } + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed > DEFAULT_MAX_STREAM_BYTES) { + throw new Error(`SNOWLUMA_MCP_MAX_STREAM_BYTES must be an integer between 1 and ${DEFAULT_MAX_STREAM_BYTES}`); + } + return parsed; +} + +export function parseTimeoutMs(raw: string | undefined): number | undefined { + if (raw === undefined) return undefined; + const value = raw.trim(); + if (!/^[1-9]\d*$/.test(value)) { + throw new Error('SNOWLUMA_MCP_TIMEOUT_MS must be a positive integer'); + } + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed > 2_147_483_647) { + throw new Error('SNOWLUMA_MCP_TIMEOUT_MS must be a positive integer no greater than 2147483647'); + } + return parsed; +} /** OneBot v11 response envelope, passed through to the LLM verbatim. */ export interface OneBotEnvelope { @@ -25,34 +78,415 @@ export interface ActionClient { /** Send one OneBot action; resolves the full envelope (even on retcode≠0), * rejects only on transport-level failure (timeout / connection / bad body). */ call(action: string, params: Record): Promise; + /** Execute a Stream Action over the HTTP multi-frame transport. */ + callStream(action: string, params: Record, options?: StreamCallOptions): Promise; } +export interface StreamCallOptions { + /** MCP-host file to upload. Only valid for upload_file_stream. */ + inputFile?: string; + /** Cancellation from the originating MCP request. */ + signal?: AbortSignal; +} + +type InternalStreamCallOptions = StreamCallOptions & { [INTERNAL_STREAM_CALL]?: true }; + +interface DownloadReservation { + streamDir: string; + partPath: string; + finalPath: string; + bytes: number; +} + +// Process-wide because multiple MCP clients can target the same directory. +const downloadReservations = new Map>(); + +function reserveDownloadQuota( + streamDir: string, + partPath: string, + finalPath: string, + bytes: number, + quotaBytes: number, +): DownloadReservation { + const active = downloadReservations.get(streamDir) ?? new Map(); + const activePaths = new Set(); + let reservedBytes = 0; + for (const reservation of active.values()) { + activePaths.add(reservation.partPath); + activePaths.add(reservation.finalPath); + reservedBytes += reservation.bytes; + } + let existingBytes = 0; + for (const entry of fs.readdirSync(streamDir, { withFileTypes: true })) { + const target = path.join(streamDir, entry.name); + if (activePaths.has(target) || !entry.isFile()) continue; + try { + existingBytes += fs.lstatSync(target).size; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + if (existingBytes + reservedBytes + bytes > quotaBytes) { + throw new Error( + `download directory quota ${quotaBytes} bytes exceeded: existing=${existingBytes}, reserved=${reservedBytes}, requested reserve=${bytes}`, + ); + } + const reservation = { streamDir, partPath, finalPath, bytes }; + active.set(partPath, reservation); + downloadReservations.set(streamDir, active); + return reservation; +} + +function releaseDownloadQuota(reservation: DownloadReservation | undefined): void { + if (!reservation) return; + const active = downloadReservations.get(reservation.streamDir); + if (!active) return; + active.delete(reservation.partPath); + if (active.size === 0) downloadReservations.delete(reservation.streamDir); +} + +function validateStreamDirectory(streamDir: string): void { + try { + fs.accessSync( + streamDir, + fs.constants.R_OK | fs.constants.W_OK | fs.constants.X_OK, + ); + // Quota admission scans the directory before opening a partial file, so + // list access is a startup requirement too. + fs.readdirSync(streamDir); + } catch (error) { + throw new Error(`streamDir is not readable, writable, and traversable: ${error instanceof Error ? error.message : String(error)}`); + } + + const probePath = path.join(streamDir, `.snowluma-mcp-write-probe-${randomUUID()}`); + let probeFd: number | undefined; + const cleanupErrors: string[] = []; + try { + probeFd = fs.openSync(probePath, 'wx', 0o600); + } catch (error) { + throw new Error(`streamDir cannot create files: ${error instanceof Error ? error.message : String(error)}`); + } + try { + fs.closeSync(probeFd); + probeFd = undefined; + } catch (error) { + cleanupErrors.push(`close probe: ${error instanceof Error ? error.message : String(error)}`); + } + try { + fs.unlinkSync(probePath); + } catch (error) { + cleanupErrors.push(`remove probe: ${error instanceof Error ? error.message : String(error)}`); + } + if (cleanupErrors.length > 0) { + throw new Error(`streamDir write probe cleanup failed: ${cleanupErrors.join('; ')}`); + } +} + +export interface GenericStreamResult { + frame_count: number; + /** Intermediate frames only. Kept bounded by the HTTP client. */ + frames: OneBotEnvelope[]; + /** Last frame received. upload_file_stream acknowledgements are single-frame responses. */ + terminal: OneBotEnvelope; +} + +export interface FileStreamResult { + file_path: string; + file_size: number; + sha256: string; + frame_count: number; + terminal: OneBotEnvelope; +} + +export interface UploadStreamResult { + file_path: string; + file_size: number; + sha256: string; + chunk_count: number; + stream_id: string; + terminal: OneBotEnvelope; +} + +export type StreamCallResult = GenericStreamResult | FileStreamResult | UploadStreamResult; + export interface HttpClientOptions { /** OneBot HTTP endpoint, e.g. http://127.0.0.1:3000/. */ endpoint: string; accessToken?: string; timeoutMs?: number; + /** Directory on the MCP host where downloaded Stream Actions are committed. */ + streamDir?: string; + /** Per-file cap. Defaults to OneBot's 4 GiB limit. */ + maxStreamBytes?: number; + /** Existing MCP-host directory from which automatic uploads may read. */ + uploadRoot?: string; /** Injectable fetch for tests; defaults to the global fetch. */ fetch?: typeof fetch; } +function record(value: unknown): Record | undefined { + return value && typeof value === 'object' && !Array.isArray(value) + ? value as Record + : undefined; +} + +function isWithin(root: string, target: string): boolean { + const relative = path.relative(root, target); + return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative); +} + +function safeDownloadName(value: unknown): string { + const raw = typeof value === 'string' ? path.basename(value) : 'download.bin'; + const safe = raw.replace(/[^A-Za-z0-9._-]/g, '_').replace(/^\.+/, '').slice(0, 180); + return safe || 'download.bin'; +} + +function decodeBase64Chunk(value: string): Buffer { + const valid = value.length % 4 === 0 && /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value); + if (!valid) throw new Error('file_chunk.data is not valid canonical base64'); + return Buffer.from(value, 'base64'); +} + +async function writeAll(handle: fs.promises.FileHandle, data: Buffer): Promise { + let offset = 0; + while (offset < data.length) { + const { bytesWritten } = await handle.write(data, offset, data.length - offset); + if (bytesWritten <= 0) throw new Error('file write made no progress'); + offset += bytesWritten; + } +} + +function terminalData(result: StreamCallResult): Record | undefined { + return record(result.terminal.data); +} + +function abortReason(signal: AbortSignal): string { + const reason = signal.reason; + return reason instanceof Error ? reason.message : reason === undefined ? 'aborted' : String(reason); +} + +function throwIfCancelled(signal: AbortSignal | undefined, action: string, stage: string): void { + if (signal?.aborted) { + throw new Error(`action ${action} stream ${stage}: cancelled: ${abortReason(signal)}`); + } +} + +type ByteStreamReadResult = Awaited['read']>>; + +async function readWithIdleTimeout( + reader: ReadableStreamDefaultReader, + timeoutMs: number, + callerSignal: AbortSignal | undefined, + action: string, + frameIndex: number, +): Promise { + if (callerSignal?.aborted) { + throw new Error(`action ${action} stream read frame ${frameIndex}: cancelled: ${abortReason(callerSignal)}`); + } + return new Promise((resolve, reject) => { + let settled = false; + const finish = (fn: () => void): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + callerSignal?.removeEventListener('abort', onAbort); + fn(); + }; + const onAbort = (): void => finish(() => reject(new Error( + `action ${action} stream read frame ${frameIndex}: cancelled: ${callerSignal ? abortReason(callerSignal) : 'aborted'}`, + ))); + const timer = setTimeout(() => finish(() => reject(new Error( + `action ${action} stream read frame ${frameIndex}: idle timeout after ${timeoutMs}ms`, + ))), timeoutMs); + if (typeof timer.unref === 'function') timer.unref(); + callerSignal?.addEventListener('abort', onAbort, { once: true }); + void reader.read().then( + (result) => finish(() => resolve(result)), + (error) => finish(() => reject(error)), + ); + }); +} + +async function uploadLocalFile( + action: string, + inputFile: string, + params: Record, + maxStreamBytes: number, + callerSignal: AbortSignal | undefined, + post: (params: Record, signal?: AbortSignal) => Promise, +): Promise { + const streamId = randomUUID(); + let handle: fs.promises.FileHandle | undefined; + let stage = 'open input'; + let remoteTouched = false; + try { + throwIfCancelled(callerSignal, action, stage); + handle = await fs.promises.open( + inputFile, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + throwIfCancelled(callerSignal, action, stage); + const initial = await handle.stat(); + if (!initial.isFile()) throw new Error('input_file is not a regular file'); + if (initial.size > maxStreamBytes) throw new Error(`input_file exceeds limit (${maxStreamBytes} bytes)`); + + const totalChunks = Math.max(1, Math.ceil(initial.size / UPLOAD_CHUNK_BYTES)); + const baseParams = { ...params }; + for (const key of MCP_UPLOAD_OWNED_FIELDS) { + delete baseParams[key]; + } + const filename = typeof params.filename === 'string' && params.filename ? params.filename : path.basename(inputFile); + const hash = createHash('sha256'); + let bytesRead = 0; + + for (let chunkIndex = 0; chunkIndex < totalChunks; chunkIndex++) { + stage = `read chunk ${chunkIndex}`; + throwIfCancelled(callerSignal, action, stage); + const wanted = initial.size === 0 ? 0 : Math.min(UPLOAD_CHUNK_BYTES, initial.size - bytesRead); + const chunk = Buffer.allocUnsafe(wanted); + let filled = 0; + while (filled < wanted) { + const read = await handle.read(chunk, filled, wanted - filled, bytesRead + filled); + if (read.bytesRead === 0) break; + filled += read.bytesRead; + } + if (filled !== wanted) throw new Error(`input_file changed while reading (expected ${wanted} bytes, read ${filled})`); + throwIfCancelled(callerSignal, action, stage); + const payload = filled === chunk.length ? chunk : chunk.subarray(0, filled); + hash.update(payload); + bytesRead += payload.length; + + stage = `send chunk ${chunkIndex}`; + throwIfCancelled(callerSignal, action, stage); + remoteTouched = true; + const ack = await post({ + ...baseParams, + stream_id: streamId, + chunk_data: payload.toString('base64'), + chunk_index: chunkIndex, + total_chunks: totalChunks, + file_size: initial.size, + filename, + }, callerSignal); + throwIfCancelled(callerSignal, action, stage); + const ackData = terminalData(ack); + if (ackData?.type !== 'stream' || ackData.status !== 'chunk_received') { + throw new Error(`unexpected chunk acknowledgement: ${JSON.stringify(ack.terminal)}`); + } + } + + stage = 'verify input'; + throwIfCancelled(callerSignal, action, stage); + const afterRead = await handle.stat(); + throwIfCancelled(callerSignal, action, stage); + if (afterRead.size !== initial.size || afterRead.mtimeMs !== initial.mtimeMs) { + throw new Error('input_file changed during upload'); + } + if (bytesRead !== initial.size) throw new Error(`input_file size mismatch (expected ${initial.size}, read ${bytesRead})`); + const sha256 = hash.digest('hex'); + + stage = 'close input'; + await handle.close(); + handle = undefined; + + stage = 'complete upload'; + throwIfCancelled(callerSignal, action, stage); + const completed = await post({ + ...baseParams, + stream_id: streamId, + total_chunks: totalChunks, + file_size: initial.size, + expected_sha256: sha256, + is_complete: true, + filename, + }, callerSignal); + throwIfCancelled(callerSignal, action, stage); + const data = terminalData(completed); + if (data?.type !== 'response' || data.status !== 'file_complete') { + throw new Error(`unexpected completion acknowledgement: ${JSON.stringify(completed.terminal)}`); + } + if (data.file_size !== initial.size) throw new Error(`remote file_size mismatch (expected ${initial.size}, got ${String(data.file_size)})`); + if (data.sha256 !== sha256) throw new Error(`remote sha256 mismatch (expected ${sha256}, got ${String(data.sha256)})`); + if (typeof data.file_path !== 'string' || !data.file_path) throw new Error('completion acknowledgement has no file_path'); + + return { + file_path: data.file_path, + file_size: initial.size, + sha256, + chunk_count: totalChunks, + stream_id: streamId, + terminal: completed.terminal, + }; + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + let closeFailure = ''; + if (handle) { + try { + await handle.close(); + handle = undefined; + } catch (closeError) { + closeFailure = `; close input failed: ${closeError instanceof Error ? closeError.message : String(closeError)}`; + } + } + let resetFailure = ''; + if (remoteTouched) { + try { + await post({ stream_id: streamId, reset: true }, AbortSignal.timeout(RESET_TIMEOUT_MS)); + } catch (resetError) { + resetFailure = `; remote reset failed: ${resetError instanceof Error ? resetError.message : String(resetError)}`; + } + } + throw new Error(`action ${action} stream ${stage}: ${detail}${closeFailure}${resetFailure}`); + } +} + export function makeHttpClient(opts: HttpClientOptions): ActionClient { const fetchImpl = opts.fetch ?? globalThis.fetch; - const timeoutMs = opts.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : DEFAULT_TIMEOUT_MS; + const timeoutMs = opts.timeoutMs ?? DEFAULT_TIMEOUT_MS; + if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 2_147_483_647) { + throw new Error('timeoutMs must be a positive integer no greater than 2147483647'); + } + const maxStreamBytes = opts.maxStreamBytes ?? DEFAULT_MAX_STREAM_BYTES; + if (!Number.isSafeInteger(maxStreamBytes) || maxStreamBytes <= 0 || maxStreamBytes > DEFAULT_MAX_STREAM_BYTES) { + throw new Error(`maxStreamBytes must be an integer between 1 and ${DEFAULT_MAX_STREAM_BYTES}`); + } + const configuredStreamDir = path.resolve(opts.streamDir ?? DEFAULT_STREAM_DIR); + try { + fs.mkdirSync(configuredStreamDir, { recursive: true, mode: 0o700 }); + } catch (error) { + throw new Error(`streamDir cannot be created: ${error instanceof Error ? error.message : String(error)}`); + } + if (!fs.statSync(configuredStreamDir).isDirectory()) { + throw new Error(`streamDir is not a directory: ${configuredStreamDir}`); + } + const streamDir = fs.realpathSync(configuredStreamDir); + validateStreamDirectory(streamDir); + let uploadRoot: string | undefined; + if (opts.uploadRoot) { + uploadRoot = fs.realpathSync(opts.uploadRoot); + if (!fs.statSync(uploadRoot).isDirectory()) throw new Error(`uploadRoot is not a directory: ${uploadRoot}`); + } const headers: Record = { 'Content-Type': 'application/json', Accept: 'application/json', }; if (opts.accessToken) headers.Authorization = `Bearer ${opts.accessToken}`; - return { + let client: ActionClient; + let activeStreams = 0; + client = { async call(action, params) { - const res = await fetchImpl(opts.endpoint, { - method: 'POST', - headers, - body: JSON.stringify({ action, params }), - signal: AbortSignal.timeout(timeoutMs), - }); + let res: Response; + try { + res = await fetchImpl(opts.endpoint, { + method: 'POST', + headers, + body: JSON.stringify({ action, params }), + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (error) { + throw new Error(`action ${action} request: ${error instanceof Error ? error.message : String(error)}`); + } const text = await res.text(); let parsed: unknown; try { @@ -65,5 +499,306 @@ export function makeHttpClient(opts: HttpClientOptions): ActionClient { } return parsed as OneBotEnvelope; }, + async callStream(action, params, options) { + const internalOptions = options as InternalStreamCallOptions | undefined; + const ownsSlot = internalOptions?.[INTERNAL_STREAM_CALL] !== true; + if (ownsSlot) { + if (activeStreams >= MAX_ACTIVE_STREAMS) { + throw new Error(`action ${action} stream admission: active Stream Action limit reached (${MAX_ACTIVE_STREAMS})`); + } + activeStreams++; + } + try { + let resolvedInputFile: string | undefined; + if (options?.inputFile) { + if (action !== 'upload_file_stream') { + throw new Error(`action ${action} stream resolve input: input_file is only valid for upload_file_stream`); + } + if (!uploadRoot) { + throw new Error(`action ${action} stream resolve input: SNOWLUMA_MCP_UPLOAD_ROOT is not configured`); + } + const conflicts = MCP_UPLOAD_OWNED_FIELDS.filter((key) => Object.hasOwn(params, key)); + if (conflicts.length) { + throw new Error(`action ${action} stream prepare upload: params conflict with MCP-owned transfer fields: ${conflicts.join(', ')}`); + } + try { + resolvedInputFile = fs.realpathSync(options.inputFile); + } catch (error) { + throw new Error(`action ${action} stream resolve input: ${error instanceof Error ? error.message : String(error)}`); + } + if (!isWithin(uploadRoot, resolvedInputFile)) { + throw new Error(`action ${action} stream resolve input: resolved path is outside the configured upload root`); + } + return uploadLocalFile( + action, + resolvedInputFile, + params, + maxStreamBytes, + options.signal, + (uploadParams, signal) => client.callStream(action, uploadParams, { + ...(signal ? { signal } : {}), + [INTERNAL_STREAM_CALL]: true, + } as InternalStreamCallOptions), + ); + } + let res: Response; + const connectionController = new AbortController(); + const requestSignal = options?.signal + ? AbortSignal.any([options.signal, connectionController.signal]) + : connectionController.signal; + const connectionTimer = setTimeout(() => { + connectionController.abort(new Error(`connection timeout after ${timeoutMs}ms`)); + }, timeoutMs); + if (typeof connectionTimer.unref === 'function') connectionTimer.unref(); + try { + res = await fetchImpl(opts.endpoint, { + method: 'POST', + headers, + body: JSON.stringify({ action, params }), + signal: requestSignal, + }); + } catch (error) { + const detail = options?.signal?.aborted + ? `cancelled: ${abortReason(options.signal)}` + : connectionController.signal.aborted + ? abortReason(connectionController.signal) + : error instanceof Error ? error.message : String(error); + throw new Error(`action ${action} stream connection: ${detail}`); + } finally { + clearTimeout(connectionTimer); + } + if (!res.ok) throw new Error(`action ${action} stream HTTP: unexpected status ${res.status}`); + if (!res.body) throw new Error(`action ${action} stream body: response body is unavailable`); + + const reader = res.body.getReader(); + const decoder = new TextDecoder('utf-8', { fatal: true }); + const frames: OneBotEnvelope[] = []; + let buffer = ''; + let bufferWireBytes = 0; + let frameIndex = 0; + let fileHandle: fs.promises.FileHandle | undefined; + let partPath: string | undefined; + let finalPath: string | undefined; + let declaredSize: number | undefined; + let fileBytes = 0; + let fileChunks = 0; + let fileTerminal: OneBotEnvelope | undefined; + let quotaReservation: DownloadReservation | undefined; + let genericTextBytes = 0; + let genericTerminalIndex: number | undefined; + const fileHash = createHash('sha256'); + + const acceptFrame = async (frame: OneBotEnvelope, rawBytes: number): Promise => { + const data = record(frame.data); + const dataType = data?.data_type; + const resetAck = action === 'upload_file_stream' && params.reset === true && + /stream reset completed/i.test(String(frame.wording ?? frame.message ?? '')); + if (!resetAck && (frame.status !== 'ok' || frame.retcode !== 0 || data?.type === 'error')) { + const detail = frame.wording || frame.message || `retcode=${String(frame.retcode)}`; + throw new Error(`action ${action} stream frame ${frameIndex}: terminal error: ${detail}`); + } + if (frameIndex === 0 && FILE_DOWNLOAD_ACTIONS.has(action) && dataType !== 'file_info') { + throw new Error(`action ${action} stream frame 0: first successful frame must be file_info`); + } + if (!fileHandle && (dataType === 'file_chunk' || dataType === 'file_complete')) { + throw new Error(`action ${action} stream frame ${frameIndex}: ${String(dataType)} received without file_info`); + } + if (dataType === 'file_info') { + if (!data) throw new Error(`action ${action} stream frame ${frameIndex}: file_info data must be an object`); + if (frameIndex !== 0 || fileHandle) throw new Error(`action ${action} stream frame ${frameIndex}: file_info must be the first and only header`); + const size = data.file_size; + if (!Number.isSafeInteger(size) || (size as number) < 0) { + throw new Error(`action ${action} stream frame ${frameIndex}: invalid file_size`); + } + if ((size as number) > maxStreamBytes) { + throw new Error(`action ${action} stream frame ${frameIndex}: file_size exceeds limit (${maxStreamBytes} bytes)`); + } + if (data.chunk_size !== undefined) { + if (!Number.isSafeInteger(data.chunk_size) || (data.chunk_size as number) <= 0) { + throw new Error(`action ${action} stream frame ${frameIndex}: invalid chunk_size`); + } + const expectedChunks = Math.ceil((size as number) / (data.chunk_size as number)); + if (expectedChunks > MAX_FILE_CHUNKS) { + throw new Error(`action ${action} stream frame ${frameIndex}: declared file chunks exceed limit (${MAX_FILE_CHUNKS})`); + } + } + // NapCat/SnowLuma use 0 when the source length is unknown. Only a + // positive header value is a strict declaration. + declaredSize = (size as number) > 0 ? size as number : undefined; + const filename = `${randomUUID()}-${safeDownloadName(data.file_name)}`; + finalPath = path.join(streamDir, filename); + partPath = `${finalPath}.part`; + quotaReservation = reserveDownloadQuota( + streamDir, + partPath, + finalPath, + declaredSize ?? maxStreamBytes, + 2 * maxStreamBytes, + ); + try { + fileHandle = await fs.promises.open(partPath, 'wx', 0o600); + } catch (error) { + releaseDownloadQuota(quotaReservation); + quotaReservation = undefined; + throw error; + } + return; + } + + if (fileHandle) { + if (fileTerminal) throw new Error(`action ${action} stream frame ${frameIndex}: frame received after terminal`); + if (dataType === 'file_chunk') { + if (fileChunks >= MAX_FILE_CHUNKS) { + throw new Error(`action ${action} stream frame ${frameIndex}: file chunks exceed limit (${MAX_FILE_CHUNKS})`); + } + if (!data || typeof data.data !== 'string') throw new Error(`action ${action} stream frame ${frameIndex}: file_chunk.data must be base64 text`); + if (!Number.isSafeInteger(data.index) || data.index !== fileChunks) { + throw new Error(`action ${action} stream frame ${frameIndex}: expected chunk index ${fileChunks}, got ${String(data.index)}`); + } + let chunk: Buffer; + try { + chunk = decodeBase64Chunk(data.data); + } catch (error) { + throw new Error(`action ${action} stream frame ${frameIndex}: ${error instanceof Error ? error.message : String(error)}`); + } + if (data.size !== undefined && (!Number.isSafeInteger(data.size) || data.size !== chunk.length)) { + throw new Error(`action ${action} stream frame ${frameIndex}: file_chunk.size does not match decoded base64 bytes`); + } + const nextBytes = fileBytes + chunk.length; + if (declaredSize !== undefined && nextBytes > declaredSize) { + throw new Error(`action ${action} stream frame ${frameIndex}: downloaded bytes exceed declared file_size (${declaredSize} bytes)`); + } + if (nextBytes > maxStreamBytes) { + throw new Error(`action ${action} stream frame ${frameIndex}: downloaded bytes exceed limit (${maxStreamBytes} bytes)`); + } + await writeAll(fileHandle, chunk); + fileHash.update(chunk); + fileBytes += chunk.length; + fileChunks++; + return; + } + if (data?.type === 'response' && dataType === 'file_complete') { + fileTerminal = frame; + return; + } + throw new Error(`action ${action} stream frame ${frameIndex}: unexpected file frame ${String(dataType ?? data?.type ?? 'unknown')}`); + } + + if (frames.length >= MAX_GENERIC_FRAMES) { + throw new Error(`action ${action} stream frame ${frameIndex}: generic frame summary exceeds limit (${MAX_GENERIC_FRAMES})`); + } + if (genericTerminalIndex !== undefined) { + throw new Error(`action ${action} stream frame ${frameIndex}: frame received after response terminal at frame ${genericTerminalIndex}`); + } + genericTextBytes += rawBytes; + if (genericTextBytes > MAX_GENERIC_TEXT_BYTES) { + throw new Error(`action ${action} stream frame ${frameIndex}: generic summary text exceeds limit (${MAX_GENERIC_TEXT_BYTES} bytes)`); + } + frames.push(frame); + if (data?.type === 'response') genericTerminalIndex = frameIndex; + }; + try { + while (true) { + const { done, value } = await readWithIdleTimeout(reader, timeoutMs, options?.signal, action, frameIndex); + if (done) break; + bufferWireBytes += value.byteLength; + buffer += decoder.decode(value, { stream: true }); + let delimiter: number; + while ((delimiter = buffer.indexOf('\r\n\r\n')) >= 0) { + const raw = buffer.slice(0, delimiter); + buffer = buffer.slice(delimiter + 4); + const rawBytes = Buffer.byteLength(raw, 'utf8'); + bufferWireBytes -= rawBytes + 4; + if (rawBytes > MAX_WIRE_FRAME_BYTES) { + throw new Error(`action ${action} stream frame ${frameIndex}: wire frame exceeds limit (${MAX_WIRE_FRAME_BYTES} bytes)`); + } + if (!raw) throw new Error(`action ${action} stream frame ${frameIndex}: empty frame`); + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (error) { + throw new Error(`action ${action} stream frame ${frameIndex}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`action ${action} stream frame ${frameIndex}: expected an object envelope`); + } + try { + await acceptFrame(parsed as OneBotEnvelope, rawBytes); + } catch (error) { + const detail = error instanceof Error ? error.message : String(error); + if (detail.startsWith(`action ${action} `)) throw error; + throw new Error(`action ${action} stream frame ${frameIndex}: frame handling failed: ${detail}`); + } + frameIndex++; + } + if (bufferWireBytes > MAX_WIRE_FRAME_BYTES) { + throw new Error(`action ${action} stream frame ${frameIndex}: wire frame exceeds limit (${MAX_WIRE_FRAME_BYTES} bytes)`); + } + } + buffer += decoder.decode(); + if (buffer.trim()) throw new Error(`action ${action} stream EOF after frame ${frameIndex}: unterminated frame`); + if (fileHandle) { + if (!fileTerminal) throw new Error(`action ${action} stream EOF after frame ${frameIndex}: missing file_complete terminal`); + if (declaredSize !== undefined && declaredSize !== fileBytes) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: expected ${declaredSize} bytes, received ${fileBytes}`); + } + const terminalData = record(fileTerminal.data); + if (!Number.isSafeInteger(terminalData?.total_bytes) || (terminalData!.total_bytes as number) < 0) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: terminal total_bytes is missing or invalid`); + } + if (terminalData!.total_bytes !== fileBytes) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: terminal total_bytes mismatch`); + } + if (terminalData?.total_chunks !== undefined && terminalData.total_chunks !== fileChunks) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: terminal total_chunks mismatch`); + } + const sha256 = fileHash.digest('hex'); + await fileHandle.close(); + fileHandle = undefined; + await fs.promises.rename(partPath!, finalPath!); + partPath = undefined; + releaseDownloadQuota(quotaReservation); + quotaReservation = undefined; + return { + file_path: finalPath!, + file_size: fileBytes, + sha256, + frame_count: frameIndex, + terminal: fileTerminal, + }; + } + if (!frames.length) throw new Error(`action ${action} stream EOF: no frames received`); + const uploadAck = action === 'upload_file_stream' && frames.length === 1; + if (genericTerminalIndex === undefined && !uploadAck) { + throw new Error(`action ${action} stream EOF after frame ${frameIndex}: missing response terminal`); + } + return { frame_count: frames.length, frames: frames.slice(0, -1), terminal: frames.at(-1)! }; + } catch (error) { + const cleanupErrors: string[] = []; + try { await reader.cancel(error instanceof Error ? error.message : String(error)); } catch (cleanupError) { + cleanupErrors.push(`cancel response body: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`); + } + try { await fileHandle?.close(); } catch (cleanupError) { + cleanupErrors.push(`close: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`); + } + if (partPath) { + try { await fs.promises.rm(partPath, { force: true }); } catch (cleanupError) { + cleanupErrors.push(`remove ${partPath}: ${cleanupError instanceof Error ? cleanupError.message : String(cleanupError)}`); + } + } + releaseDownloadQuota(quotaReservation); + quotaReservation = undefined; + const detail = error instanceof Error ? error.message : String(error); + const base = detail.startsWith(`action ${action} `) ? detail : `action ${action} stream body: ${detail}`; + const suffix = cleanupErrors.length ? `; cleanup failed (${cleanupErrors.join('; ')})` : ''; + throw new Error(base + suffix); + } finally { + reader.releaseLock(); + } + } finally { + if (ownsSlot) activeStreams--; + } + }, }; + return client; } diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 247d313c..1e597048 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -7202,6 +7202,15 @@ "description": "OneBot message: string | segment[] | object" } }, + { + "name": "group_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, { "name": "auto_escape", "type": "bool", @@ -7224,6 +7233,10 @@ "message": { "description": "OneBot message: string | segment[] | object" }, + "group_id": { + "type": "integer", + "minimum": 0 + }, "auto_escape": { "type": "boolean", "default": false diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 4ea6f6e9..39a0437b 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -7205,6 +7205,15 @@ export const ACTIONS: CatalogAction[] = [ "description": "OneBot message: string | segment[] | object" } }, + { + "name": "group_id", + "type": "int", + "required": false, + "schema": { + "type": "integer", + "minimum": 0 + } + }, { "name": "auto_escape", "type": "bool", @@ -7227,6 +7236,10 @@ export const ACTIONS: CatalogAction[] = [ "message": { "description": "OneBot message: string | segment[] | object" }, + "group_id": { + "type": "integer", + "minimum": 0 + }, "auto_escape": { "type": "boolean", "default": false diff --git a/packages/mcp/src/server.ts b/packages/mcp/src/server.ts index 93dc5df7..63718d96 100644 --- a/packages/mcp/src/server.ts +++ b/packages/mcp/src/server.ts @@ -13,9 +13,13 @@ // SNOWLUMA_MCP_ENDPOINT OneBot HTTP endpoint (e.g. http://127.0.0.1:3000/). // Absent → docs-only (execution tools hidden). // SNOWLUMA_MCP_TOKEN access token (Bearer) for the endpoint. -// SNOWLUMA_MCP_TIMEOUT_MS per-request timeout (default SDK 30s). +// SNOWLUMA_MCP_TIMEOUT_MS ordinary request timeout; Stream connection and +// per-read idle timeout (default 30s). // SNOWLUMA_MCP_MODE docs | read | write. Default: read when an // endpoint is set, else docs. +// SNOWLUMA_MCP_STREAM_DIR MCP-host directory for completed downloads. +// SNOWLUMA_MCP_UPLOAD_ROOT Existing MCP-host directory allowed for uploads. +// SNOWLUMA_MCP_MAX_STREAM_BYTES Per-file cap (1..4 GiB; default 4 GiB). // // NOTE: stdout is the MCP protocol channel — all diagnostics go to stderr. @@ -29,8 +33,8 @@ import { ReadResourceRequestSchema, } from '@modelcontextprotocol/sdk/types.js'; import { ACTIONS, CATEGORIES } from './generated/catalog.js'; -import { makeHttpClient, type ActionClient } from './client.js'; -import { callTool, computeTools, type Mode } from './tools.js'; +import { makeHttpClient, parseMaxStreamBytes, parseTimeoutMs, type ActionClient } from './client.js'; +import { callTool, computeTools, parseMode, type Mode } from './tools.js'; const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')) as { version: string }; const VERSION = pkg.version; @@ -41,24 +45,25 @@ const RESOURCE_URI = 'snowluma://onebot/actions'; function resolveRuntime(): { mode: Mode; client?: ActionClient } { const endpoint = process.env.SNOWLUMA_MCP_ENDPOINT?.trim(); const token = process.env.SNOWLUMA_MCP_TOKEN?.trim() || undefined; - const timeoutRaw = Number(process.env.SNOWLUMA_MCP_TIMEOUT_MS); - const timeoutMs = Number.isFinite(timeoutRaw) && timeoutRaw > 0 ? timeoutRaw : undefined; - const requested = process.env.SNOWLUMA_MCP_MODE?.trim().toLowerCase(); - const validRequest = requested === 'docs' || requested === 'read' || requested === 'write' ? requested : undefined; + const streamDir = process.env.SNOWLUMA_MCP_STREAM_DIR?.trim() || undefined; + const uploadRoot = process.env.SNOWLUMA_MCP_UPLOAD_ROOT?.trim() || undefined; + const maxStreamBytes = parseMaxStreamBytes(process.env.SNOWLUMA_MCP_MAX_STREAM_BYTES); + const timeoutMs = parseTimeoutMs(process.env.SNOWLUMA_MCP_TIMEOUT_MS); + const requested = parseMode(process.env.SNOWLUMA_MCP_MODE); if (!endpoint) { - if (validRequest && validRequest !== 'docs') { - console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${validRequest} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`); + if (requested && requested !== 'docs') { + console.error(`[snowluma-mcp] SNOWLUMA_MCP_MODE=${requested} ignored: no SNOWLUMA_MCP_ENDPOINT set — docs-only.`); } return { mode: 'docs' }; } - const mode: Mode = validRequest ?? 'read'; + const mode: Mode = requested ?? 'read'; if (mode === 'docs') { // Endpoint set but operator explicitly wants docs-only — honor it. return { mode: 'docs' }; } - const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs }); + const client = makeHttpClient({ endpoint, accessToken: token, timeoutMs, streamDir, uploadRoot, maxStreamBytes }); return { mode, client }; } @@ -71,9 +76,9 @@ const server = new Server( server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools: computeTools(mode) })); -server.setRequestHandler(CallToolRequestSchema, async (req) => { +server.setRequestHandler(CallToolRequestSchema, async (req, extra) => { const args = (req.params.arguments ?? {}) as Record; - return callTool(req.params.name, args, { mode, client }); + return callTool(req.params.name, args, { mode, client, signal: extra.signal }); }); server.setRequestHandler(ListResourcesRequestSchema, async () => ({ diff --git a/packages/mcp/src/tools.ts b/packages/mcp/src/tools.ts index ca1e21af..0099ae1e 100644 --- a/packages/mcp/src/tools.ts +++ b/packages/mcp/src/tools.ts @@ -15,6 +15,13 @@ import type { ActionClient } from './client.js'; export type Mode = 'docs' | 'read' | 'write'; +export function parseMode(raw: string | undefined): Mode | undefined { + if (raw === undefined) return undefined; + const value = raw.trim().toLowerCase(); + if (value === 'docs' || value === 'read' || value === 'write') return value; + throw new Error('SNOWLUMA_MCP_MODE must be one of: docs, read, write'); +} + // name + every alias → action, so lookups accept aliases too. const byName = new Map(); for (const a of ACTIONS) { @@ -23,13 +30,13 @@ for (const a of ACTIONS) { /** Lightweight index entry (keeps list/search payloads small). */ function lite(a: CatalogAction) { - return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly }; + return { name: a.name, category: a.category, summary: a.summary, aliases: a.aliases, readOnly: a.readOnly, stream: a.stream ?? false }; } const DOCS_TOOLS: Tool[] = [ { name: 'list_actions', - description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读)。', + description: '列出所有 OneBot action(可按 category 过滤)。返回轻量索引(名称/分类/摘要/别名/是否只读/是否为 Stream Action)。', inputSchema: { type: 'object', properties: { category: { type: 'string', description: '按分类过滤,如 群管理 / 消息 / 好友' } }, @@ -72,6 +79,17 @@ const EXEC_INPUT_SCHEMA = { properties: { action: { type: 'string', description: 'action 名(接受别名)。先用 get_action 查它的参数 inputSchema。' }, params: { type: 'object', description: '该 action 的参数对象', additionalProperties: true }, + execution: { + type: 'object', + description: 'MCP 主机侧执行选项(不会发送为 OneBot params)。自动上传本地文件时使用。', + properties: { + input_file: { + type: 'string', + description: 'MCP 主机上的文件路径。仅用于 upload_file_stream,且必须位于 SNOWLUMA_MCP_UPLOAD_ROOT。', + }, + }, + additionalProperties: false, + }, }, required: ['action'], additionalProperties: false, @@ -89,7 +107,7 @@ function queryTool(): Tool { function invokeTool(): Tool { return { name: 'invoke_action', - description: '调用一个 OneBot action(可产生副作用:发消息、改群、改资料等)并返回完整响应。仅在写模式可用。', + description: '调用一个 OneBot action(可产生副作用)。Stream 下载会写入 MCP 主机受控目录并只返回文件元数据;upload_file_stream 可用 execution.input_file 自动分块上传。仅在写模式可用。', inputSchema: EXEC_INPUT_SCHEMA, annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true }, }; @@ -115,6 +133,7 @@ function asError(message: string): ToolResult { export interface CallCtx { mode: Mode; client?: ActionClient; + signal?: AbortSignal; } export async function callTool(name: string, args: Record, ctx: CallCtx): Promise { @@ -173,10 +192,36 @@ async function execute(args: Record, ctx: CallCtx, kind: 'read' args.params && typeof args.params === 'object' && !Array.isArray(args.params) ? (args.params as Record) : {}; + let inputFile: string | undefined; + if (args.execution !== undefined) { + if (!args.execution || typeof args.execution !== 'object' || Array.isArray(args.execution)) { + return asError('execution 必须是对象。'); + } + const execution = args.execution as Record; + const unknown = Object.keys(execution).filter((key) => key !== 'input_file'); + if (unknown.length) return asError(`未知 MCP execution 选项: ${unknown.join(', ')}`); + if (execution.input_file !== undefined) { + if (typeof execution.input_file !== 'string' || !execution.input_file.trim()) { + return asError('execution.input_file 必须是非空字符串。'); + } + inputFile = execution.input_file; + } + } + if (inputFile && cat.name !== 'upload_file_stream') { + return asError('execution.input_file 仅可用于 upload_file_stream。'); + } + if (inputFile && !cat.stream) { + return asError(`${action} 不是 Stream Action,不能使用 execution.input_file。`); + } try { - const envelope = await ctx.client.call(action, params); - return asText(envelope); + const result = cat.stream + ? await ctx.client.callStream(action, params, { + ...(inputFile ? { inputFile } : {}), + ...(ctx.signal ? { signal: ctx.signal } : {}), + }) + : await ctx.client.call(action, params); + return asText(result); } catch (err) { - return asError(`调用失败: ${err instanceof Error ? err.message : String(err)}`); + return asError(`调用失败 (${action}): ${err instanceof Error ? err.message : String(err)}`); } } diff --git a/packages/mcp/tests/client.test.ts b/packages/mcp/tests/client.test.ts index 28994e67..bf8b0cf8 100644 --- a/packages/mcp/tests/client.test.ts +++ b/packages/mcp/tests/client.test.ts @@ -1,10 +1,73 @@ -import { describe, it, expect } from 'vitest'; -import { makeHttpClient } from '../src/client'; +import { describe, it, expect, afterEach, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createHash } from 'node:crypto'; +import { makeHttpClient, parseMaxStreamBytes, parseTimeoutMs } from '../src/client'; + +const tempDirs: string[] = []; + +afterEach(() => { + vi.restoreAllMocks(); + for (const dir of tempDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); +}); // Verifies the HTTP bridge: a OneBot action becomes a POST of `{ action, params }` // to the endpoint (with Bearer auth), and the JSON envelope comes back verbatim. // A fake fetch stands in for the network. describe('makeHttpClient — OneBot HTTP wiring', () => { + it('validates SNOWLUMA_MCP_MAX_STREAM_BYTES as a positive 4 GiB-or-lower integer', () => { + expect(parseMaxStreamBytes(undefined)).toBeUndefined(); + expect(parseMaxStreamBytes('1048576')).toBe(1048576); + for (const invalid of ['', '0', '-1', '1.5', '1e6', String(4 * 1024 * 1024 * 1024 + 1), 'nope']) { + expect(() => parseMaxStreamBytes(invalid), invalid).toThrow(/SNOWLUMA_MCP_MAX_STREAM_BYTES/); + } + }); + + it('fails fast on an invalid SNOWLUMA_MCP_TIMEOUT_MS', () => { + expect(parseTimeoutMs(undefined)).toBeUndefined(); + expect(parseTimeoutMs('30000')).toBe(30000); + for (const invalid of ['', '0', '-1', '1.5', '1e3', 'nope']) { + expect(() => parseTimeoutMs(invalid), invalid).toThrow(/SNOWLUMA_MCP_TIMEOUT_MS/); + } + }); + + it('rejects an invalid programmatic timeout instead of silently using the default', () => { + for (const timeoutMs of [0, -1, 1.5, Number.NaN, Number.POSITIVE_INFINITY]) { + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', timeoutMs }), String(timeoutMs)) + .toThrow(/timeoutMs.*positive.*integer/i); + } + }); + + it('creates the configured stream directory at client startup and rejects a file path', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-config-')); + tempDirs.push(root); + const nested = path.join(root, 'nested', 'downloads'); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: nested })).not.toThrow(); + expect(fs.statSync(nested).isDirectory()).toBe(true); + + const filePath = path.join(root, 'not-a-directory'); + fs.writeFileSync(filePath, 'x'); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: filePath })).toThrow(/streamDir.*(?:not a directory|cannot be created)/i); + }); + + it('fails startup when the stream directory cannot be accessed or create files', () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-config-')); + tempDirs.push(root); + + vi.spyOn(fs, 'accessSync').mockImplementationOnce(() => { + throw Object.assign(new Error('permission denied'), { code: 'EACCES' }); + }); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: root })) + .toThrow(/streamDir.*readable.*writable.*traversable.*permission denied/i); + + vi.spyOn(fs, 'openSync').mockImplementationOnce(() => { + throw Object.assign(new Error('create denied'), { code: 'EACCES' }); + }); + expect(() => makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', streamDir: root })) + .toThrow(/streamDir.*cannot create files.*create denied/i); + }); + it('POSTs {action, params} to the endpoint and returns the parsed envelope', async () => { const calls: Array<{ url: string; body: any; auth?: string }> = []; const fakeFetch = (async (url: unknown, init: any) => { @@ -36,4 +99,592 @@ describe('makeHttpClient — OneBot HTTP wiring', () => { const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); await expect(client.call('get_status', {})).rejects.toThrow(); }); + + it('incrementally parses stream frames across arbitrary network chunk boundaries', async () => { + const frames = [ + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', data_type: 'data_chunk', data: 'Index-> 1' } }, + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'response', data_type: 'data_complete', data: 'done' } }, + ]; + const wire = frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const cuts = [1, 7, 19, 31, 57, wire.length]; + const chunks: Uint8Array[] = []; + let offset = 0; + for (const cut of cuts) { + chunks.push(new TextEncoder().encode(wire.slice(offset, cut))); + offset = cut; + } + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk); + controller.close(); + }, + }), { status: 200 })) as unknown as typeof fetch; + + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + const result = await client.callStream('test_download_stream', {}); + + expect(result).toEqual({ frame_count: 2, frames: [frames[0]], terminal: frames[1] }); + }); + + it('writes a multi-frame file download atomically and returns metadata instead of base64', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const content = Buffer.from('streamed file content '.repeat(200)); + const parts = [content.subarray(0, 997), content.subarray(997)]; + const frames = [ + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', data_type: 'file_info', file_name: '../unsafe.bin', file_size: content.length, chunk_size: 997 } }, + ...parts.map((part, index) => ({ status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', data_type: 'file_chunk', index, size: part.length, data: part.toString('base64') } })), + { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'response', data_type: 'file_complete', total_chunks: parts.length, total_bytes: content.length } }, + ]; + const wire = frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const fakeFetch = (async () => new Response(wire, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + const result = await client.callStream('download_file_stream', { file: 'remote-id' }); + + expect(Object.keys(result).sort()).toEqual(['file_path', 'file_size', 'frame_count', 'sha256', 'terminal']); + expect(result.file_size).toBe(content.length); + expect(result.frame_count).toBe(frames.length); + expect(result.sha256).toBe(createHash('sha256').update(content).digest('hex')); + expect(path.isAbsolute(result.file_path)).toBe(true); + expect(path.dirname(result.file_path)).toBe(fs.realpathSync(streamDir)); + expect(fs.readFileSync(result.file_path).equals(content)).toBe(true); + expect(fs.readdirSync(streamDir).some((name) => name.endsWith('.part'))).toBe(false); + expect(JSON.stringify(result)).not.toContain(parts[0].toString('base64')); + }); + + it('surfaces a terminal stream error with action/frame context and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'broken.bin', file_size: 3 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 3, data: Buffer.from('abc').toString('base64') } }, + { status: 'failed', retcode: 100, wording: 'source disconnected', data: { type: 'error', data_type: 'error' } }, + ]; + const wire = frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const fakeFetch = (async () => new Response(wire, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*frame 2.*source disconnected/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('removes the partial file when the response body disconnects before a terminal frame', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const prefix = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'cut.bin', file_size: 6 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 3, data: Buffer.from('abc').toString('base64') } }, + ].map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode(prefix)); + controller.error(new Error('socket reset')); + }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*body.*socket reset/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('enforces the configured byte ceiling while streaming and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'too-big.bin', file_size: 3 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 4, data: Buffer.from('abcd').toString('base64') } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, maxStreamBytes: 3 }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/frame 1.*exceed.*3 bytes/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('fails fast when a non-file stream exceeds the bounded frame summary count', async () => { + const frames = Array.from({ length: 257 }, (_, index) => ({ + status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: `frame-${index}` }, + })); + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 256.*summary.*256/i); + }); + + it('fails fast when a non-file stream exceeds the bounded summary text size', async () => { + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'x'.repeat(256 * 1024) } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 0.*summary text.*262144/i); + }); + + it('rejects malformed base64 file frames and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'bad.bin', file_size: 0 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 0, data: '%%%=' } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*frame 1.*base64/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('accepts upload_file_stream single-frame acknowledgements without requiring a response-type terminal', async () => { + const ack = { status: 'ok', retcode: 0, stream: 'stream-action', data: { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 2 } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(ack)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('upload_file_stream', { stream_id: 'id', chunk_index: 0, chunk_data: 'YQ==' })) + .resolves.toEqual({ frame_count: 1, frames: [], terminal: ack }); + }); + + it('refuses MCP-host file upload unless an upload root is explicitly configured', async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-upload-')); + tempDirs.push(dir); + const inputFile = path.join(dir, 'local.txt'); + fs.writeFileSync(inputFile, 'local'); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile })).rejects.toThrow(/upload_file_stream.*resolve input.*SNOWLUMA_MCP_UPLOAD_ROOT/i); + expect(fetchCalls).toBe(0); + }); + + it('rejects an unterminated wire frame before its buffer can grow beyond the 24 MiB frame cap', async () => { + const oversized = new Uint8Array(24 * 1024 * 1024 + 1).fill(0x78); + const fakeFetch = (async () => new Response(oversized, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 0.*wire.*25165824/i); + }); + + it('actively cancels the response body when frame parsing fails', async () => { + let cancelled = false; + const body = new ReadableStream({ + start(controller) { + controller.enqueue(new TextEncoder().encode('not-json\r\n\r\n')); + }, + cancel() { + cancelled = true; + }, + }); + const fakeFetch = (async () => new Response(body, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/frame 0.*invalid JSON/i); + expect(cancelled).toBe(true); + }); + + it('rejects EOF on a generic stream that never produced a response terminal', async () => { + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'only-intermediate' } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*EOF.*missing.*response terminal/i); + }); + + it('rejects any generic frame after the unique response terminal', async () => { + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete', data: 'done' } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'late' } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/test_download_stream.*frame 1.*after response terminal.*frame 0/i); + }); + + it('realpaths upload inputs and rejects a symlink that escapes the configured upload root', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-outside-')); + tempDirs.push(root, outside); + const outsideFile = path.join(outside, 'secret.txt'); + const link = path.join(root, 'escape.txt'); + fs.writeFileSync(outsideFile, 'secret'); + fs.symlinkSync(outsideFile, link); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile: link })).rejects.toThrow(/upload_file_stream.*resolve input.*outside.*upload root/i); + expect(fetchCalls).toBe(0); + }); + + it('uploads an allowed MCP-host file in fixed chunks and returns a base64-free summary', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'payload.bin'); + const content = Buffer.alloc(600 * 1024); + for (let i = 0; i < content.length; i++) content[i] = i % 251; + fs.writeFileSync(inputFile, content); + const sha256 = createHash('sha256').update(content).digest('hex'); + const requests: Array> = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + const p = request.params; + const data = p.is_complete + ? { type: 'response', status: 'file_complete', file_path: '/snowluma/upload/payload.bin', file_size: content.length, sha256, total_chunks: 2 } + : { type: 'stream', status: 'chunk_received', received_chunks: p.chunk_index + 1, total_chunks: 2 }; + const frame = { status: 'ok', retcode: 0, stream: 'stream-action', data }; + return new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + const result = await client.callStream('upload_file_stream', { file_retention: 0 }, { inputFile }); + + expect(requests).toHaveLength(3); + expect(requests.every((request) => request.action === 'upload_file_stream')).toBe(true); + const chunks = requests.slice(0, 2).map((request) => Buffer.from(request.params.chunk_data, 'base64')); + expect(Buffer.concat(chunks).equals(content)).toBe(true); + expect(requests[0].params).toMatchObject({ chunk_index: 0, total_chunks: 2, file_size: content.length, filename: 'payload.bin', file_retention: 0 }); + expect(requests[1].params).toMatchObject({ chunk_index: 1, total_chunks: 2 }); + expect(requests[2].params).toMatchObject({ is_complete: true, expected_sha256: sha256, file_size: content.length }); + expect(new Set(requests.map((request) => request.params.stream_id)).size).toBe(1); + expect(result).toMatchObject({ + file_path: '/snowluma/upload/payload.bin', + file_size: content.length, + sha256, + chunk_count: 2, + stream_id: requests[0].params.stream_id, + }); + expect(JSON.stringify(result)).not.toContain(requests[0].params.chunk_data); + }); + + it('attempts to reset the remote upload stream after a chunk failure and preserves the original stage error', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'payload.bin'); + fs.writeFileSync(inputFile, Buffer.alloc(600 * 1024, 7)); + const requests: Array> = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + let frame: Record; + if (request.params.reset) { + frame = { status: 'failed', retcode: 100, wording: 'Stream reset completed', data: { type: 'error', data_type: 'error' } }; + } else if (request.params.chunk_index === 1) { + frame = { status: 'failed', retcode: 100, wording: 'disk full', data: { type: 'error', data_type: 'error' } }; + } else { + frame = { status: 'ok', retcode: 0, data: { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 2 } }; + } + return new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile })).rejects.toThrow(/upload_file_stream.*send chunk 1.*disk full/i); + expect(requests.at(-1)?.params).toMatchObject({ stream_id: requests[0].params.stream_id, reset: true }); + }); + + it('adds action and request-stage context to a stream transport failure', async () => { + const fakeFetch = (async () => { throw new Error('ECONNREFUSED'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('test_download_stream', {})).rejects.toThrow(/action test_download_stream.*connection.*ECONNREFUSED/i); + }); + + it('fails fast when automatic-upload params conflict with MCP-owned transfer fields', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'empty.bin'); + fs.writeFileSync(inputFile, ''); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', { stream_id: 'caller-owned', chunk_data: 'YQ==' }, { inputFile })) + .rejects.toThrow(/upload_file_stream.*prepare upload.*conflict.*stream_id.*chunk_data/i); + expect(fetchCalls).toBe(0); + }); + + it('uploads an empty file as one empty chunk followed by explicit completion', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'empty.bin'); + fs.writeFileSync(inputFile, ''); + const sha256 = createHash('sha256').update('').digest('hex'); + const requests: Array> = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + const data = request.params.is_complete + ? { type: 'response', status: 'file_complete', file_path: '/remote/empty.bin', file_size: 0, sha256 } + : { type: 'stream', status: 'chunk_received', received_chunks: 1, total_chunks: 1 }; + return new Response(`${JSON.stringify({ status: 'ok', retcode: 0, data })}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + const result = await client.callStream('upload_file_stream', {}, { inputFile }); + + expect(requests).toHaveLength(2); + expect(requests[0].params).toMatchObject({ chunk_data: '', chunk_index: 0, total_chunks: 1, file_size: 0 }); + expect(requests[1].params).toMatchObject({ is_complete: true, expected_sha256: sha256 }); + expect(result).toMatchObject({ file_path: '/remote/empty.bin', file_size: 0, sha256, chunk_count: 1 }); + }); + + it('rejects an upload input that resolves to a directory before any network call', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + const dir = path.join(root, 'nested'); + fs.mkdirSync(dir); + tempDirs.push(root); + let fetchCalls = 0; + const fakeFetch = (async () => { fetchCalls++; throw new Error('fetch must not run'); }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile: dir })).rejects.toThrow(/upload_file_stream.*open input.*not a regular file/i); + expect(fetchCalls).toBe(0); + }); + + it('reports a failed best-effort remote reset instead of silently dropping it', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'one.bin'); + fs.writeFileSync(inputFile, 'x'); + let calls = 0; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + calls++; + const request = JSON.parse(String(init.body)) as Record; + if (request.params.reset) throw new Error('reset connection lost'); + const frame = { status: 'failed', retcode: 100, wording: 'chunk rejected', data: { type: 'error' } }; + return new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root }); + + await expect(client.callStream('upload_file_stream', {}, { inputFile })) + .rejects.toThrow(/send chunk 0.*chunk rejected.*remote reset failed.*reset connection lost/i); + expect(calls).toBe(2); + }); + + it('rejects file_info whose declared chunk geometry exceeds the 200000-frame file cap', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const frame = { + status: 'ok', retcode: 0, + data: { type: 'stream', data_type: 'file_info', file_name: 'tiny-chunks.bin', file_size: 200_001, chunk_size: 1 }, + }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/frame 0.*file chunks.*200000/i); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('treats file_size=0 as unknown and commits a non-empty download using terminal.total_bytes', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const content = Buffer.from('unknown-size payload'); + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'unknown.bin', file_size: 0, chunk_size: 65536 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: content.length, data: content.toString('base64') } }, + { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'file_complete', total_chunks: 1, total_bytes: content.length } }, + ]; + const fakeFetch = (async () => new Response(frames.map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir }); + + const result = await client.callStream('download_file_stream', {}); + + expect(result.file_size).toBe(content.length); + expect(fs.readFileSync(result.file_path).equals(content)).toBe(true); + }); + + it('requires file_info as the first successful frame for known file-download actions', async () => { + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'unexpected' } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*frame 0.*first.*file_info/i); + }); + + it('never treats file_chunk or file_complete without file_info as a generic frame summary', async () => { + for (const dataType of ['file_chunk', 'file_complete']) { + const secret = Buffer.from(`secret-${dataType}`).toString('base64'); + const frame = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: dataType, data: secret } }; + const fakeFetch = (async () => new Response(`${JSON.stringify(frame)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch }); + + let message = ''; + try { await client.callStream('test_download_stream', {}); } catch (error) { message = String(error); } + expect(message).toMatch(/frame 0.*without file_info/i); + expect(message).not.toContain(secret); + } + }); + + it('cancels an in-flight download from the MCP signal and removes its partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const prefix = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'cancel.bin', file_size: 6, chunk_size: 3 } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_chunk', index: 0, size: 3, data: Buffer.from('abc').toString('base64') } }, + ].map((frame) => `${JSON.stringify(frame)}\r\n\r\n`).join(''); + let bodyCancelled = false; + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(prefix)); }, + cancel() { bodyCancelled = true; }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, timeoutMs: 1_000 }); + const controller = new AbortController(); + const pending = client.callStream('download_file_stream', {}, { signal: controller.signal }); + + for (let i = 0; i < 50 && !fs.readdirSync(streamDir).some((name) => name.endsWith('.part')); i++) { + await new Promise((resolve) => setImmediate(resolve)); + } + controller.abort(new Error('MCP caller cancelled')); + const outcome = await Promise.race([ + pending.then((value) => ({ value }), (error) => ({ error })), + new Promise<{ pending: true }>((resolve) => setTimeout(() => resolve({ pending: true }), 250)), + ]); + + expect(outcome).toHaveProperty('error'); + expect(String('error' in outcome ? outcome.error : '')).toMatch(/download_file_stream.*cancel.*MCP caller cancelled/i); + expect(bodyCancelled).toBe(true); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('resets the idle deadline after every frame instead of imposing an overall stream timeout', async () => { + const frames = [ + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'one' } }, + { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'data_chunk', data: 'two' } }, + { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete', data: 'done' } }, + ]; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const signal = init.signal as AbortSignal; + const body = new ReadableStream({ + start(controller) { + const timers = frames.map((frame, index) => setTimeout(() => { + controller.enqueue(new TextEncoder().encode(`${JSON.stringify(frame)}\r\n\r\n`)); + if (index === frames.length - 1) controller.close(); + }, [10, 35, 65][index])); + signal.addEventListener('abort', () => { + for (const timer of timers) clearTimeout(timer); + controller.error(signal.reason); + }, { once: true }); + }, + }); + return new Response(body, { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, timeoutMs: 40 }); + + const result = await client.callStream('test_download_stream', {}); + + expect(result).toMatchObject({ frame_count: 3, terminal: frames[2] }); + }); + + it('cancels a stalled body at the per-read idle deadline and removes the partial file', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-client-')); + tempDirs.push(streamDir); + const info = { status: 'ok', retcode: 0, data: { type: 'stream', data_type: 'file_info', file_name: 'idle.bin', file_size: 4, chunk_size: 4 } }; + let cancelled = false; + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(`${JSON.stringify(info)}\r\n\r\n`)); }, + cancel() { cancelled = true; }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, timeoutMs: 20 }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download_file_stream.*idle timeout.*20ms/i); + expect(cancelled).toBe(true); + expect(fs.readdirSync(streamDir)).toEqual([]); + }); + + it('propagates upload cancellation but performs remote reset with an independent cleanup signal', async () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-root-')); + tempDirs.push(root); + const inputFile = path.join(root, 'cancel-upload.bin'); + fs.writeFileSync(inputFile, 'x'); + const requests: Array> = []; + const signals: AbortSignal[] = []; + const fakeFetch = (async (_url: unknown, init: RequestInit) => { + const request = JSON.parse(String(init.body)) as Record; + requests.push(request); + signals.push(init.signal as AbortSignal); + if (request.params.reset) { + const reset = { status: 'failed', retcode: 100, wording: 'Stream reset completed', data: { type: 'error' } }; + return new Response(`${JSON.stringify(reset)}\r\n\r\n`, { status: 200 }); + } + return new Response(new ReadableStream({ start() {} }), { status: 200 }); + }) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, uploadRoot: root, timeoutMs: 1_000 }); + const controller = new AbortController(); + const pending = client.callStream('upload_file_stream', {}, { inputFile, signal: controller.signal }); + for (let i = 0; i < 50 && requests.length === 0; i++) await new Promise((resolve) => setImmediate(resolve)); + + controller.abort(new Error('cancel automatic upload')); + const outcome = await Promise.race([ + pending.then((value) => ({ value }), (error) => ({ error })), + new Promise<{ pending: true }>((resolve) => setTimeout(() => resolve({ pending: true }), 250)), + ]); + + expect(outcome).toHaveProperty('error'); + expect(String('error' in outcome ? outcome.error : '')).toMatch(/upload_file_stream.*cancel automatic upload/i); + expect(requests.at(-1)?.params).toMatchObject({ reset: true, stream_id: requests[0].params.stream_id }); + expect(signals).toHaveLength(2); + expect(signals[1]).not.toBe(controller.signal); + expect(signals[1].aborted).toBe(false); + }); + + it('limits each client to four top-level active Stream Actions', async () => { + const resolvers: Array<(response: Response) => void> = []; + const fakeFetch = (async () => new Promise((resolve) => { resolvers.push(resolve); })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, timeoutMs: 1_000 }); + const active = Array.from({ length: 4 }, () => client.callStream('test_download_stream', {})); + const fifth = client.callStream('test_download_stream', {}); + const fifthOutcomePromise = fifth.then((value) => ({ value }), (error) => ({ error })); + await new Promise((resolve) => setImmediate(resolve)); + const startedRequests = resolvers.length; + const terminal = { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } }; + for (const resolve of resolvers) { + resolve(new Response(`${JSON.stringify(terminal)}\r\n\r\n`, { status: 200 })); + } + const fifthOutcome = await fifthOutcomePromise; + await Promise.all(active); + + expect(startedRequests).toBe(4); + expect(fifthOutcome).toHaveProperty('error'); + expect(String('error' in fifthOutcome ? fifthOutcome.error : '')).toMatch(/active Stream Action.*limit.*4/i); + }); + + it('enforces the download-directory quota and reserves maxStreamBytes for unknown-size files', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-quota-')); + tempDirs.push(streamDir); + fs.writeFileSync(path.join(streamDir, 'existing.bin'), Buffer.alloc(11)); + const info = { + status: 'ok', retcode: 0, + data: { type: 'stream', data_type: 'file_info', file_name: 'unknown.bin', file_size: 0, chunk_size: 4 }, + }; + const fakeFetch = (async () => new Response(`${JSON.stringify(info)}\r\n\r\n`, { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, maxStreamBytes: 10 }); + + await expect(client.callStream('download_file_stream', {})).rejects.toThrow(/download directory quota.*20.*existing.*11.*reserve.*10/i); + expect(fs.readdirSync(streamDir)).toEqual(['existing.bin']); + }); + + it('includes in-process reservations when admitting concurrent downloads', async () => { + const streamDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-mcp-quota-')); + tempDirs.push(streamDir); + fs.writeFileSync(path.join(streamDir, 'existing.bin'), Buffer.alloc(1)); + const info = { + status: 'ok', retcode: 0, + data: { type: 'stream', data_type: 'file_info', file_name: 'pending.bin', file_size: 0, chunk_size: 4 }, + }; + const fakeFetch = (async () => new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(`${JSON.stringify(info)}\r\n\r\n`)); }, + }), { status: 200 })) as unknown as typeof fetch; + const client = makeHttpClient({ endpoint: 'http://127.0.0.1:9999/', fetch: fakeFetch, streamDir, maxStreamBytes: 10, timeoutMs: 1_000 }); + const firstController = new AbortController(); + const first = client.callStream('download_file_stream', { id: 1 }, { signal: firstController.signal }); + const firstOutcome = first.then((value) => ({ value }), (error) => ({ error })); + for (let i = 0; i < 50 && !fs.readdirSync(streamDir).some((name) => name.endsWith('.part')); i++) { + await new Promise((resolve) => setImmediate(resolve)); + } + + await expect(client.callStream('download_file_stream', { id: 2 })).rejects.toThrow(/quota.*reserved=10.*reserve=10/i); + firstController.abort(new Error('test cleanup')); + await firstOutcome; + expect(fs.readdirSync(streamDir)).toEqual(['existing.bin']); + }); }); diff --git a/packages/mcp/tests/tools.test.ts b/packages/mcp/tests/tools.test.ts index 800d4c23..142d6479 100644 --- a/packages/mcp/tests/tools.test.ts +++ b/packages/mcp/tests/tools.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from 'vitest'; -import { computeTools, callTool } from '../src/tools'; -import type { ActionClient, OneBotEnvelope } from '../src/client'; +import { computeTools, callTool, parseMode } from '../src/tools'; +import type { ActionClient, OneBotEnvelope, StreamCallOptions, StreamCallResult } from '../src/client'; type Res = Awaited>; function text(res: Res): string { @@ -13,13 +13,28 @@ function parsed(res: Res): any { /** A fake ActionClient — no transport. Records the last call and returns a * canned envelope (overridable per test). */ -function fakeClient(impl?: (action: string, params: Record) => OneBotEnvelope): ActionClient { +function fakeClient( + impl?: (action: string, params: Record) => OneBotEnvelope, + streamImpl?: (action: string, params: Record, options?: StreamCallOptions) => StreamCallResult, +): ActionClient { return { call: async (action, params) => impl?.(action, params) ?? { status: 'ok', retcode: 0, data: { action, params } }, + callStream: async (action, params, options) => streamImpl?.(action, params, options) ?? { + frame_count: 1, + frames: [], + terminal: { status: 'ok', retcode: 0, data: { type: 'response', action, params } }, + }, }; } describe('computeTools — mode gating', () => { + it('fails fast on an invalid SNOWLUMA_MCP_MODE', () => { + expect(parseMode(undefined)).toBeUndefined(); + expect(parseMode('WRITE')).toBe('write'); + for (const invalid of ['', 'unsafe', 'reader']) { + expect(() => parseMode(invalid), invalid).toThrow(/SNOWLUMA_MCP_MODE/); + } + }); it('docs mode exposes only the 4 catalog tools', () => { expect(computeTools('docs').map((t) => t.name)).toEqual([ 'list_actions', 'get_action', 'search_actions', 'list_categories', @@ -100,6 +115,7 @@ describe('callTool — invoke_action (write)', () => { seen = { action, params }; return { status: 'ok', retcode: 0, data: { message_id: 42 } }; }, + callStream: async () => { throw new Error('unexpected stream call'); }, }; const res = await callTool('invoke_action', { action: 'send_group_msg', params: { group_id: 1, message: 'hi' } }, { mode: 'write', client }); expect(res.isError).toBeFalsy(); @@ -120,7 +136,10 @@ describe('callTool — invoke_action (write)', () => { expect(parsed(res).wording).toBe('未找到'); }); it('maps a transport-level throw to isError', async () => { - const client: ActionClient = { call: async () => { throw new Error('connection refused'); } }; + const client: ActionClient = { + call: async () => { throw new Error('connection refused'); }, + callStream: async () => { throw new Error('unexpected stream call'); }, + }; const res = await callTool('invoke_action', { action: 'send_group_msg', params: {} }, { mode: 'write', client }); expect(res.isError).toBe(true); expect(text(res)).toContain('调用失败'); @@ -135,4 +154,66 @@ describe('callTool — invoke_action (write)', () => { expect(res.isError).toBe(true); expect(text(res)).toContain('未知 action'); }); + + it('routes catalog Stream Actions through callStream and returns the bounded summary', async () => { + let ordinaryCalls = 0; + let streamCalls = 0; + const terminal = { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } }; + const client: ActionClient = { + call: async () => { ordinaryCalls++; return { status: 'ok', retcode: 0 }; }, + callStream: async (action, params) => { + streamCalls++; + expect(action).toBe('test_download_stream'); + expect(params).toEqual({ error: false }); + return { frame_count: 1, frames: [], terminal }; + }, + }; + + const res = await callTool('invoke_action', { action: 'test_download_stream', params: { error: false } }, { mode: 'write', client }); + + expect(res.isError).toBeFalsy(); + expect(parsed(res)).toEqual({ frame_count: 1, frames: [], terminal }); + expect(streamCalls).toBe(1); + expect(ordinaryCalls).toBe(0); + }); + + it('passes execution.input_file only as an MCP upload option, never as OneBot params', async () => { + let seen: { params: Record; inputFile?: string } | undefined; + const client = fakeClient(undefined, (_action, params, options) => { + seen = { params, inputFile: options?.inputFile }; + return { + file_path: '/remote/local.txt', file_size: 5, sha256: 'abc', chunk_count: 1, stream_id: 'id', + terminal: { status: 'ok', retcode: 0, data: { type: 'response', status: 'file_complete' } }, + }; + }); + + const res = await callTool('invoke_action', { + action: 'upload_file_stream', + params: { file_retention: 0 }, + execution: { input_file: '/allowed/local.txt' }, + }, { mode: 'write', client }); + + expect(res.isError).toBeFalsy(); + expect(seen).toEqual({ params: { file_retention: 0 }, inputFile: '/allowed/local.txt' }); + }); + + it('forwards MCP request cancellation to Stream Action execution', async () => { + const controller = new AbortController(); + let seenSignal: AbortSignal | undefined; + const client = fakeClient(undefined, (_action, _params, options) => { + seenSignal = options?.signal; + return { + frame_count: 1, + frames: [], + terminal: { status: 'ok', retcode: 0, data: { type: 'response', data_type: 'data_complete' } }, + }; + }); + + const res = await callTool('invoke_action', { action: 'test_download_stream', params: {} }, { + mode: 'write', client, signal: controller.signal, + }); + + expect(res.isError).toBeFalsy(); + expect(seenSignal).toBe(controller.signal); + }); }); diff --git a/packages/onebot/package.json b/packages/onebot/package.json index d1f49fe8..eab29acb 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.12.0", + "version": "1.12.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/onebot/src/action-docs.ts b/packages/onebot/src/action-docs.ts index 77f121e4..ef485160 100644 --- a/packages/onebot/src/action-docs.ts +++ b/packages/onebot/src/action-docs.ts @@ -4,27 +4,28 @@ // structured doc list + a Markdown view. The metadata is carried on the same // values that drive runtime validation, so docs cannot drift from behavior. // -// Coverage note: the ~15 genuinely irregular actions in `actions/extended.ts` -// that remain on the legacy `h.registerAction(...)` path are NOT ActionSpecs -// and so do not appear here — that is the documented irregular tail. +// The reserved `.handle_quick_operation` raw handler deliberately has no +// ActionSpec/doc entry; every catalogued action comes from ACTION_REGISTRY. // // The serving SURFACE (WebUI panel / OpenAPI export / static markdown) is a // deferred product decision; this module produces format-agnostic data plus a // Markdown default. Point any renderer at `collectActionDocs()`. import type { ActionDoc } from './action-kit'; -import { ACTION_GROUPS } from './actions'; +import { ACTION_REGISTRY } from './actions'; /** Every declarative action's doc (with category), sorted by name. */ export function collectActionDocs(): ActionDoc[] { - return ACTION_GROUPS - .flatMap(({ category, actions }) => actions.map((s) => ({ ...s.describe(), category }))) + return ACTION_REGISTRY.actions + // Preserve the collector's value semantics: callers may sort/transform + // docs without mutating the process-wide compiled registry. + .map(({ doc }) => structuredClone(doc)) .sort((a, b) => a.name.localeCompare(b.name)); } /** Distinct categories with action counts. */ export function collectCategories(): Array<{ category: string; count: number }> { - return ACTION_GROUPS.map(({ category, actions }) => ({ category, count: actions.length })); + return ACTION_REGISTRY.categories.map(({ category, count }) => ({ category, count })); } function paramRow(p: ActionDoc['params'][number]): string { @@ -57,7 +58,7 @@ export function renderActionDocsMarkdown(docs: readonly ActionDoc[] = collectAct '# OneBot Actions', '', '> 由 `packages/onebot/src/action-docs.ts` 从各 `ActionSpec.describe()` 自动生成,请勿手改。', - '> 仅覆盖声明式 action;`extended.ts` 中少量走 legacy `registerAction` 的不规则 action 不在此列。', + '> 覆盖完整声明式 Action registry;保留的 raw `.handle_quick_operation` handler 不生成文档。', '', `共 ${docs.length} 个声明式 action。`, '', diff --git a/packages/onebot/src/action-kit.ts b/packages/onebot/src/action-kit.ts index a06207ce..14bf0efb 100644 --- a/packages/onebot/src/action-kit.ts +++ b/packages/onebot/src/action-kit.ts @@ -447,12 +447,18 @@ type Handler = (params: JsonObject) => Promise; * both kinds in one flat list without coupling to either concrete generic. */ export interface RegisteredActionSpec { + /** Runtime dispatch kind. Kept on the spec so the compiled registry can + * validate the executable namespace without inferring behavior from docs. */ + readonly kind: 'normal' | 'stream'; + /** Canonical name first, followed by every executable alias. */ + readonly names: readonly string[]; describe(): ActionDoc; register(h: ApiHandler, ctx: ApiActionContext): void; } export interface ActionSpec extends RegisteredActionSpec { - readonly names: string[]; + readonly kind: 'normal'; + readonly names: readonly string[]; readonly params: S; /** Pure: coerce + validate + cross-field, no ctx, no I/O. The test surface. */ parse(raw: JsonObject): CoerceResult>; @@ -482,7 +488,7 @@ interface ActionDef { const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason); export function defineAction(def: ActionDef): ActionSpec { - const names = typeof def.name === 'string' ? [def.name] : [...def.name]; + const names = Object.freeze(typeof def.name === 'string' ? [def.name] : [...def.name]); const rules: readonly CrossFieldRule[] = def.rules ? def.rules(RULES as unknown as RuleBuilders>) : []; @@ -510,6 +516,7 @@ export function defineAction(def: ActionDef): ActionSpec { }; return { + kind: 'normal', names, params: def.params, parse, @@ -567,7 +574,8 @@ interface StreamActionDef { } export interface StreamActionSpec extends RegisteredActionSpec { - readonly names: string[]; + readonly kind: 'stream'; + readonly names: readonly string[]; readonly params: S; parse(raw: JsonObject): CoerceResult>; } @@ -587,6 +595,7 @@ export function defineStreamAction(def: StreamActionDef): Str }); return { + kind: 'stream', names: base.names, params: def.params, parse: base.parse, diff --git a/packages/onebot/src/actions/index.ts b/packages/onebot/src/actions/index.ts index 5fbd5e92..3a79035f 100644 --- a/packages/onebot/src/actions/index.ts +++ b/packages/onebot/src/actions/index.ts @@ -1,15 +1,13 @@ -// 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. +// Action registry — the single source of the executable OneBot namespace. // -// "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). +// ACTION_GROUPS is the authored input. ACTION_REGISTRY compiles it exactly +// once at module initialization, validating canonical names, aliases, stream +// classification, and the reserved raw-action namespace before any +// ApiHandler can start. Runtime registration and generated docs are projections +// of that same compiled value; neither is allowed to rebuild its own list. -import type { RegisteredActionSpec } from '../action-kit'; +import type { ActionDoc, RegisteredActionSpec } from '../action-kit'; +import type { ApiActionContext, ApiHandler } from '../api-handler'; import { actions as infoActions } from './info'; import { actions as messageActions } from './message'; import { actions as friendActions } from './friend'; @@ -29,7 +27,164 @@ export interface ActionGroup { readonly actions: readonly RegisteredActionSpec[]; } -/** Every action, grouped by domain category. The single source of truth. */ +export interface RawActionReservation { + /** Executable wire name reserved for a handler that cannot be an ActionSpec. */ + readonly name: string; + /** Diagnostic owner. Usually identical to name; explicit for conflict logs. */ + readonly canonical: string; +} + +export type CompiledActionKind = RegisteredActionSpec['kind'] | 'raw'; +export type ActionNameRole = 'canonical' | 'alias' | 'raw'; + +export interface CompiledAction { + readonly canonical: string; + readonly names: readonly string[]; + readonly kind: RegisteredActionSpec['kind']; + readonly category: string; + readonly doc: ActionDoc; + readonly spec: RegisteredActionSpec; +} + +interface ActionNameClaimBase { + readonly name: string; + readonly canonical: string; + readonly kind: CompiledActionKind; + readonly role: ActionNameRole; +} + +export interface CompiledDeclarativeName extends ActionNameClaimBase { + readonly kind: RegisteredActionSpec['kind']; + readonly role: 'canonical' | 'alias'; + readonly action: CompiledAction; +} + +export interface CompiledRawName extends ActionNameClaimBase { + readonly kind: 'raw'; + readonly role: 'raw'; +} + +export type CompiledActionName = CompiledDeclarativeName | CompiledRawName; + +export interface CompiledActionRegistry { + /** Canonical declarative actions in authored group/action order. */ + readonly actions: readonly CompiledAction[]; + /** Every executable name, including aliases and reserved raw handlers. */ + readonly executableNames: readonly CompiledActionName[]; + /** Category order/counts used by the docs and UI. */ + readonly categories: readonly { category: string; count: number }[]; + readonly rawActions: readonly CompiledRawName[]; + resolve(name: string): CompiledActionName | undefined; + register(h: ApiHandler, ctx: ApiActionContext): void; +} + +function validateSpecProjection(spec: RegisteredActionSpec, doc: ActionDoc): void { + const canonical = spec.names[0]; + if (!canonical || canonical.trim() === '') { + throw new Error(`Action registry invalid ${spec.kind} action: canonical name must not be empty`); + } + for (const name of spec.names) { + if (name.trim() === '') { + throw new Error(`Action registry invalid ${spec.kind} action canonical "${canonical}": executable name must not be empty`); + } + } + + const aliases = spec.names.slice(1); + if (doc.name !== canonical || doc.aliases.length !== aliases.length || doc.aliases.some((name, i) => name !== aliases[i])) { + throw new Error( + `Action registry invalid ${spec.kind} action canonical "${canonical}": describe() names do not match executable names`, + ); + } + const documentedKind = doc.stream === true ? 'stream' : 'normal'; + if (documentedKind !== spec.kind) { + throw new Error( + `Action registry invalid ${spec.kind} action canonical "${canonical}": describe() reports kind ${documentedKind}`, + ); + } +} + +function conflictMessage(name: string, first: CompiledActionName, second: CompiledActionName): string { + return [ + `Action registry conflict for executable name "${name}"`, + `canonical "${first.canonical}" (name "${first.name}", kind ${first.kind}, role ${first.role})`, + `canonical "${second.canonical}" (name "${second.name}", kind ${second.kind}, role ${second.role})`, + ].join(': '); +} + +/** Compile and validate a complete executable namespace. Exported so the + * conflict matrix can be tested without constructing an ApiHandler. */ +export function compileActionRegistry( + groups: readonly ActionGroup[], + rawReservations: readonly RawActionReservation[] = [], +): CompiledActionRegistry { + const actions: CompiledAction[] = []; + const executableNames: CompiledActionName[] = []; + const rawActions: CompiledRawName[] = []; + const byName = new Map(); + + const claim = (next: CompiledActionName): void => { + const previous = byName.get(next.name); + if (previous) throw new Error(conflictMessage(next.name, previous, next)); + byName.set(next.name, next); + executableNames.push(next); + }; + + for (const group of groups) { + for (const spec of group.actions) { + const described = spec.describe(); + validateSpecProjection(spec, described); + const canonical = spec.names[0]!; + const action: CompiledAction = Object.freeze({ + canonical, + names: Object.freeze([...spec.names]), + kind: spec.kind, + category: group.category, + doc: Object.freeze({ ...described, category: group.category }), + spec, + }); + actions.push(action); + action.names.forEach((name, index) => claim(Object.freeze({ + name, + canonical, + kind: action.kind, + role: index === 0 ? 'canonical' : 'alias', + action, + }))); + } + } + + for (const reservation of rawReservations) { + if (reservation.name.trim() === '' || reservation.canonical.trim() === '') { + throw new Error('Action registry invalid raw action: canonical and executable name must not be empty'); + } + const raw: CompiledRawName = Object.freeze({ + name: reservation.name, + canonical: reservation.canonical, + kind: 'raw', + role: 'raw', + }); + claim(raw); + rawActions.push(raw); + } + + const categories = groups.map(({ category, actions: groupActions }) => Object.freeze({ + category, + count: groupActions.length, + })); + + return Object.freeze({ + actions: Object.freeze(actions), + executableNames: Object.freeze(executableNames), + categories: Object.freeze(categories), + rawActions: Object.freeze(rawActions), + resolve: (name: string) => byName.get(name), + register: (h: ApiHandler, ctx: ApiActionContext) => { + for (const action of actions) action.spec.register(h, ctx); + }, + }); +} + +/** Every declarative action, grouped by domain category. Authored input. */ export const ACTION_GROUPS: readonly ActionGroup[] = [ { category: '信息', actions: infoActions }, { category: '消息', actions: messageActions }, @@ -44,5 +199,11 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [ { 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); +/** The sole non-ActionSpec handler; reserved in the same namespace up front. */ +export const HANDLE_QUICK_OPERATION_ACTION = '.handle_quick_operation'; +export const RAW_ACTION_RESERVATIONS: readonly RawActionReservation[] = [ + { name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION }, +]; + +/** Complete, validated runtime/docs registry. Compilation happens on import. */ +export const ACTION_REGISTRY = compileActionRegistry(ACTION_GROUPS, RAW_ACTION_RESERVATIONS); diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index b1aca91d..e92c34c8 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -52,13 +52,17 @@ export const actions = [ auto_escape: f.bool().default(false), }, run: async (p, ctx) => { - if (p.message_type === 'group' || p.group_id !== undefined) { + // Group temp-session reply: message_type=private with BOTH a user_id and + // a group_id (the source group). Detect it first so a group_id here + // doesn't get misrouted to a group message. + const isTempReply = p.message_type === 'private' && p.user_id !== undefined && p.group_id !== undefined; + if (!isTempReply && (p.message_type === 'group' || p.group_id !== undefined)) { if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape); return okResponse({ message_id: result.messageId }); } if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape); + const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, isTempReply ? p.group_id : undefined); return okResponse({ message_id: result.messageId }); }, }), @@ -67,9 +71,19 @@ export const actions = [ name: 'send_private_msg', summary: '发送私聊消息', returns: '{ message_id: number }', - params: { user_id: f.userId(), message: f.message(), auto_escape: f.bool().default(false) }, + params: { + user_id: f.userId(), + message: f.message(), + // Optional source group: reply into that group's temp session (临时会话) + // instead of a friend chat. int({min:0}) rather than groupId (which + // rejects 0): a client that fills every field with group_id:0 must keep + // working as a plain private send, so 0/absent means "no temp session". + group_id: f.int({ min: 0 }).optional(), + auto_escape: f.bool().default(false), + }, run: async (p, ctx) => { - const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape); + const tempGroupId = p.group_id && p.group_id > 0 ? p.group_id : undefined; + const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, tempGroupId); return okResponse({ message_id: result.messageId }); }, }), diff --git a/packages/onebot/src/actions/request.ts b/packages/onebot/src/actions/request.ts index 1a386a3e..6a6e4576 100644 --- a/packages/onebot/src/actions/request.ts +++ b/packages/onebot/src/actions/request.ts @@ -20,6 +20,7 @@ export const actions = [ name: 'set_group_add_request', summary: '处理加群请求', params: { + // Opaque handle from the original request event; callers must echo it. flag: f.string({ allowEmpty: false }), // sub_type/type pass through with a nested fallback (sub_type → type → 'add'); // kept raw so the original asString resolution is preserved verbatim. @@ -35,4 +36,3 @@ export const actions = [ }, }), ]; - diff --git a/packages/onebot/src/api-handler.ts b/packages/onebot/src/api-handler.ts index ab121eeb..0fb39ae9 100644 --- a/packages/onebot/src/api-handler.ts +++ b/packages/onebot/src/api-handler.ts @@ -1,8 +1,13 @@ 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 { ALL_ACTIONS } from './actions'; -import { registerActions } from './action-kit'; +import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; +import { + ACTION_REGISTRY, + HANDLE_QUICK_OPERATION_ACTION, + type CompiledActionKind, + type CompiledActionRegistry, +} from './actions'; import type { ForwardPreviewMeta } from './modules/message-actions'; import type { JsonObject, JsonValue, MessageMeta } from './types'; import { RETCODE, failedResponse, okResponse } from './types'; @@ -32,7 +37,7 @@ export interface ApiActionContext { isOnline: () => boolean; getMessage: (messageId: number) => JsonObject | null; getMessageMeta: (messageId: number) => MessageMeta | null; - sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean) => Promise; + sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise; sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise; deleteMessage: (messageId: number, meta: MessageMeta) => Promise; canSendImage: () => boolean; @@ -75,6 +80,12 @@ export interface ApiActionContext { type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise; +interface RegisteredHandler { + readonly handler: ActionHandler; + readonly canonical: string; + readonly kind: CompiledActionKind; +} + /** A handled-action record handed to debug observers. */ export interface ActionRecord { action: string; @@ -85,10 +96,15 @@ export interface ActionRecord { export type ActionObserver = (rec: ActionRecord) => void; export class ApiHandler { - private readonly handlers = new Map(); - /** Names that answer with a multi-frame Stream API response (#163). The - * network adapter consults this BEFORE dispatch to pick streaming output. */ - private readonly streamActions = new Set(); + /** Handler + dispatch kind live in one record so stream classification can + * never outlive or drift from the handler it describes. */ + private readonly handlers = new Map(); + private readonly registry: CompiledActionRegistry; + private registrationOpen = true; + /** Sticky instance-lifecycle gate. A failed transport close may restore its + * own listener for retry, but it must never reopen execution against a + * retiring Bridge/store generation. */ + private acceptingActions = true; private readonly log: Logger; /** Debug-stream taps — notified after every handled action. Attached * on-demand (ref-counted) by the WebUI debug stream. */ @@ -100,43 +116,129 @@ export class ApiHandler { return () => { this.observers.delete(cb); }; } - constructor(context: ApiActionContext, uin?: number) { + constructor( + context: ApiActionContext, + uin?: number, + registry: CompiledActionRegistry = ACTION_REGISTRY, + ) { + this.registry = registry; this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog; - registerActions(this, context, ALL_ACTIONS); + try { + registry.register(this, context); - // 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(); - }); + // 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.registerRawAction(HANDLE_QUICK_OPERATION_ACTION, 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(); + }); + this.assertRegistryFullyBound(); + } finally { + // registerAction/registerStreamAction are the constructor-time port used + // by ActionSpec. Once construction finishes (successfully or not), the + // runtime namespace is immutable and cannot bypass the compiled registry. + this.registrationOpen = false; + } } registerAction(action: string, handler: ActionHandler): void { - this.handlers.set(action, handler); + this.registerHandler(action, handler, 'normal'); } /** Register a Stream API action — dispatched exactly like a normal action, * but flagged so adapters stream its frames (the handler receives a sink). */ registerStreamAction(action: string, handler: ActionHandler): void { - this.handlers.set(action, handler); - this.streamActions.add(action); + this.registerHandler(action, handler, 'stream'); + } + + private registerRawAction(action: string, handler: ActionHandler): void { + this.registerHandler(action, handler, 'raw'); + } + + private registerHandler(action: string, handler: ActionHandler, kind: CompiledActionKind): void { + if (!this.registrationOpen) { + throw new Error( + `Action registry is sealed; cannot register canonical "${action}" (name "${action}", kind ${kind})`, + ); + } + const claim = this.registry.resolve(action); + if (!claim) { + throw new Error( + `Action registration is not declared by the compiled registry: ` + + `canonical "${action}" (name "${action}", kind ${kind})`, + ); + } + const canonical = claim.canonical; + const existing = this.handlers.get(action); + if (existing) { + throw new Error( + `Action handler conflict for executable name "${action}": ` + + `canonical "${existing.canonical}" (name "${action}", kind ${existing.kind}) conflicts with ` + + `canonical "${canonical}" (name "${action}", kind ${kind})`, + ); + } + if (claim.kind !== kind) { + throw new Error( + `Action handler kind mismatch for canonical "${canonical}" (name "${action}"): ` + + `registry kind ${claim.kind}, registration kind ${kind}`, + ); + } + this.handlers.set(action, { handler, canonical, kind }); + } + + private assertRegistryFullyBound(): void { + for (const claim of this.registry.executableNames) { + if (this.handlers.has(claim.name)) continue; + throw new Error( + `Action registry claim has no handler: canonical "${claim.canonical}" ` + + `(name "${claim.name}", kind ${claim.kind})`, + ); + } + if (this.handlers.size !== this.registry.executableNames.length) { + throw new Error( + `Action registry binding count mismatch: ${this.handlers.size} handlers for ` + + `${this.registry.executableNames.length} executable names`, + ); + } } /** Whether `action` answers with a multi-frame Stream API response. */ isStreamAction(action: string): boolean { - return this.streamActions.has(action); + return this.handlers.get(action)?.kind === 'stream'; + } + + /** Whether the owning OneBot instance still accepts new Action execution. */ + get isAcceptingActions(): boolean { + return this.acceptingActions; + } + + /** Permanently reject new Actions for this handler generation. + * + * Existing calls have already been admitted and are drained by their owning + * transport/instance. There is intentionally no resume operation: hot reload + * keeps the same live generation open, while teardown creates a new handler + * only after the previous generation has fully retired. */ + quiesce(): void { + if (!this.acceptingActions) return; + this.acceptingActions = false; + this.log.info('Action ingress quiesced'); } async handle(action: string, params: JsonObject, sink?: StreamSink): Promise { - const handler = this.handlers.get(action); - if (!handler) { + if (!this.acceptingActions) { + const response = failedResponse(RETCODE.ACTION_FAILED, 'OneBot instance is shutting down'); + this.log.warn('rejected Action %s after instance quiesce', action); + this.notifyObservers(action, params, response, 0); + return response; + } + const registered = this.handlers.get(action); + if (!registered) { this.log.debug('unknown action %s', action); return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action'); } @@ -146,9 +248,9 @@ export class ApiHandler { // the wrap + id allocation when trace is actually live, so the default // path stays allocation-free. if (getLogLevel() !== 'trace') { - return this.runAction(action, handler, params, sink); + return this.runAction(action, registered.handler, params, sink); } - return runWithRequestId(nextRequestId(), () => this.runAction(action, handler, params, sink)); + return runWithRequestId(nextRequestId(), () => this.runAction(action, registered.handler, params, sink)); } private async runAction( @@ -170,23 +272,23 @@ export class ApiHandler { response = await handler(params, sink); this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]); } catch (error) { - // 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. + // Single error seam: typed message-contract failures are caller errors + // and therefore map to BAD_REQUEST. Bridge/OIDB business failures and + // unexpected internal faults retain the shared ACTION_FAILED policy. + // Action `run` bodies should not hand-roll their own catch/response + // mapping: central classification keeps every transport consistent. + // `OidbError.message` already carries the QQ server code, so it needs no + // special casing. warn (not error) keeps the log file useful 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 : String(error); - response = failedResponse(RETCODE.ACTION_FAILED, message); + const retcode = error instanceof MessageElementValidationError + ? RETCODE.BAD_REQUEST + : RETCODE.ACTION_FAILED; + response = failedResponse(retcode, message); } this.notifyObservers(action, params, response, Date.now() - startedAt); return response; @@ -218,22 +320,24 @@ export class ApiHandler { emit: (json: string) => void | Promise, isAlive?: () => boolean, ): Promise { - const bad = (): void => { void emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))); }; - if (!rawRequest.trim()) { bad(); return; } + const bad = (): Promise => Promise.resolve( + emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))), + ); + if (!rawRequest.trim()) { await bad(); return; } let action: string; let params: JsonObject; let echo: JsonValue | undefined; try { const parsed = JSON.parse(rawRequest) as unknown; - if (!isJsonObject(parsed)) { bad(); return; } + if (!isJsonObject(parsed)) { await bad(); return; } const a = asString(parsed.action); - if (!a) { bad(); return; } + if (!a) { await bad(); return; } action = a; params = isJsonObject(parsed.params) ? parsed.params : {}; echo = parsed.echo !== undefined ? toJsonValue(parsed.echo) : undefined; } catch { - bad(); + await bad(); return; } diff --git a/packages/onebot/src/config.ts b/packages/onebot/src/config.ts index 94833dd8..45acb727 100644 --- a/packages/onebot/src/config.ts +++ b/packages/onebot/src/config.ts @@ -21,6 +21,8 @@ const log = createLogger('OneBot.Config'); const CONFIG_DIR = 'config'; const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json'); const DEFAULT_ACCESS_TOKEN_BYTES = 32; +const NODE_TIMER_MAX_MS = 2_147_483_647; +const PER_UIN_SNAPSHOT_MARKER = 'snapshot'; const DEFAULT_STATUS_COMMAND: StatusCommandConfig = { enabled: true, @@ -75,31 +77,243 @@ export interface LoadOneBotConfigOptions { persistDefaults?: boolean; } +/** A deterministic configuration error. Callers may safely return this as a + * 4xx without conflating it with filesystem/runtime failures. */ +export class OneBotConfigValidationError extends Error { + constructor(message: string) { + super(message); + this.name = 'OneBotConfigValidationError'; + } +} + export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig { ensureConfigDir(); const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH); - const perUinRaw = tryLoadJson(perUinPath); + // A per-account desired config is authoritative state. Corruption must stop + // startup instead of silently reviving global/default endpoints. + const perUinRaw = tryLoadJson(perUinPath, true); const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw); const sources: JsonObject[] = []; - if (globalRaw) sources.push(globalRaw); + const isCanonicalSnapshot = perUinRaw?.mode === PER_UIN_SNAPSHOT_MARKER; + if (globalRaw && !isCanonicalSnapshot) sources.push(globalRaw); if (perUinRaw) sources.push(perUinRaw); const config = fromJson(sources, !perUinRaw && !globalRaw); if (options.persistDefaults && (!perUinRaw || legacy)) { - saveOneBotConfig(uin, config); + saveOneBotConfig(uin, config, { mode: globalRaw ? 'overlay' : 'snapshot' }); } return config; } -export function saveOneBotConfig(uin: string, config: OneBotConfig): void { +export interface SaveOneBotConfigOptions { + /** Snapshot is the WebUI/user-save contract. Overlay is reserved for the + * automatic legacy/global-default materialization path. */ + mode?: 'snapshot' | 'overlay'; +} + +export function saveOneBotConfig( + uin: string, + config: OneBotConfig, + options: SaveOneBotConfigOptions = {}, +): void { + assertValidOneBotConfig(config); ensureConfigDir(); const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); - saveJson(perUinPath, toJsonObject(config)); + saveJson(perUinPath, toJsonObject(config, options.mode ?? 'snapshot')); +} + +/** Validate the normalized, public OneBot configuration shape before it is + * persisted or compiled into a live network plan. Adapter names form one + * process-wide namespace per account, not four independent namespaces. */ +export function assertValidOneBotConfig(value: unknown): asserts value is OneBotConfig { + if (!isObject(value)) invalid('configuration must be an object'); + if (!isObject(value.networks)) invalid('networks must be an object'); + + const seen = new Map(); + const serverBindings = new Map(); + validateNetworkList(value.networks, 'httpServers', seen, (item, at) => { + validateServer(item, at); + validateServerBinding(item, at, serverBindings); + }); + validateNetworkList(value.networks, 'httpClients', seen, (item, at) => { + validateClient(item, at, new Set(['http:', 'https:'])); + if ( + item.timeoutMs !== undefined && + ( + typeof item.timeoutMs !== 'number' || + !Number.isSafeInteger(item.timeoutMs) || + item.timeoutMs <= 0 || + item.timeoutMs > NODE_TIMER_MAX_MS + ) + ) { + invalid(`${at}.timeoutMs must be an integer between 1 and ${NODE_TIMER_MAX_MS}`); + } + }); + validateNetworkList(value.networks, 'wsServers', seen, (item, at) => { + validateServer(item, at); + validateServerBinding(item, at, serverBindings); + validateRole(item.role, `${at}.role`); + }); + validateNetworkList(value.networks, 'wsClients', seen, (item, at) => { + validateClient(item, at, new Set(['ws:', 'wss:'])); + validateRole(item.role, `${at}.role`); + if ( + item.reconnectIntervalMs !== undefined && + ( + typeof item.reconnectIntervalMs !== 'number' || + !Number.isSafeInteger(item.reconnectIntervalMs) || + item.reconnectIntervalMs < 1000 || + item.reconnectIntervalMs > NODE_TIMER_MAX_MS + ) + ) { + invalid(`${at}.reconnectIntervalMs must be an integer between 1000 and ${NODE_TIMER_MAX_MS}`); + } + }); + + if (!isObject(value.statusCommand)) invalid('statusCommand must be an object'); + const status = value.statusCommand; + if (typeof status.enabled !== 'boolean') invalid('statusCommand.enabled must be a boolean'); + if (typeof status.swallow !== 'boolean') invalid('statusCommand.swallow must be a boolean'); + if ( + typeof status.cooldownSeconds !== 'number' || + !Number.isInteger(status.cooldownSeconds) || + status.cooldownSeconds < 0 + ) { + invalid('statusCommand.cooldownSeconds must be a non-negative integer'); + } + if ( + typeof status.trigger !== 'string' || + !status.trigger.trim() || + status.trigger.length > STATUS_COMMAND_TRIGGER_MAX_LENGTH || + /[\r\n]/.test(status.trigger) + ) { + invalid(`statusCommand.trigger must be non-empty, single-line, and <= ${STATUS_COMMAND_TRIGGER_MAX_LENGTH} characters`); + } + + if (value.notifications !== undefined) { + if (!isObject(value.notifications) || !Array.isArray(value.notifications.channelIds)) { + invalid('notifications.channelIds must be an array'); + } + for (const [index, channelId] of value.notifications.channelIds.entries()) { + if (typeof channelId !== 'string' || !channelId || channelId.length > 64 || !/^[\w.-]+$/.test(channelId)) { + invalid(`notifications.channelIds[${index}] is invalid`); + } + } + } +} + +function validateNetworkList( + networks: JsonObject, + kind: keyof OneBotNetworks, + seen: Map, + validateSpecific: (item: JsonObject, at: string) => void, +): void { + const list = networks[kind]; + if (!Array.isArray(list)) invalid(`networks.${kind} must be an array`); + for (let index = 0; index < list.length; index += 1) { + const item = list[index]; + const at = `networks.${kind}[${index}]`; + if (!isObject(item)) invalid(`${at} must be an object`); + validateNetworkBase(item, at); + const name = item.name as string; + const previousKind = seen.get(name); + if (previousKind !== undefined) { + invalid(`network adapter name "${name}" is duplicated in ${previousKind} and ${kind}`); + } + seen.set(name, kind); + validateSpecific(item, at); + } +} + +function validateNetworkBase(item: JsonObject, at: string): void { + if (typeof item.name !== 'string' || !item.name.trim()) invalid(`${at}.name must be a non-empty string`); + if (item.name !== (item.name as string).trim()) invalid(`${at}.name must not have surrounding whitespace`); + if (item.enabled !== undefined && typeof item.enabled !== 'boolean') invalid(`${at}.enabled must be a boolean`); + if (item.accessToken !== undefined && typeof item.accessToken !== 'string') { + invalid(`${at}.accessToken must be a string`); + } + if (item.messageFormat !== 'array' && item.messageFormat !== 'string') { + invalid(`${at}.messageFormat must be "array" or "string"`); + } + if (typeof item.reportSelfMessage !== 'boolean') invalid(`${at}.reportSelfMessage must be a boolean`); +} + +function validateServer(item: JsonObject, at: string): void { + if (!Number.isInteger(item.port) || (item.port as number) <= 0 || (item.port as number) > 65535) { + invalid(`${at}.port must be an integer between 1 and 65535`); + } + if (item.host !== undefined) { + if (typeof item.host !== 'string') invalid(`${at}.host must be a string`); + if (!item.host.trim()) invalid(`${at}.host must be a non-empty string when provided`); + if (item.host !== item.host.trim()) invalid(`${at}.host must not have surrounding whitespace`); + } + if (item.path !== undefined) { + if (typeof item.path !== 'string') invalid(`${at}.path must be a string`); + if (item.path !== item.path.trim()) invalid(`${at}.path must not have surrounding whitespace`); + const pathValue = item.path || '/'; + if (!pathValue.startsWith('/')) invalid(`${at}.path must be empty or start with /`); + if (pathValue.includes('?') || pathValue.includes('#')) invalid(`${at}.path must not include query or hash`); + if (new URL(`http://127.0.0.1${pathValue}`).pathname !== pathValue) { + invalid(`${at}.path must already be a normalized URL pathname`); + } + } +} + +function validateServerBinding(item: JsonObject, at: string, bindings: Map): void { + if (item.enabled === false) return; + const host = typeof item.host === 'string' && item.host.trim() + ? item.host.trim().toLowerCase() + : '0.0.0.0'; + const port = item.port as number; + const binding = `${host}:${String(port)}`; + const exact = bindings.get(binding); + if (exact) invalid(`${at} conflicts with ${exact} on server binding ${binding}`); + + // A wildcard listener owns every address in its family. Conservatively + // reject any second listener on the same port when either side is a + // wildcard; otherwise the saved plan deterministically degrades at bind. + const wildcardKey = `*:${String(port)}`; + const previousWildcard = bindings.get(wildcardKey); + if (previousWildcard) invalid(`${at} conflicts with ${previousWildcard} on wildcard server port ${String(port)}`); + const isWildcard = host === '0.0.0.0' || host === '::' || host === '[::]'; + if (isWildcard) { + const previousSamePort = [...bindings.entries()].find(([key]) => key.endsWith(`:${String(port)}`)); + if (previousSamePort) { + invalid(`${at} conflicts with ${previousSamePort[1]} on wildcard server port ${String(port)}`); + } + bindings.set(wildcardKey, at); + } + bindings.set(binding, at); +} + +function validateClient(item: JsonObject, at: string, protocols: ReadonlySet): void { + if (typeof item.url !== 'string') invalid(`${at}.url must be a string`); + if (item.enabled === false) return; + if (!item.url.trim()) invalid(`${at}.url must be non-empty while the adapter is enabled`); + let parsed: URL; + try { + parsed = new URL(item.url); + } catch { + invalid(`${at}.url must be a valid absolute URL`); + } + if (!protocols.has(parsed.protocol)) { + invalid(`${at}.url protocol must be one of ${[...protocols].join(', ')}`); + } +} + +function validateRole(value: unknown, at: string): void { + if (value !== undefined && value !== 'Api' && value !== 'Event' && value !== 'Universal') { + invalid(`${at} must be Api, Event, or Universal`); + } +} + +function invalid(message: string): never { + throw new OneBotConfigValidationError(message); } function ensureConfigDir(): void { @@ -138,9 +352,13 @@ export function cleanupInvalidPerUinConfigs(): string[] { return removed; } -function toJsonObject(config: OneBotConfig): JsonObject { +function toJsonObject(config: OneBotConfig, mode: 'snapshot' | 'overlay'): JsonObject { const nets = config.networks; return { + // Canonical per-UIN files are complete desired-state snapshots. Older + // files without this marker retain the legacy global-overlay migration + // behavior until their next successful save. + mode, networks: { httpServers: nets.httpServers.map(httpServerToJson), httpClients: nets.httpClients.map(httpClientToJson), @@ -235,11 +453,13 @@ function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { } const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients }; - return { + const config: OneBotConfig = { networks, statusCommand: parseStatusCommand(sources), notifications: parseNotifications(sources), }; + assertValidOneBotConfig(config); + return config; } /** Last-write-wins merge of `notifications.channelIds` across config sources, @@ -369,10 +589,11 @@ function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServ function parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClientNetwork | null { const url = asString(value.url); - if (!url) return null; + const base = parseBase(value, defaults); + if (!url && base.enabled !== false) return null; const timeout = asNumber(value.timeoutMs, 0); return clean({ - ...parseBase(value, defaults), + ...base, url, timeoutMs: timeout > 0 ? timeout : undefined, }); @@ -392,10 +613,11 @@ function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNe function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNetwork | null { const url = asString(value.url); - if (!url) return null; + const base = parseBase(value, defaults); + if (!url && base.enabled !== false) return null; const reconnectIntervalMs = asNumber(value.reconnectIntervalMs, 5000); return clean({ - ...parseBase(value, defaults), + ...base, url, role: asRole(value.role, 'Universal'), reconnectIntervalMs: Math.max(1000, reconnectIntervalMs), @@ -448,21 +670,45 @@ function asNumber(value: unknown, fallback = 0): number { return fallback; } -function tryLoadJson(filePath: string): JsonObject | null { +function tryLoadJson(filePath: string, failOnCorrupt = false): JsonObject | null { if (!fs.existsSync(filePath)) return null; try { const raw = fs.readFileSync(filePath, 'utf8'); const parsed = JSON.parse(raw) as unknown; - return isObject(parsed) ? parsed : null; + if (!isObject(parsed)) throw new Error('configuration root must be an object'); + return parsed; } catch (err) { - log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err)); + const message = err instanceof Error ? err.message : String(err); + if (failOnCorrupt) { + throw new Error(`config file ${filePath} is corrupt: ${message}`, { cause: err }); + } + log.warn('config file %s is corrupt and will be ignored: %s', filePath, message); return null; } } function saveJson(filePath: string, json: JsonObject): void { - fs.mkdirSync(path.dirname(filePath), { recursive: true }); - fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8'); + const dir = path.dirname(filePath); + fs.mkdirSync(dir, { recursive: true }); + const tempPath = path.join( + dir, + `.${path.basename(filePath)}.${String(process.pid)}.${randomBytes(6).toString('hex')}.tmp`, + ); + let fd: number | null = null; + try { + fd = fs.openSync(tempPath, 'wx', 0o600); + fs.writeFileSync(fd, JSON.stringify(json, null, 2), 'utf8'); + fs.fsyncSync(fd); + fs.closeSync(fd); + fd = null; + fs.renameSync(tempPath, filePath); + } catch (error) { + if (fd !== null) { + try { fs.closeSync(fd); } catch { /* preserve the primary write error */ } + } + try { fs.unlinkSync(tempPath); } catch { /* temp may not exist or rename succeeded */ } + throw error; + } } function isObject(value: unknown): value is JsonObject { diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts index 328a3063..53b5a9e8 100644 --- a/packages/onebot/src/event-converter/element-codecs.ts +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -1,5 +1,10 @@ import { createLogger } from '@snowluma/common/logger'; -import type { MessageElement } from '@snowluma/protocol/events'; +import type { + MessageElement, + MessageElementOf, + MessageElementType, +} from '@snowluma/protocol/events'; +import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; import type { JsonObject } from '../types'; import type { ParseMessageOptions } from '../message-parser'; import type { @@ -22,7 +27,7 @@ import { resolveReplyId } from './utils'; // 见 element-manifest.ts 的说明。纯 OneBot 输入糖(骰子/分享/…)也不进表,留在 // message-parser 当前置 normalize。 // -// 行为对 to-segment / message-parser 的原实现 byte 级不变——仅把分支体平移到此。 +// 每条目由判别类型精确约束:S 读错字段或 P 产出错 discriminant 会在 typecheck 报错。 // ───────────────────────────────────────────────────────────────────────── const log = createLogger('MsgParser'); @@ -37,27 +42,58 @@ export interface ToSegmentContext { mediaSegmentSink?: MediaSegmentSink | null; } -export interface ElementCodec { +// The image segment is the one intentional triangular mapping: an image with +// emoji_id normalizes to a market-face element so it can round-trip as the +// original wire type. Every other codec emits its own discriminant. +type CodecOutput = T extends 'image' + ? MessageElementOf<'image'> | MessageElementOf<'mface'> + : MessageElementOf; + +export interface ElementCodec { /** S 收·转:MessageElement → OneBot 段。 */ - toSegment?: (element: MessageElement, ctx: ToSegmentContext) => Promise; - /** P 发·解:OneBot 段 data → MessageElement(null = 丢弃该段)。 */ - fromSegment?: (data: Record, options?: ParseMessageOptions) => Promise; + toSegment?: (element: MessageElementOf, ctx: ToSegmentContext) => Promise; + /** P 发·解:OneBot 段 data → MessageElement(null = 无法构造,parser 会 typed reject)。 */ + fromSegment?: (data: Record, options?: ParseMessageOptions) => Promise | null>; } +type ElementCodecMap = Partial<{ + readonly [T in MessageElementType]: ElementCodec; +}>; + // ── 共享低层工具(原在 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; + if (typeof value === 'number') { + if (Number.isSafeInteger(value)) return value; + throw new MessageElementValidationError( + 'INVALID_FIELD', + `numeric message segment field must be a safe integer, received ${String(value)}`, + ); + } + if (typeof value === 'string') { + const text = value.trim(); + if (!text) return fallback; + if (!/^[+-]?\d+$/.test(text)) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `numeric message segment field must contain only an integer, received ${JSON.stringify(value)}`, + ); + } + const parsed = Number(text); + if (Number.isSafeInteger(parsed)) return parsed; + } + throw new MessageElementValidationError( + 'INVALID_FIELD', + `numeric message segment field must be a safe integer, received ${String(value)}`, + ); } /** 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 { +export function marketFaceElement(emojiId: string, data: Record): MessageElementOf<'mface'> { return { type: 'mface', text: String(data.summary ?? data.name ?? ''), @@ -95,7 +131,7 @@ export function pickMediaSource(data: Record): string { // ── codec 表:一种元素类型一条,键即 element.type(收·转)/ 段 type(发·解,二者同名)── -export const ELEMENT_CODECS: Record = { +export const ELEMENT_CODECS = { text: { async toSegment(element) { return { type: 'text', data: { text: element.text ?? '' } }; @@ -190,6 +226,7 @@ export const ELEMENT_CODECS: Record = { sub_type: element.subType ?? 0, summary: element.summary ?? '', }; + if (element.flash) data.type = 'flash'; if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId); return { type: 'image', data }; }, @@ -203,7 +240,7 @@ export const ELEMENT_CODECS: Record = { type: 'image', url: pickMediaSource(data), flash: data.type === 'flash', - subType: intOr(data.subType, 0), + subType: intOr(data.sub_type ?? data.subType, 0), summary: data.summary ? String(data.summary) : undefined, }; }, @@ -276,7 +313,7 @@ export const ELEMENT_CODECS: Record = { return { type: 'xml', text: String(data.data ?? ''), - subType: intOr(data.id, 0), + subType: intOr(data.resid ?? data.id, 0), }; }, }, @@ -306,14 +343,16 @@ export const ELEMENT_CODECS: Record = { }; }, async fromSegment(data) { - const fileId = String(data.file_id ?? data.fileId ?? '').trim(); - const source = String(data.file ?? data.url ?? data.path ?? '').trim(); + const fileId = String(data.file_id ?? data.fileId ?? data.id ?? '').trim(); + // Reuse the media-source rule: a bare `file` token is commonly only the + // display filename/internal id and must not mask a loadable HTTP URL. + const source = pickMediaSource(data); 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 fileSize = intOr(data.file_size ?? 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(); @@ -375,9 +414,10 @@ export const ELEMENT_CODECS: Record = { }; }, async fromSegment(data) { + if (data.type === undefined && data.id === undefined) return null; return { type: 'poke', - faceId: intOr(data.type ?? data.id, 0), + subType: intOr(data.type ?? data.id, 0), }; }, }, @@ -422,4 +462,13 @@ export const ELEMENT_CODECS: Record = { }; }, }, -}; +} satisfies ElementCodecMap; + +/** + * Dynamic lookup boundary. Each table entry is checked against its precise + * discriminant above; callers with a runtime type receive the safe union view. + */ +export function getElementCodec(type: string): ElementCodec | undefined { + if (!Object.hasOwn(ELEMENT_CODECS, type)) return undefined; + return (ELEMENT_CODECS as unknown as Record)[type]; +} diff --git a/packages/onebot/src/event-converter/to-message.ts b/packages/onebot/src/event-converter/to-message.ts index d6c48ec6..9725fe0c 100644 --- a/packages/onebot/src/event-converter/to-message.ts +++ b/packages/onebot/src/event-converter/to-message.ts @@ -34,6 +34,18 @@ async function convertPrivateMessage( ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT, ); const segments = await toSegments(ctx, event.elements, false, event.senderUin); + const sender: JsonObject = { + user_id: event.senderUin, + nickname: event.senderNick, + sex: 'unknown', + age: 0, + }; + // A temp (group-originated) message carries its source group so a client can + // reply via send_private_msg(user_id, group_id=sender.group_id). Mirrors + // go-cqhttp / NapCat, which expose it on sender.group_id. + if (subType === 'group' && 'groupId' in event && event.groupId > 0) { + sender.group_id = event.groupId; + } return message(ctx, event, postType, { message_type: 'private', sub_type: subType, @@ -43,12 +55,7 @@ async function convertPrivateMessage( message: segments, raw_message: segmentsToRawMessage(segments), font: 0, - sender: { - user_id: event.senderUin, - nickname: event.senderNick, - sex: 'unknown', - age: 0, - }, + sender, }); } @@ -73,6 +80,7 @@ export async function convertGroupMessage(ctx: ConverterContext, event: GroupMes message_id: messageId, message_seq: event.msgSeq, group_id: event.groupId, + group_name: event.groupName, user_id: event.senderUin, message: segments, raw_message: segmentsToRawMessage(segments), diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index 80199630..3410c0df 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 { ELEMENT_CODECS } from './element-codecs'; +import { getElementCodec } from './element-codecs'; import { createLogger } from '@snowluma/common/logger'; const log = createLogger('OneBot'); @@ -47,7 +47,7 @@ async function elementToSegment( mediaSegmentSink?: MediaSegmentSink | null, ): Promise { // S 收·转:按 element.type 查 codec 表;缺条目则走 default 透传(保持原兜底)。 - const codec = ELEMENT_CODECS[element.type]; + const codec = getElementCodec(element.type); if (codec?.toSegment) { return codec.toSegment(element, { isGroup, @@ -58,5 +58,6 @@ async function elementToSegment( mediaSegmentSink, }); } + log.warn('segment convert fallback type=%s reason=no receive-side codec', element.type); return { type: element.type, data: {} }; } diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 1c278809..f4a0f727 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -9,51 +9,115 @@ import { deliverPttTransText, pttTransKey } from './modules/ptt-trans-waiter'; const moduleLog = createLogger('Event'); -export function registerEventPipeline(ctx: OneBotInstanceContext): () => void { +/** Lifecycle handle for the asynchronous bridge-event pipeline. + * + * `stop()` is synchronous and idempotent: it removes every subscription so no + * new conversion can start. `drain()` resolves only after conversions that had + * already started have settled. Instance teardown must call them in that order + * before closing stores used by conversion/backfill/dispatch. */ +export interface EventPipelineHandle { + stop(): void; + drain(): Promise; +} + +export function registerEventPipeline(ctx: OneBotInstanceContext): EventPipelineHandle { const uinNum = Number.parseInt(ctx.uin, 10); const log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog; const disposers: Array<() => void> = []; + const inFlight = new Set>(); + let accepting = true; + + const track = ( + kind: QQEventVariant['kind'], + start: () => void | Promise, + ): Promise => { + if (!accepting) return Promise.resolve(); + let operation: Promise; + try { + operation = Promise.resolve(start()); + } catch (error) { + operation = Promise.reject(error); + } + const tracked = operation.then( + () => undefined, + (error) => { + log.error( + 'event pipeline handler failed kind=%s: %s', + kind, + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + }, + ); + inFlight.add(tracked); + void tracked.then(() => { inFlight.delete(tracked); }); + return tracked; + }; + disposers.push( - ctx.bridge.events.on('group_message', async (event) => { + ctx.bridge.events.on('group_message', (event) => track(event.kind, async () => { cacheGroupMessageMeta(ctx, event); await convertAndDispatch(ctx, log, event); - }), + })), ); disposers.push( - ctx.bridge.events.on('friend_message', async (event) => { + ctx.bridge.events.on('friend_message', (event) => track(event.kind, async () => { cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId); await convertAndDispatch(ctx, log, event); - }), + })), ); disposers.push( - ctx.bridge.events.on('temp_message', async (event) => { + ctx.bridge.events.on('temp_message', (event) => track(event.kind, async () => { cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0); + // Record this group temp session so a later reply is limited to sessions + // the peer opened. + ctx.tempSessions.record(event.senderUin, event.groupId); await convertAndDispatch(ctx, log, event); - }), + })), ); for (const kind of NOTICE_KINDS) { disposers.push( - ctx.bridge.events.on(kind, async (event) => { + ctx.bridge.events.on(kind, (event) => track(event.kind, async () => { if (event.kind === 'group_msg_emoji_like') { cacheReaction(ctx, event); } await convertAndDispatch(ctx, log, event); - }), + })), ); } // Internal-only: voice-to-text result push. Not converted to a OneBot event — // it just unblocks the fetch_ptt_text call waiting on this msgId. disposers.push( - ctx.bridge.events.on('ptt_trans_result', (event) => { + ctx.bridge.events.on('ptt_trans_result', (event) => track(event.kind, () => { deliverPttTransText(pttTransKey(event.selfUin, event.msgId), event.text); - }), + })), ); - return () => { + const stop = (): void => { + if (!accepting) return; + accepting = false; for (const dispose of disposers) { - try { dispose(); } catch { /* ignore */ } + try { + dispose(); + } catch (error) { + log.error( + 'event pipeline unsubscribe failed: %s', + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } } }; + + return { + stop, + async drain(): Promise { + // `stop()` makes the set monotonic: no later event can be admitted while + // this snapshot is settling. + if (accepting) { + throw new Error('event pipeline must be stopped before it can be drained'); + } + await Promise.allSettled([...inFlight]); + }, + }; } const NOTICE_KINDS = [ @@ -107,7 +171,15 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev // back-fill failure block delivery of the live message. try { await backfillReplyTarget(ctx, event); - } catch { /* best-effort — dispatch the live event regardless */ } + } catch (error) { + // Best-effort — dispatch the live event regardless, but keep the failure + // attributable so a repeated store/server miss is diagnosable. + log.warn( + 'reply backfill failed kind=%s: %s', + event.kind, + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + } ctx.dispatchEvent(converted); log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]); } diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index 61541b4c..949082e0 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -5,6 +5,7 @@ import type { ApiActionContext } from './api-handler'; import type { ConverterContext } from './event-converter'; import type { MediaStore } from './media-store'; import type { MessageStore } from './message-store'; +import type { TempSessionStore } from './temp-session-store'; import { getDownloadRKeys, getFriendList, @@ -46,6 +47,8 @@ export interface OneBotInstanceContext { messageStore: MessageStore; mediaStore: MediaStore; reactionStore: ReactionStore; + /** Group temp-session records — see {@link TempSessionStore}. */ + tempSessions: TempSessionStore; converterCtx: ConverterContext; config: OneBotConfig; musicSignUrl?: string; @@ -65,7 +68,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getMessageMeta: (messageId) => messageStore.findMeta(messageId), canSendImage: () => true, canSendRecord: () => true, - sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape), + sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId), sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape), deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta), getFriendList: () => getFriendList(bridge), diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 93a94d9d..7bc46ee9 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -4,8 +4,9 @@ import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@sn import path from 'path'; import { ApiHandler, type ActionObserver } from './api-handler'; import type { ConverterContext } from './event-converter'; -import { registerEventPipeline } from './event-pipeline'; +import { registerEventPipeline, type EventPipelineHandle } from './event-pipeline'; import { buildApiContext, type OneBotInstanceContext } from './instance-context'; +import { TempSessionStore } from './temp-session-store'; import { RKeyCache } from './instance-rkey'; import type { GlobalSettings } from './global-config'; import { MediaIndexer } from './media-indexer'; @@ -22,10 +23,13 @@ import { WsClientAdapter, WsServerAdapter, type AdapterStatus, + type DesiredNetworkAdapter, type NetworkAdapterContext, + type NetworkReconcileResult, + type NetworkShutdownResult, } from './network'; import { ReactionStore } from './reaction-store'; -import type { ApiResponse, JsonObject, JsonValue, MessageMeta, NetworkBase, OneBotConfig } from './types'; +import type { ApiResponse, JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types'; const moduleLog = createLogger('Event'); @@ -39,13 +43,25 @@ export class OneBotInstance { private readonly mediaStore: MediaStore; private readonly reactionStore: ReactionStore; private readonly networkManager: OneBotNetworkManager; + private readonly networkReady: Promise; + private lifecycleTail: Promise; private readonly rkeyCache: RKeyCache; private readonly ctx: OneBotInstanceContext; /** Process-uptime baseline for the `#sl` status reply. */ private readonly startedAt = Date.now(); /** Per-conversation last-reply timestamp for the `#sl` cooldown. */ private readonly statusCommandCooldown = new Map(); - private disposeEventPipeline: (() => void) | null = null; + private eventPipeline: EventPipelineHandle | null = null; + private eventPipelineDrain: Promise = Promise.resolve(); + private disposePromise: Promise | null = null; + private disposeRequested = false; + private acceptingActions = true; + private readonly inFlightActions = new Set>(); + private readonly storeCloseState = { + message: false, + media: false, + reaction: false, + }; private readonly pids = new Set(); private online = true; @@ -71,7 +87,7 @@ export class OneBotInstance { } /** Invoke an OneBot action against this account (debug tester). */ invokeAction(action: string, params: JsonObject): Promise { - return this.apiHandler.handle(action, params); + return this.trackAction(`debug action ${action}`, () => this.apiHandler.handle(action, params)); } /** Drive an action through the streaming seam (debug tester, stream actions). * `rawRequest` is a `{action, params, echo?}` JSON string; `emit` receives @@ -81,7 +97,7 @@ export class OneBotInstance { emit: (json: string) => void | Promise, isAlive?: () => boolean, ): Promise { - return this.apiHandler.processStreamRequest(rawRequest, emit, isAlive); + return this.trackAction('debug stream action', () => this.apiHandler.processStreamRequest(rawRequest, emit, isAlive)); } constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig, globalSettings: GlobalSettings) { @@ -116,6 +132,7 @@ export class OneBotInstance { messageStore: this.messageStore, mediaStore: this.mediaStore, reactionStore: this.reactionStore, + tempSessions: new TempSessionStore(), converterCtx: this.converterCtx, config, musicSignUrl: globalSettings.musicSignUrl, @@ -125,23 +142,34 @@ export class OneBotInstance { this.ctx = ctx; this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined); - this.networkManager = new OneBotNetworkManager(); - this.installAdaptersFromConfig(config); - void this.networkManager.openAll().catch((err) => { - this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); - }); + const networkCtx = this.buildNetworkContext(); + this.networkManager = new OneBotNetworkManager((desired) => this.createNetworkAdapter(desired, networkCtx)); + this.networkReady = this.networkManager.reconcile(config); + this.lifecycleTail = this.networkReady.then( + () => undefined, + () => undefined, + ); this.startHeartbeat(); this.rkeyCache.warmUp(this.bridge, this.uin); - this.disposeEventPipeline = registerEventPipeline(ctx); + this.eventPipeline = registerEventPipeline(ctx); } - reloadConfig(config: OneBotConfig): void { - // Keep the shared context's config in sync so live readers (e.g. the - // `#sl` handler reading `statusCommand`) pick up edits without a restart. - this.ctx.config = config; - void this.applyConfigDiff(config).catch((err) => { - this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); + waitUntilNetworkReady(): Promise { + return this.networkReady; + } + + reloadConfig(config: OneBotConfig): Promise { + if (this.disposeRequested) return Promise.reject(new Error(`OneBot instance UIN=${this.uin} is disposing`)); + const snapshot = structuredClone(config); + // Validate before entering the FIFO so deterministic errors fail fast. + this.networkManager.compileDesiredPlan(snapshot); + return this.enqueueLifecycle(async () => { + // Keep the shared context's config in sync for exactly the same ordered + // snapshot the network manager is applying. Concurrent POSTs therefore + // linearize as A then B instead of publishing B while A is reconciling. + this.ctx.config = snapshot; + return this.networkManager.reconcile(snapshot); }); } @@ -152,17 +180,75 @@ export class OneBotInstance { this.ctx.musicSignUrl = globalSettings.musicSignUrl; } - dispose(): void { + /** Synchronously stop every ingress seam for this instance generation. + * + * This operation is sticky and idempotent. It is intentionally separate + * from the asynchronous resource release so the manager can quiesce all + * generations before waiting for older lifecycle work to settle. */ + quiesce(): void { + if (this.disposeRequested) return; + this.disposeRequested = true; + this.acceptingActions = false; + this.apiHandler.quiesce(); this.online = false; this.stopHeartbeat(); - this.disposeEventPipeline?.(); - this.disposeEventPipeline = null; - void this.networkManager.closeAll().catch((err) => { - this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); + const pipeline = this.eventPipeline; + if (pipeline) { + pipeline.stop(); + this.eventPipeline = null; + this.eventPipelineDrain = pipeline.drain(); + } + } + + dispose(): Promise { + if (this.disposePromise) return this.disposePromise; + this.quiesce(); + const attempt = this.enqueueLifecycle(async () => { + await Promise.all([ + Promise.all(this.inFlightActions), + this.eventPipelineDrain, + ]); + const shutdown = await this.networkManager.shutdown(); + if (!shutdown.closed) { + throw new AggregateError( + shutdown.errors.map((error) => new Error( + `adapter ${error.name} ${error.phase} failed: ${error.message}`, + )), + `network shutdown incomplete for UIN=${this.uin}; stores remain open`, + ); + } + // Stores are intentionally closed only after every queued network + // reconcile and every transport have actually closed. + const closeErrors: unknown[] = []; + const stores = [ + ['message', () => this.messageStore.close()], + ['media', () => this.mediaStore.close()], + ['reaction', () => this.reactionStore.close()], + ] as const; + for (const [name, close] of stores) { + if (this.storeCloseState[name]) continue; + try { + close(); + this.storeCloseState[name] = true; + } catch (error) { + closeErrors.push(error); + } + } + if (closeErrors.length > 0) { + throw new AggregateError(closeErrors, `failed to close OneBot stores for UIN=${this.uin}`); + } + return shutdown; }); - this.messageStore.close(); - this.mediaStore.close(); - this.reactionStore.close(); + this.disposePromise = attempt; + void attempt.then( + () => undefined, + () => { + // Network-close and per-store completion state are retained. Let a + // later dispose call retry only the meaningful unfinished remainder. + if (this.disposePromise === attempt) this.disposePromise = null; + }, + ); + return attempt; } addPid(pid: number): void { @@ -217,9 +303,7 @@ export class OneBotInstance { const now = Date.now(); if (statusCooldownElapsed(this.statusCommandCooldown.get(key), now, cfg.cooldownSeconds)) { this.statusCommandCooldown.set(key, now); - void this.replyStatus(isGroup, sessionId).catch((err) => { - this.log.warn('status command reply failed: %s', err instanceof Error ? err.message : String(err)); - }); + void this.trackAction('status command reply', () => this.replyStatus(isGroup, sessionId)); } return cfg.swallow; } @@ -244,70 +328,51 @@ export class OneBotInstance { }; } - private installAdaptersFromConfig(config: OneBotConfig): void { - const ctx = this.buildNetworkContext(); - for (const net of config.networks.httpServers) { - if (net.enabled === false) continue; - this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)); - } - for (const net of config.networks.httpClients) { - if (net.enabled === false || !net.url) continue; - this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)); - } - for (const net of config.networks.wsServers) { - if (net.enabled === false) continue; - this.networkManager.register(new WsServerAdapter(net.name, net, ctx)); - } - for (const net of config.networks.wsClients) { - if (net.enabled === false || !net.url) continue; - this.networkManager.register(new WsClientAdapter(net.name, net, ctx)); + private createNetworkAdapter(desired: DesiredNetworkAdapter, ctx: NetworkAdapterContext) { + switch (desired.kind) { + case 'httpServer': return new HttpServerAdapter(desired.name, desired.config, ctx); + case 'httpClient': return new HttpPostAdapter(desired.name, desired.config, ctx); + case 'wsServer': return new WsServerAdapter(desired.name, desired.config, ctx); + case 'wsClient': return new WsClientAdapter(desired.name, desired.config, ctx); } } - private async applyConfigDiff(next: OneBotConfig): Promise { - const ctx = this.buildNetworkContext(); - const desired = new Map(); - const factories = new Map void>(); + private enqueueLifecycle(operation: () => Promise): Promise { + const result = this.lifecycleTail.then(operation); + this.lifecycleTail = result.then( + () => undefined, + () => undefined, + ); + return result; + } - for (const net of next.networks.httpServers) { - desired.set(net.name, net); - factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx))); + private trackAction(label: string, start: () => Promise): Promise { + if (!this.acceptingActions) { + return this.rejectedAction(label, new Error(`OneBot instance UIN=${this.uin} is disposing; ${label} rejected`)); } - for (const net of next.networks.httpClients) { - desired.set(net.name, net); - factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx))); - } - for (const net of next.networks.wsServers) { - desired.set(net.name, net); - factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx))); - } - for (const net of next.networks.wsClients) { - desired.set(net.name, net); - factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx))); + let action: Promise; + try { + action = start(); + } catch (error) { + return this.rejectedAction(label, error); } + const tracked = action.then( + () => undefined, + (error) => { + this.log.error('%s failed: %s', label, error instanceof Error ? (error.stack ?? error.message) : String(error)); + }, + ); + this.inFlightActions.add(tracked); + void tracked.then(() => { this.inFlightActions.delete(tracked); }); + return action; + } - // Close adapters whose entry has been removed entirely. - for (const adapter of this.networkManager.list()) { - if (!desired.has(adapter.name)) { - await this.networkManager.closeOne(adapter.name); - } - } - for (const [name, net] of desired) { - const existing = this.networkManager.get(name); - if (existing) { - try { - await existing.reload(net); - } catch (err) { - this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err)); - } - } else if (net.enabled !== false) { - const factory = factories.get(name); - if (factory) { - factory(); - await this.networkManager.get(name)?.open(); - } - } - } + private rejectedAction(label: string, error: unknown): Promise { + const rejected = Promise.reject(error); + void rejected.catch((reason) => { + this.log.error('%s rejected: %s', label, reason instanceof Error ? (reason.stack ?? reason.message) : String(reason)); + }); + return rejected; } private logReceivedMessage(event: JsonObject): void { diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index 7618489d..33bdeafc 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -4,11 +4,19 @@ import type { BridgeManager } from '@snowluma/core/manager'; import { loadOneBotConfig } from './config'; import { loadGlobalSettings } from './global-config'; import { OneBotInstance } from './instance'; -import type { AdapterStatus } from './network'; +import type { AdapterStatus, NetworkApplyError } from './network'; +import type { OneBotConfig } from './types'; const log = createLogger('OneBot'); const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; +class InstanceLifecycleError extends Error { + constructor(readonly instance: OneBotInstance, readonly rootCause: unknown) { + super(rootCause instanceof Error ? rootCause.message : String(rootCause)); + this.name = 'InstanceLifecycleError'; + } +} + /** Per-account OneBot connection health, surfaced to the WebUI dashboard. */ export interface AccountConnections { uin: string; @@ -16,8 +24,25 @@ export interface AccountConnections { adapters: AdapterStatus[]; } +export interface ConfigApplyResult { + online: boolean; + applied: boolean; + errors: NetworkApplyError[]; + adapters: AdapterStatus[]; +} + export class OneBotManager { private readonly instances = new Map(); + private readonly pendingLifecycle = new Set>(); + private readonly retiringInstances = new Set(); + private readonly lifecycleFailures: Array<{ + label: string; + error: unknown; + instances?: Set; + }> = []; + private readonly pendingStarts = new Map(); + private disposePromise: Promise | null = null; + private disposed = false; bind(bridgeManager: BridgeManager): void { bridgeManager.addSessionStartedListener((uin, bridge) => { @@ -37,23 +62,36 @@ export class OneBotManager { return [...this.instances.values()]; } - /** Live OneBot adapter status for every account, for the WebUI dashboard. */ + /** Live OneBot adapter status for active accounts plus failed retiring + * generations. A zombie that still owns a port must remain observable. */ getConnectionStatuses(): AccountConnections[] { - return this.getInstances().map((i) => ({ + const visible = [...this.instances.values()]; + for (const instance of this.retiringInstances) { + if (!visible.includes(instance)) visible.push(instance); + } + return visible.map((i) => ({ uin: i.uin, nickname: i.nickname, adapters: i.getConnectionStatuses(), })); } - reloadConfig(uin: string): boolean { + async reloadConfig(uin: string, config: OneBotConfig): Promise { const instance = this.instances.get(uin); - if (!instance) return false; + if (!instance) return { online: false, applied: false, errors: [], adapters: [] }; - const config = loadOneBotConfig(uin, { persistDefaults: true }); - instance.reloadConfig(config); - log.info('configuration reloaded: UIN=%s', uin); - return true; + const result = await instance.reloadConfig(config); + if (result.applied) { + log.info('configuration applied: UIN=%s adapters=%d', uin, result.statuses.length); + } else { + log.warn('configuration saved but not fully applied: UIN=%s failures=%d', uin, result.errors.length); + } + return { + online: true, + applied: result.applied, + errors: result.errors, + adapters: result.statuses, + }; } /** Re-read global (all-accounts) settings from config/snowluma.json and push @@ -66,15 +104,80 @@ export class OneBotManager { log.info('global settings reloaded for %d instance(s)', this.instances.size); } - dispose(): void { - for (const instance of this.instances.values()) { - instance.dispose(); - } + dispose(): Promise { + if (this.disposePromise) return this.disposePromise; + this.disposed = true; + for (const instance of this.instances.values()) this.retiringInstances.add(instance); + // Quiesce every live generation before awaiting older startup/shutdown + // work. A deferred lifecycle operation must not leave Action ingress open + // during process teardown. + for (const instance of this.retiringInstances) instance.quiesce(); this.instances.clear(); + const attempt = (async () => { + // Let already-tracked startup/session-close work settle first. Rejected + // operations are recorded by trackLifecycle and their instances remain + // in retiringInstances for the retry below. + await Promise.all(this.pendingLifecycle); + let failures = this.lifecycleFailures.splice(0); + const targets = [...this.retiringInstances]; + const settled = await Promise.allSettled(targets.map((instance) => instance.dispose())); + for (let index = 0; index < settled.length; index += 1) { + const instance = targets[index]; + const result = settled[index]; + const shutdownLabel = `network shutdown UIN=${instance.uin}`; + if (result.status === 'rejected') { + failures.push({ label: shutdownLabel, error: result.reason, instances: new Set([instance]) }); + continue; + } + this.retirementSucceeded(instance); + // A later successful retry supersedes failures only for this exact + // generation. Same-UIN instances must never clear one another. + failures = failures.flatMap((failure) => { + if (!failure.instances?.has(instance)) return [failure]; + const remaining = new Set(failure.instances); + remaining.delete(instance); + return remaining.size > 0 ? [{ ...failure, instances: remaining }] : []; + }); + } + if (failures.length > 0) { + throw new AggregateError( + failures.map(({ label, error }) => new Error( + `${label}: ${error instanceof Error ? error.message : String(error)}`, + )), + 'failed to dispose OneBot manager cleanly', + ); + } + this.pendingStarts.clear(); + })(); + this.disposePromise = attempt; + void attempt.then( + () => undefined, + () => { + if (this.disposePromise === attempt) this.disposePromise = null; + }, + ); + return attempt; } private onSessionStarted(uin: string, bridge: BridgeInterface): void { - if (this.instances.has(uin)) return; + if (this.disposed || this.instances.has(uin) || this.pendingStarts.has(uin)) return; + + const retiring = [...this.retiringInstances].filter((instance) => instance.uin === uin); + if (retiring.length > 0) { + const pending = { bridge, cancelled: false }; + this.pendingStarts.set(uin, pending); + this.trackLifecycle( + `session handoff UIN=${uin}`, + this.finishRetiringBeforeStart(uin, pending, retiring), + ); + return; + } + + this.startSession(uin, bridge); + } + + private startSession(uin: string, bridge: BridgeInterface): void { + if (this.disposed || this.instances.has(uin)) return; const config = loadOneBotConfig(uin, { persistDefaults: true }); const instance = new OneBotInstance(uin, bridge, config, loadGlobalSettings()); @@ -87,6 +190,10 @@ export class OneBotManager { this.instances.set(uin, instance); log.info('session started: UIN=%s', uin); + this.trackLifecycle(`network startup UIN=${uin}`, instance.waitUntilNetworkReady().then((result) => { + if (result.applied) log.info('network startup applied: UIN=%s adapters=%d', uin, result.statuses.length); + else log.warn('network startup degraded: UIN=%s failures=%d', uin, result.errors.length); + })); warmUpBridgeState(uin, bridge).catch((err) => { log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err)); }); @@ -94,13 +201,82 @@ export class OneBotManager { private onSessionClosed(uin: string): void { const instance = this.instances.get(uin); - if (!instance) return; + if (!instance) { + const pending = this.pendingStarts.get(uin); + if (pending) { + pending.cancelled = true; + this.pendingStarts.delete(uin); + } + return; + } - instance.dispose(); this.instances.delete(uin); + this.retiringInstances.add(instance); + this.trackLifecycle( + `network shutdown UIN=${uin}`, + instance.dispose().then((result) => { + this.retirementSucceeded(instance); + return result; + }), + [instance], + ); log.info('session closed: UIN=%s', uin); } + private async finishRetiringBeforeStart( + uin: string, + pending: { bridge: BridgeInterface; cancelled: boolean }, + retiring: OneBotInstance[], + ): Promise { + for (const instance of retiring) { + try { + await instance.dispose(); + } catch (error) { + // Do not leave this UIN permanently guarded by a failed handoff. A + // later session-start observation may retry the still-visible retire. + if (this.pendingStarts.get(uin) === pending) this.pendingStarts.delete(uin); + throw new InstanceLifecycleError(instance, error); + } + this.retirementSucceeded(instance); + } + if (this.pendingStarts.get(uin) !== pending) return; + this.pendingStarts.delete(uin); + if (pending.cancelled || this.disposed) return; + this.startSession(uin, pending.bridge); + } + + private trackLifecycle( + label: string, + operation: Promise, + instances?: OneBotInstance[], + ): void { + const tracked = operation.then( + () => undefined, + (error) => { + const rootCause = error instanceof InstanceLifecycleError ? error.rootCause : error; + const relatedInstances = error instanceof InstanceLifecycleError ? [error.instance] : instances; + log.error('%s failed: %s', label, rootCause instanceof Error ? (rootCause.stack ?? rootCause.message) : String(rootCause)); + this.lifecycleFailures.push({ + label, + error: rootCause, + ...(relatedInstances && relatedInstances.length > 0 ? { instances: new Set(relatedInstances) } : {}), + }); + }, + ); + this.pendingLifecycle.add(tracked); + void tracked.then(() => { this.pendingLifecycle.delete(tracked); }); + } + + private retirementSucceeded(instance: OneBotInstance): void { + this.retiringInstances.delete(instance); + for (let index = this.lifecycleFailures.length - 1; index >= 0; index -= 1) { + const failure = this.lifecycleFailures[index]; + if (!failure.instances?.has(instance)) continue; + failure.instances.delete(instance); + if (failure.instances.size === 0) this.lifecycleFailures.splice(index, 1); + } + } + } async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise { diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 0932fcee..6c2be457 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -1,11 +1,18 @@ import { createLogger } from '@snowluma/common/logger'; import type { MessageElement } from '@snowluma/protocol/events'; +import { + assertValidMessageElement, + ELEMENT_MANIFEST, + MessageElementValidationError, +} from '@snowluma/protocol/element-manifest'; import { parseFromCQString } from './helper/cq'; -import { ELEMENT_CODECS, intOr } from './event-converter/element-codecs'; +import { getElementCodec, intOr } from './event-converter/element-codecs'; import type { JsonValue } from './types'; const log = createLogger('MsgParser'); +export { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; + export interface ParseMessageOptions { resolveReplySequence?: (replyMessageId: number) => number | null; resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null; @@ -16,7 +23,7 @@ export interface ParseMessageOptions { // --- CQ Code parsing --- -export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; +export const CQ_REGEX = /\[CQ:([A-Za-z][A-Za-z0-9_]*)(?:,([^\]]*))?\]/g; export function parseCQParams(raw: string): Record { const params: Record = {}; @@ -44,33 +51,108 @@ interface MessageSegment { function isSegmentArray(val: unknown): val is MessageSegment[] { return Array.isArray(val) && val.every( - (item) => typeof item === 'object' && item !== null && 'type' in item + (item) => typeof item === 'object' && item !== null && !Array.isArray(item) + && typeof (item as { type?: unknown }).type === 'string' + && (item as { type: string }).type.trim().length > 0, ); } +function invalidMessageShape(message: string): MessageElementValidationError { + return new MessageElementValidationError('MISSING_FIELD', message, undefined, 'message'); +} + +function validatedOutboundElement(element: MessageElement): MessageElement { + // P validates the OneBot→MessageElement conversion; W ensures the resulting + // element can actually enter QQ's message-element send pipeline. Keeping + // both checks here makes parseMessage all-or-nothing before any send starts. + assertValidMessageElement(element, 'P'); + assertValidMessageElement(element, 'W'); + return element; +} + +function assertScalarSegmentData(type: string, data: Record): void { + for (const [field, value] of Object.entries(data)) { + if ( + value === undefined + || value === null + || typeof value === 'string' + || typeof value === 'number' + || typeof value === 'boolean' + ) continue; + throw new MessageElementValidationError( + 'INVALID_FIELD', + `message segment "${type}" field "${field}" must be a scalar value`, + type, + field, + ); + } +} + +function requireNonEmptyStringField( + type: string, + data: Record, + field: string, +): string { + const value = data[field]; + if (typeof value !== 'string' || !value.trim()) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `message segment "${type}" field "${field}" must be a non-empty string`, + type, + field, + ); + } + return value; +} + +function requireCoordinate( + data: Record, + field: 'lat' | 'lon', +): string { + const raw = data[field]; + const text = typeof raw === 'number' ? String(raw) : typeof raw === 'string' ? raw : ''; + const value = Number(text); + const limit = field === 'lat' ? 90 : 180; + if (!text.trim() || text !== text.trim() || !Number.isFinite(value) || value < -limit || value > limit) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `message segment "location" field "${field}" must be a finite coordinate between ${String(-limit)} and ${String(limit)}`, + 'location', + field, + ); + } + return text; +} + 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。 + // Ordinary OneBot segment fields are scalar. Reject objects/arrays before + // codecs can stringify them into "[object Object]" and alter caller intent. + // Forward nodes deliberately own nested content but are rejected by their + // dedicated normal-send branch below; anonymous is rejected regardless of + // payload, so neither needs the scalar guard. + if (normalizedType !== 'node' && normalizedType !== 'anonymous') { + assertScalarSegmentData(normalizedType, data); + } + + // 纯 OneBot 输入词:可执行的塌缩成 json/face;没有合法发送语义的 node / shake / + // anonymous 在这里明确拒绝。它们无收侧对应、无专属 wire 形态,故不进 codec 表。 + // 真实元素(收发同名)走下方的 ELEMENT_CODECS。 switch (normalizedType) { 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 - const name = String(data.nickname ?? data.name ?? ''); - return { - type: 'node', - targetUin: intOr(data.user_id ?? data.uin, 0), - text: name, - // Raw content is stored as JSON string in resId for later processing - resId: JSON.stringify(data.content ?? ''), - }; + // Forward-node arrays are consumed by parseForwardNodes before reaching + // this function. A node mixed into a normal message is not sendable. + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'message segment "node" is only valid inside a forward node list', + normalizedType, + ); } case 'share': { // Link share — map to json card message - const url = String(data.url ?? ''); - const title = String(data.title ?? ''); + const url = requireNonEmptyStringField(normalizedType, data, 'url'); + const title = requireNonEmptyStringField(normalizedType, data, 'title'); const content = String(data.content ?? ''); const image = String(data.image ?? ''); const jsonData = JSON.stringify({ @@ -79,11 +161,26 @@ export async function segmentToElement(type: string, data: Record; @@ -107,7 +204,7 @@ export async function segmentToElement(type: string, data: Record 0 && options?.resolveContactArk && (normalizedContactType === 'qq' || normalizedContactType === 'group')) { const ark = await options.resolveContactArk(contactType, numericId); if (!ark) throw new Error(`contact ark unavailable for ${contactType}:${numericId}`); - return { type: 'json', text: ark }; + return validatedOutboundElement({ type: 'json', text: ark }); } const jsonData = JSON.stringify({ app: 'com.tencent.contact.lua', @@ -160,33 +273,55 @@ export async function segmentToElement(type: string, data: Record { @@ -203,31 +338,56 @@ function segmentPayload(seg: MessageSegment): Record { export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise { if (typeof message === 'string') { + if (message.length === 0) throw invalidMessageShape('message must not be empty'); if (autoEscape) { - return message ? [{ type: 'text', text: message }] : []; + return [validatedOutboundElement({ type: 'text', text: message })]; } - return parseFromCQString(message, options); + const elements = await parseFromCQString(message, options); + if (elements.length === 0) throw invalidMessageShape('message must contain at least one sendable segment'); + return elements; } - if (isSegmentArray(message)) { + if (Array.isArray(message)) { + if (!isSegmentArray(message)) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + 'message segment array entries must be objects with a non-empty string type', + undefined, + 'message', + ); + } + if (message.length === 0) throw invalidMessageShape('message segment array must not be empty'); const elements: MessageElement[] = []; for (const seg of message) { const data = segmentPayload(seg); const elem = await segmentToElement(seg.type, data, options); if (elem) elements.push(elem); } + if (elements.length === 0) throw invalidMessageShape('message must contain at least one sendable segment'); return elements; } // Single segment object if (typeof message === 'object' && message !== null && !Array.isArray(message)) { const seg = message as unknown as MessageSegment; - if (seg.type) { + if (typeof seg.type === 'string' && seg.type.trim()) { const data = segmentPayload(seg); const elem = await segmentToElement(seg.type, data, options); - return elem ? [elem] : []; + if (elem) return [elem]; + throw invalidMessageShape('message must contain at least one sendable segment'); } + throw new MessageElementValidationError( + 'MISSING_FIELD', + 'single message segment requires a non-empty string type', + undefined, + 'type', + ); } - return []; + throw new MessageElementValidationError( + 'INVALID_FIELD', + 'message must be a string, a segment object, or a segment array', + undefined, + 'message', + ); } diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 781fbbc1..7678b3e4 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -1,5 +1,6 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { IdentityService } from '@snowluma/protocol/identity-service'; +import { formatGroupRequestFlag } from '@snowluma/protocol/qq-info'; import type { OneBotInstanceContext } from '../instance-context'; import type { JsonObject } from '../types'; @@ -239,7 +240,7 @@ export async function getGroupSystemMessages(bridge: BridgeInterface): Promise>, isSizeErr: boolean, -): { fileEls: MessageElement[]; remaining: MessageElement[] } { - const fileEls: MessageElement[] = []; - const remaining: MessageElement[] = []; +): { + fileEls: Array>; + remaining: Array>; +} { + const fileEls: Array> = []; + const remaining: Array> = []; for (const e of elements) { if (videoNeedsFileFallback(e, isSizeErr)) { - fileEls.push({ type: 'file', url: e.url, fileId: e.fileId, fileName: e.fileName || 'video.mp4' }); + const fileElement: MessageElementOf<'file'> = { + type: 'file', + url: e.url, + fileId: e.fileId, + fileName: e.fileName || 'video.mp4', + fileSize: e.fileSize, + fileHash: e.fileHash, + md5Hex: e.md5Hex, + sha1Hex: e.sha1Hex, + }; + if (!fileElement.url && !fileElement.fileId) { + throw new MessageElementValidationError( + 'MISSING_FIELD', + 'oversized video fallback requires a file/url source; a fingerprint alone cannot enter the file upload pipeline', + 'video', + 'url', + ); + } + fileEls.push(fileElement); } else { remaining.push(e); } @@ -546,7 +567,14 @@ export async function sendPrivateMessage( userId: number, message: JsonValue, autoEscape: boolean, + /** When set, reply into this group's temp session instead of friend c2c. */ + tempGroupId?: number, ): Promise { + // A temp-session reply is only allowed into a session the peer opened. + const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId); + if (tempGroupId !== undefined && !isTempReply) { + throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`); + } const elements = await parseMessage(message, autoEscape, { resolveReplySequence: (replyMessageId) => { return ref.messageStore.resolveReplySequence(false, userId, replyMessageId); @@ -590,29 +618,38 @@ export async function sendPrivateMessage( }); if (elements.length === 0) throw new Error('message is empty'); - // Private chats cannot @-mention anyone — QQ simply ignores the mention - // element in c2c messages. Many OneBot callers blindly append an `at` - // segment right after `reply` (the group-chat convention), which ends up - // producing a broken wire message. Strip `at` elements so they never - // reach the protocol layer. - const hasReply = elements.some(e => e.type === 'reply'); - for (let i = elements.length - 1; i >= 0; i--) { - if (elements[i].type === 'at') { - if (!hasReply) { - log.warn('[OneBot] at segment in private message is unsupported — stripped'); - } - elements.splice(i, 1); + // Private chats cannot @-mention anyone. Reject the whole request rather + // than deleting the at and sending a different message than the caller gave. + const hasAt = elements.some(e => e.type === 'at'); + if (hasAt) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'message element "at" cannot be sent in a private chat', + 'at', + ); + } + + // Temp sessions only have the message-element transport. File elements use + // the friend c2c upload path, so reject them before sending any preceding + // text/media batch; discovering this after sendText would create a partial + // send followed by a failed Action response. + if (tempGroupId !== undefined) { + const unsupported = elements.find((element) => + element.type === 'file' || videoNeedsFileFallback(element, false)); + if (unsupported) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + `message element "${unsupported.type}" cannot be sent in a temp session`, + unsupported.type, + ); } } - if (elements.length === 0) throw new Error('message is empty'); // C2C `{type:'file'}` segments can't ride on the elems[] pipeline — // c2c files live on `RichText.notOnlineFile`, parallel to elems // (see `@snowluma/proto-defs/message:notOnlineFile`). The element-builder - // explicitly drops them with a warn ("file send via elems[] is - // group-only"), so a private message that bundled a file alongside - // anything else used to either ship as "[空消息]" (only-file case, - // 0 elements after drop) or silently lose the file (mixed case). + // rejects them as a routing error. Split them before invoking the element + // builder so they enter the dedicated c2c-file pipeline. // // NapCat splits the same way (`dev/NapCatQQ/.../SendMsg.ts:404-415`): // FILE / VIDEO / ARK / PTT each go in their own sendMsg call, @@ -624,6 +661,14 @@ export async function sendPrivateMessage( // b) has file_id from a prior upload_private_file → sendC2cFile() only let allFileElements = elements.filter(e => e.type === 'file'); let nonFileElements = elements.filter(e => e.type !== 'file'); + let fileTargetUid: string | null = null; + const ensureFileTargetUid = async (): Promise => { + if (fileTargetUid) return fileTargetUid; + const resolved = await ref.bridge.resolveUserUid(userId); + if (!resolved) throw new Error(`c2c file send: could not resolve uid for user ${userId}`); + fileTargetUid = resolved; + return resolved; + }; // [#145] Videos up to MAX_VIDEO_SIZE (1.5 GiB) send as real videos; only // above that do we route to the file pipeline (the whole video is buffered @@ -639,12 +684,28 @@ export async function sendPrivateMessage( } } + // Resolve every deterministic prerequisite for the dedicated file path + // before sending a preceding text/media batch. Otherwise a mixed + // `[text, file]` request could publish the text and only then discover that + // the recipient UID required by RichText.notOnlineFile is unavailable. + if (allFileElements.length > 0) await ensureFileTargetUid(); + + // Route text/media batches through the temp-session primitive when replying + // passively, else the normal friend c2c path. + const sendText = (elems: MessageElement[]) => + isTempReply && tempGroupId !== undefined + ? ref.bridge.apis.message.sendGroupTempMessage(userId, tempGroupId, elems) + : ref.bridge.apis.message.sendPrivate(userId, elems); + let lastReceipt: Awaited> | undefined; if (nonFileElements.length > 0) { try { - lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); + lastReceipt = await sendText(nonFileElements); logSentMessage(false, userId, nonFileElements); } catch (err) { + // A temp-session reply can't fall back to the c2c file path (friend-only) + // — surface the original error rather than mis-routing. + if (tempGroupId !== undefined) throw err; // Highway upload failed — if a large video triggered it, fall back to // file upload for that element (private messages cannot carry file // elements through the element pipeline). @@ -654,6 +715,7 @@ export async function sendPrivateMessage( const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr); allFileElements = [...allFileElements, ...fileEls]; nonFileElements = remaining; + if (fileEls.length > 0) await ensureFileTargetUid(); if (nonFileElements.length > 0) { lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements); logSentMessage(false, userId, nonFileElements); @@ -661,8 +723,10 @@ export async function sendPrivateMessage( } } if (allFileElements.length > 0) { - const userUid = await ref.bridge.resolveUserUid(userId); - if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`); + if (tempGroupId !== undefined) { + throw new Error('temp-session file preflight invariant failed'); + } + const userUid = await ensureFileTargetUid(); for (const fileEl of allFileElements) { if (fileEl.url && !fileEl.fileId) { // uploadPrivate() already calls sendC2cFile() internally — do NOT call it again. @@ -681,7 +745,11 @@ export async function sendPrivateMessage( lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash }); logSentMessage(false, userId, [fileEl]); } else { - log.warn('[OneBot] private file segment without file_id or url — skipped'); + throw new MessageElementValidationError( + 'MISSING_FIELD', + 'private file segment requires file_id or url', + 'file', + ); } } } @@ -767,12 +835,16 @@ export async function sendGroupMessage( const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file'; const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true); fileId = result.fileId ?? ''; - if (!fileId) { log.warn('[OneBot] group file auto-upload returned no file_id — skipped'); continue; } + if (!fileId) throw new Error('group file auto-upload returned no file_id'); } else if (fileEl.fileId) { fileId = fileEl.fileId; await ref.bridge.apis.groupFile.publish(groupId, fileId); } else { - log.warn('[OneBot] group file segment without file_id or url — skipped'); + throw new MessageElementValidationError( + 'MISSING_FIELD', + 'group file segment requires file_id or url', + 'file', + ); continue; } logSentMessage(true, groupId, [fileEl]); @@ -1123,10 +1195,9 @@ interface ParseForwardOptions { /** * Are all entries of this array `{type:'node'}` segments? Then `content` * itself is a nested forward chain (vs a regular flat segment list). - * Mixed content (some nodes + some text/image) returns false: that's - * not a meaningful protocol shape, so we treat it as flat-segment and - * let the node entries fall through to parseMessage (which drops them - * with a warning). + * Mixed content (some nodes + some text/image) returns false: that's not a + * meaningful nested-forward shape, so the regular strict parser rejects the + * embedded node before any upload starts. */ function isNestedNodeArray(value: JsonValue): boolean { if (!Array.isArray(value) || value.length === 0) return false; @@ -1137,6 +1208,25 @@ function isNestedNodeArray(value: JsonValue): boolean { return true; } +function assertForwardNodeMetadataIsScalar( + nodeData: JsonObject, + index: number, +): void { + for (const [field, value] of Object.entries(nodeData)) { + if (field === 'content' || field === 'message') continue; + if ( + value === undefined || value === null || typeof value === 'string' + || typeof value === 'number' || typeof value === 'boolean' + ) continue; + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward messages[${index}].${field} must be a scalar value`, + 'node', + field, + ); + } +} + async function parseForwardNodes( ref: OneBotInstanceContext, messages: JsonValue, @@ -1144,38 +1234,121 @@ async function parseForwardNodes( ): Promise { const depth = options.depth ?? 0; if (depth >= MAX_FORWARD_DEPTH) { - throw new Error(`forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`); + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`, + 'node', + 'content', + ); } if (!Array.isArray(messages)) { - throw new Error('forward messages must be an array'); + throw new MessageElementValidationError( + 'INVALID_FIELD', + 'forward messages must be an array of node segments', + 'node', + 'messages', + ); + } + if (messages.length === 0) { + throw new MessageElementValidationError( + 'MISSING_FIELD', + 'forward messages must contain at least one node', + 'node', + 'messages', + ); } - const nodes: ForwardNodePayload[] = []; - for (const item of messages) { + // Validate the entire top-level node list before parsing any content. The + // old loop silently continued past malformed/unknown entries, so a forward + // Action could upload the remaining nodes and report success with altered + // caller intent. + const prepared = messages.map((item, index) => { const segment = asJsonObject(item); - if (!segment) continue; - - let nodeData: JsonObject | null = null; - if (String(segment.type ?? '') === 'node') { - nodeData = asJsonObject(segment.data); - } else if (segment.content !== undefined || segment.message !== undefined) { - nodeData = segment; + if (!segment) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward messages[${index}] must be an object`, + 'node', + `messages[${index}]`, + ); + } + const rawType = segment.type; + if (rawType !== undefined && typeof rawType !== 'string') { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward messages[${index}].type must be "node"`, + 'node', + 'type', + ); + } + if (typeof rawType === 'string' && rawType !== 'node') { + throw new MessageElementValidationError( + 'UNKNOWN_TYPE', + `unknown forward message segment type: ${rawType}`, + rawType, + 'type', + ); } - if (!nodeData) continue; - const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id); - if (messageId > 0) { + if (rawType === 'node') { + const nodeData = asJsonObject(segment.data); + if (!nodeData) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward messages[${index}].data must be an object`, + 'node', + 'data', + ); + } + assertForwardNodeMetadataIsScalar(nodeData, index); + return { segment, nodeData }; + } + + // Preserve the existing bare-node compatibility form, but require it to + // carry content explicitly instead of silently ignoring arbitrary objects. + if (segment.content === undefined && segment.message === undefined) { + throw new MessageElementValidationError( + 'MISSING_FIELD', + `forward messages[${index}] requires type:"node" data or bare content/message`, + 'node', + 'content', + ); + } + assertForwardNodeMetadataIsScalar(segment, index); + return { segment, nodeData: segment }; + }); + + const nodes: ForwardNodePayload[] = []; + for (const { nodeData } of prepared) { + + const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id); + if (messageId !== 0) { const event = ref.messageStore.findEvent(messageId); - if (!event) throw new Error(`forward node message_id not found: ${messageId}`); + if (!event) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward node message_id not found: ${String(messageId)}`, + 'node', + 'message_id', + ); + } const eventSender = asJsonObject(event.sender) ?? {}; const senderCard = eventSender.card !== undefined ? String(eventSender.card) : undefined; const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? ''); const userUin = toPositiveInt(event.user_id); + if (userUin <= 0) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `forward node message_id ${String(messageId)} has no valid sender user_id`, + 'node', + 'user_id', + ); + } const content = (event.message ?? event.raw_message ?? '') as JsonValue; const elements = await parseMessage(content, false); - if (userUin > 0 && elements.length > 0) { + if (elements.length > 0) { const messageType = event.message_type === 'group' ? 'group' : 'private'; const groupIdValue = toPositiveInt(event.group_id); nodes.push({ @@ -1183,7 +1356,7 @@ async function parseForwardNodes( nickname: nickname || String(userUin), elements, time: typeof event.time === 'number' ? event.time : toPositiveInt(event.time), - msgId: toPositiveInt(event.message_id), + msgId: toSafeSignedInteger(event.message_id), msgSeq: toPositiveInt(event.message_seq), groupId: groupIdValue > 0 ? groupIdValue : undefined, senderCard, @@ -1351,3 +1524,27 @@ function toPositiveInt(value: JsonValue | undefined): number { } return 0; } + +function toSafeSignedInteger(value: JsonValue | undefined): number { + if (typeof value === 'number' && Number.isSafeInteger(value)) return value; + if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) { + const parsed = Number(value.trim()); + if (Number.isSafeInteger(parsed)) return parsed; + } + return 0; +} + +function parseForwardMessageId(value: JsonValue | undefined): number { + if (value === undefined || value === null || value === '') return 0; + if (typeof value === 'number' && Number.isSafeInteger(value)) return value; + if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) { + const parsed = Number(value.trim()); + if (Number.isSafeInteger(parsed)) return parsed; + } + throw new MessageElementValidationError( + 'INVALID_FIELD', + 'forward node id/message_id must be a non-zero safe integer', + 'node', + 'message_id', + ); +} diff --git a/packages/onebot/src/modules/request-actions.ts b/packages/onebot/src/modules/request-actions.ts index 27224c4c..e0072aac 100644 --- a/packages/onebot/src/modules/request-actions.ts +++ b/packages/onebot/src/modules/request-actions.ts @@ -1,4 +1,96 @@ +import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { GroupRequestHandle, GroupRequestInfo } from '@snowluma/protocol/qq-info'; + +const log = createLogger('OneBot.Request'); + +type ParsedGroupRequestFlag = + | ({ kind: 'canonical' } & GroupRequestHandle) + | { kind: 'sequence'; sequence: number } + | { kind: 'legacy'; requestType: 'add' | 'invite'; groupId: number; targetUid: string }; + +function positiveSafeInteger(value: string, field: string): number { + if (!/^\d+$/.test(value)) throw new Error(`invalid ${field} in group request flag`); + const parsed = Number(value); + if (!Number.isSafeInteger(parsed) || parsed <= 0) { + throw new Error(`invalid ${field} in group request flag`); + } + return parsed; +} + +export function parseGroupRequestFlag(flag: string): ParsedGroupRequestFlag { + if (/^\d+$/.test(flag)) { + return { kind: 'sequence', sequence: positiveSafeInteger(flag, 'sequence') }; + } + + const parts = flag.split(':'); + if (parts[0] === 'slreq') { + if (parts.length !== 6 || parts[1] !== '1') { + throw new Error('unsupported canonical group request flag'); + } + if (parts[5] !== '0' && parts[5] !== '1') { + throw new Error('invalid filtered value in group request flag'); + } + return { + kind: 'canonical', + sequence: positiveSafeInteger(parts[2], 'sequence'), + groupId: positiveSafeInteger(parts[3], 'group_id'), + eventType: positiveSafeInteger(parts[4], 'event_type'), + filtered: parts[5] === '1', + }; + } + + const requestType = parts[0]; + if ((requestType !== 'add' && requestType !== 'invite') || parts.length < 3) { + throw new Error('invalid group request flag'); + } + const groupId = positiveSafeInteger(parts[1], 'group_id'); + const targetUid = parts.slice(2).join(':'); + if (!targetUid) throw new Error('invalid request target in flag'); + return { kind: 'legacy', requestType, groupId, targetUid }; +} + +async function fetchRequestInboxes(bridge: BridgeInterface): Promise { + const [main, filtered] = await Promise.allSettled([ + bridge.apis.contacts.fetchGroupRequests(false), + bridge.apis.contacts.fetchGroupRequests(true), + ]); + + if (main.status === 'rejected') { + log.warn('failed to fetch main group-request inbox: %s', + main.reason instanceof Error ? main.reason.message : String(main.reason)); + } + if (filtered.status === 'rejected') { + log.warn('failed to fetch filtered group-request inbox: %s', + filtered.reason instanceof Error ? filtered.reason.message : String(filtered.reason)); + } + if (main.status === 'rejected' && filtered.status === 'rejected') { + throw new Error('failed to fetch group requests from both inboxes'); + } + + return [ + ...(main.status === 'fulfilled' ? main.value : []), + ...(filtered.status === 'fulfilled' ? filtered.value : []), + ]; +} + +async function applyGroupRequest( + bridge: BridgeInterface, + handle: GroupRequestHandle, + approve: boolean, + reason: string, +): Promise { + log.debug('handling group request: group=%d sequence=%d eventType=%d filtered=%s approve=%s', + handle.groupId, handle.sequence, handle.eventType, handle.filtered, approve); + await bridge.apis.groupAdmin.setAddRequest( + handle.groupId, + handle.sequence, + handle.eventType, + approve, + reason, + handle.filtered, + ); +} export async function handleGroupAddRequest( bridge: BridgeInterface, @@ -6,55 +98,58 @@ export async function handleGroupAddRequest( approve: boolean, reason: string, ): Promise { - // flag format: "add:groupId:uid" or "invite:groupId:uid" - const parts = flag.split(':'); - if (parts.length < 3) throw new Error('invalid group request flag'); - const requestType = parts[0]; - const groupId = parseInt(parts[1], 10); - const targetUid = parts.slice(2).join(':'); - if (!groupId) throw new Error('invalid group_id in flag'); - if (!targetUid) throw new Error('invalid request target in flag'); + const parsed = parseGroupRequestFlag(flag); - // Bot self-invited via a private "qun.invite" card: the only sequence the - // server accepts at 0x10c8_1 is that card's jumpUrl msgseq, with eventType=2 - // / filtered=false. The fetchGroupRequests tuple below fails this case with - // 120161001 ("handle async message fail"). See issue #125. - if (requestType === 'invite') { - const cardSequence = bridge.apis.contacts.getGroupInviteCardSequence(groupId); + if (parsed.kind === 'canonical') { + await applyGroupRequest(bridge, parsed, approve, reason); + return; + } + + if (parsed.kind === 'sequence') { + // Private "qun.invite" cards use their Ark msgseq and never appear under + // that sequence in 0x10C0. Resolve the reverse card cache before inboxes. + const cardGroupId = bridge.apis.contacts.findGroupInviteCardGroupBySequence(parsed.sequence); + if (cardGroupId) { + await applyGroupRequest(bridge, { + groupId: cardGroupId, + sequence: parsed.sequence, + eventType: 2, + filtered: false, + }, approve, reason); + return; + } + + const matching = (await fetchRequestInboxes(bridge)) + .find((request) => request.sequence === parsed.sequence); + if (!matching) throw new Error(`group request sequence ${parsed.sequence} not found`); + await applyGroupRequest(bridge, matching, approve, reason); + return; + } + + // Legacy SnowLuma flags remain accepted for events emitted by older builds. + // A private invite card needs its msgseq rather than the 0x10C0 tuple (#125). + if (parsed.requestType === 'invite') { + const cardSequence = bridge.apis.contacts.getGroupInviteCardSequence(parsed.groupId); if (cardSequence) { - await bridge.apis.groupAdmin.setAddRequest(groupId, cardSequence, 2, approve, reason, false); + await applyGroupRequest(bridge, { + groupId: parsed.groupId, + sequence: cardSequence, + eventType: 2, + filtered: false, + }, approve, reason); return; } } - // A join/invite request lands in either the main inbox (0x10c8 subCommand 1) - // or the spam-filtered one (subCommand 2). The old code only fetched the main - // inbox, so a filtered request that SnowLuma had already reported to the - // client couldn't be approved through its own flag — "matching group request - // not found" (#197). Search both; each request keeps the `filtered` flag its - // inbox needs for the approval subCommand. One inbox failing degrades to the - // other rather than aborting. - const [mainInbox, filteredInbox] = await Promise.all([ - bridge.apis.contacts.fetchGroupRequests(false).catch(() => []), - bridge.apis.contacts.fetchGroupRequests(true).catch(() => []), - ]); - const requests = [...mainInbox, ...filteredInbox]; - const matching = requests.find((r) => { - if (r.groupId !== groupId) return false; - if (requestType === 'add') return r.targetUid === targetUid; - if (requestType === 'invite') return r.invitorUid === targetUid; - return false; - }) || requests.find(r => r.groupId === groupId); + const matching = (await fetchRequestInboxes(bridge)).find((request) => { + if (request.groupId !== parsed.groupId) return false; + return parsed.requestType === 'add' + ? request.targetUid === parsed.targetUid + : request.invitorUid === parsed.targetUid; + }); - if (!matching) { - throw new Error('matching group request not found'); - } - await bridge.apis.groupAdmin.setAddRequest( - groupId, - matching.sequence, - matching.eventType, - approve, - reason, - matching.filtered, - ); + // Never fall back to an arbitrary request from the same group: when a UID + // does not match, approving another pending request is worse than failing. + if (!matching) throw new Error('matching group request not found'); + await applyGroupRequest(bridge, matching, approve, reason); } diff --git a/packages/onebot/src/network/adapter.ts b/packages/onebot/src/network/adapter.ts index e1bda450..db316403 100644 --- a/packages/onebot/src/network/adapter.ts +++ b/packages/onebot/src/network/adapter.ts @@ -17,7 +17,7 @@ export enum NetworkReloadType { Opened = 3, } -export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled'; +export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled' | 'degraded'; /** Live runtime status of a single network adapter, surfaced to the WebUI * dashboard (and the per-node config cards) so the gateway's own @@ -28,6 +28,11 @@ export interface AdapterStatus { kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient'; status: AdapterStatusLevel; detail: string; + /** Present when the desired config could not be applied or the bound + * transport later failed. The adapter may still be serving its restored + * previous config; `degraded` describes reconciliation, not only liveness. */ + lastError?: string; + lastErrorAt?: number; } export abstract class IOneBotNetworkAdapter { @@ -36,6 +41,7 @@ export abstract class IOneBotNetworkAdapter { protected readonly ctx: NetworkAdapterContext; protected readonly log: Logger; protected isEnabled = false; + private applyFailure: { message: string; at: number } | null = null; constructor(name: string, config: C, ctx: NetworkAdapterContext, moduleLog?: Logger) { this.name = name; @@ -50,6 +56,8 @@ export abstract class IOneBotNetworkAdapter { get currentConfig(): Readonly { return this.config; } + get hasApplyFailure(): boolean { return this.applyFailure !== null; } + abstract open(): void | Promise; abstract close(): void | Promise; @@ -58,6 +66,35 @@ export abstract class IOneBotNetworkAdapter { /** Report live connection health for the WebUI dashboard. */ abstract describeStatus(): AdapterStatus; + /** Status with the manager-owned desired/live mismatch overlaid. Concrete + * adapters continue to describe transport health; reconciliation failures + * are kept here so a successfully restored old binding is still visible. */ + describeManagedStatus(): AdapterStatus { + const status = this.describeStatus(); + if (!this.applyFailure) return status; + return { + ...status, + status: 'degraded', + detail: `应用失败:${this.applyFailure.message}`, + lastError: this.applyFailure.message, + lastErrorAt: this.applyFailure.at, + }; + } + + /** NetworkManager lifecycle seam. A failure is cleared only after a later + * reconciliation reaches the desired state. */ + markApplyFailure(error: unknown, at = Date.now()): void { + this.applyFailure = { message: errorMessage(error), at }; + } + + clearApplyFailure(): void { + this.applyFailure = null; + } + + protected recordTransportFailure(error: unknown, at = Date.now()): void { + this.markApplyFailure(error, at); + } + // ── meta-event framing: shared by the connection-oriented adapters ───── // // Lifecycle (connect/enable/disable) and heartbeat meta events don't flow @@ -99,9 +136,10 @@ export abstract class IOneBotNetworkAdapter { // three things that genuinely differ per adapter are the hooks below. // // NOTE: the returned `NetworkReloadType` is a *test-observability* seam. - // The sole production caller (`instance.applyConfigDiff`) discards it — - // it exists so tests can assert "which transition did this config cause" - // without poking private state. Behaviour, not the label, is the contract. + // OneBotNetworkManager awaits the transition but derives apply truth from + // success/failure rather than this label. Tests use it to assert "which + // transition did this config cause" without poking private state. + // Behaviour, not the label, is the contract. /** Stable string identity of the bound resource (host:port / url / token …). * A change here means the live binding must be torn down and re-opened. */ @@ -121,27 +159,36 @@ export abstract class IOneBotNetworkAdapter { const prevSig = this.bindingSignature(this.config); const wasEnabled = this.isEnabled; const willEnable = this.willEnable(next); - - this.config = structuredClone(next); - this.onConfigReplaced(next); - const sigChanged = prevSig !== this.bindingSignature(next); - if (sigChanged && wasEnabled) { + + // Keep currentConfig truthful while the old live resource is being + // released. Only publish the desired config after close succeeds; an + // opening adapter necessarily sees the new config, while a close failure + // leaves the previous config intact for recovery and diagnostics. + if (wasEnabled && (sigChanged || !willEnable)) { await this.close(); + this.replaceConfig(next); if (willEnable) { await this.open(); return NetworkReloadType.Reopened; } return NetworkReloadType.Closed; } + + this.replaceConfig(next); if (!wasEnabled && willEnable) { await this.open(); return NetworkReloadType.Opened; } - if (wasEnabled && !willEnable) { - await this.close(); - return NetworkReloadType.Closed; - } return NetworkReloadType.Normal; } + + private replaceConfig(next: C): void { + this.config = structuredClone(next); + this.onConfigReplaced(next); + } +} + +function errorMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); } diff --git a/packages/onebot/src/network/http-post-adapter.ts b/packages/onebot/src/network/http-post-adapter.ts index b84deb44..3c8669b3 100644 --- a/packages/onebot/src/network/http-post-adapter.ts +++ b/packages/onebot/src/network/http-post-adapter.ts @@ -52,16 +52,22 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { this.options = resolveReportOptions(next); } - onEvent(event: JsonObject, payload: DispatchPayload): void { + async onEvent(event: JsonObject, payload: DispatchPayload): Promise { if (!this.isEnabled) return; const json = pickDispatchJson(payload, this.options); if (json === null) return; - void this.postEvent(json, event).catch((err) => { - this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); - }); + // A reconcile may replace this.config while HMAC computation or fetch is + // awaiting. Keep one event on one immutable config epoch so an old token + // can never sign a request sent to a new URL (or vice versa). + const config = structuredClone(this.config); + await this.postEvent(json, event, config); } - private async postEvent(payload: string, event: JsonObject): Promise { + private async postEvent( + payload: string, + event: JsonObject, + config: HttpClientNetwork, + ): Promise { if (!this.isEnabled) return; const headers: Record = { @@ -69,13 +75,13 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { 'User-Agent': 'OneBot', 'X-Self-ID': this.ctx.uin, }; - if (this.config.accessToken) { - headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload); + if (config.accessToken) { + headers['X-Signature'] = await computeHmacSha1(config.accessToken, payload); } - const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS; + const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS; try { - const response = await fetch(this.config.url, { + const response = await fetch(config.url, { method: 'POST', headers, body: payload, @@ -92,13 +98,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { } } else { this.lastDelivery = { at: Date.now(), ok: false }; - this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status); + this.log.warn('[%s] POST %s returned %d', this.name, config.url, response.status); } } catch (error) { this.lastDelivery = { at: Date.now(), ok: false }; - if (this.isEnabled) { - this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error)); - } + this.log.warn('[%s] POST %s failed: %s', this.name, config.url, error instanceof Error ? error.message : String(error)); } } diff --git a/packages/onebot/src/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts index b617df8e..9d466282 100644 --- a/packages/onebot/src/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -17,24 +17,56 @@ const moduleLog = createLogger('OneBot.HTTP'); export class HttpServerAdapter extends IOneBotNetworkAdapter { private server: Server | null = null; private listening = false; + private closePromise: Promise | null = null; + private acceptingActions = false; + private readonly inFlightActions = new Set>(); constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx, moduleLog); } - open(): void { - if (this.isEnabled) return; + async open(): Promise { + if (this.isEnabled && this.listening) return; if (this.config.enabled === false) return; - this.startServer(); + if (this.server) throw new Error(`HTTP adapter [${this.name}] still owns a previous server`); + await this.startServer(); this.isEnabled = true; + this.clearApplyFailure(); } - close(): void { - if (!this.isEnabled && !this.server) return; + async close(): Promise { + if (this.closePromise) return this.closePromise; + if (!this.isEnabled && !this.server && this.inFlightActions.size === 0) return; + const wasEnabled = this.isEnabled; + const wasListening = this.listening; + const wasAcceptingActions = this.acceptingActions; + this.acceptingActions = false; this.isEnabled = false; this.listening = false; - this.server?.close(); - this.server = null; + const server = this.server; + const release = server + ? new Promise((resolve, reject) => { + server.close((error) => { + if (error && !isAlreadyClosedError(error)) reject(error); + else resolve(); + }); + }) + : Promise.resolve(); + const attempt = Promise.all([release, Promise.all(this.inFlightActions)]).then(() => undefined); + this.closePromise = attempt; + try { + await attempt; + if (this.server === server) this.server = null; + } catch (error) { + // A failed close callback cannot prove the listener was released. Keep + // ownership and live-state truth so shutdown/reconcile can retry it. + this.isEnabled = wasEnabled; + this.listening = wasListening; + this.acceptingActions = wasAcceptingActions; + throw error; + } finally { + this.closePromise = null; + } } override describeStatus(): AdapterStatus { @@ -49,28 +81,57 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ } - private startServer(): void { - const server = createServer((req, res) => { - void this.handleRequest(req, res); - }); - this.server = server; + private startServer(): Promise { + return new Promise((resolve, reject) => { + const server = createServer((req, res) => { + this.trackInboundAction(req, res); + }); + this.server = server; + let opening = true; - server.on('listening', () => { - this.listening = true; - this.log.success( - '[%s] listening %s:%d%s', - this.name, - this.config.host ?? '0.0.0.0', - this.config.port, - normalizePath(this.config.path ?? '/'), - ); - }); - server.on('error', (err) => { - this.listening = false; - this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); - }); + server.once('listening', () => { + opening = false; + if (this.server !== server || this.closePromise) { + server.close(); + reject(new Error(`HTTP adapter [${this.name}] was closed while binding`)); + return; + } + this.listening = true; + this.isEnabled = true; + this.acceptingActions = true; + this.log.success( + '[%s] listening %s:%d%s', + this.name, + this.config.host ?? '0.0.0.0', + this.config.port, + normalizePath(this.config.path ?? '/'), + ); + resolve(); + }); + server.on('error', (error) => { + if (this.server === server) { + this.listening = false; + this.isEnabled = false; + this.acceptingActions = false; + this.recordTransportFailure(error); + if (opening) this.server = null; + } + this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error)); + if (opening) { + opening = false; + reject(error); + } + }); - server.listen(this.config.port, this.config.host ?? '0.0.0.0'); + try { + server.listen(this.config.port, this.config.host ?? '0.0.0.0'); + } catch (error) { + opening = false; + if (this.server === server) this.server = null; + this.recordTransportFailure(error); + reject(error); + } + }); } private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise { @@ -200,6 +261,33 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording }); } } + + private trackInboundAction(req: IncomingMessage, res: ServerResponse): void { + if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) { + writeJson(res, 503, { status: 'failed', retcode: 1200, data: null, wording: 'server closing' }); + return; + } + let action: Promise; + try { + action = this.handleRequest(req, res); + } catch (error) { + this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error)); + writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording: 'internal error' }); + return; + } + const tracked = action.then( + () => undefined, + (error) => { + this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error)); + }, + ); + this.inFlightActions.add(tracked); + void tracked.then(() => { this.inFlightActions.delete(tracked); }); + } +} + +function isAlreadyClosedError(error: Error): boolean { + return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING'; } function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise { @@ -223,7 +311,7 @@ function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Prom function writeJson(res: ServerResponse, statusCode: number, data: unknown): void { // A streaming response may already have flushed headers (and even ended); a // late error must not double-send and trip ERR_HTTP_HEADERS_SENT. - if (res.headersSent || res.writableEnded) return; + if (res.headersSent || res.writableEnded || res.destroyed) return; res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(data)); diff --git a/packages/onebot/src/network/index.ts b/packages/onebot/src/network/index.ts index 541f7a41..a25c0541 100644 --- a/packages/onebot/src/network/index.ts +++ b/packages/onebot/src/network/index.ts @@ -7,8 +7,16 @@ export { } from './adapter'; export { HttpPostAdapter } from './http-post-adapter'; export { HttpServerAdapter } from './http-server-adapter'; -export { OneBotNetworkManager } from './network-manager'; +export { + OneBotNetworkManager, + type DesiredNetworkAdapter, + type NetworkAdapterFactory, + type NetworkAdapterKind, + type NetworkApplyError, + type NetworkApplyPhase, + type NetworkReconcileResult, + type NetworkShutdownResult, +} from './network-manager'; export { executeQuickOperation } from './quick-operation'; export { WsClientAdapter } from './ws-client-adapter'; export { WsServerAdapter } from './ws-server-adapter'; - diff --git a/packages/onebot/src/network/network-manager.ts b/packages/onebot/src/network/network-manager.ts index 89f82da7..a430d0e5 100644 --- a/packages/onebot/src/network/network-manager.ts +++ b/packages/onebot/src/network/network-manager.ts @@ -1,113 +1,468 @@ import { createLogger } from '@snowluma/common/logger'; +import { assertValidOneBotConfig } from '../config'; import { buildDispatchPayload } from '../event-filter'; -import type { JsonObject, NetworkBase } from '../types'; +import type { + HttpClientNetwork, + HttpServerNetwork, + JsonObject, + NetworkBase, + OneBotConfig, + WsClientNetwork, + WsServerNetwork, +} from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter'; const log = createLogger('OneBot.Network'); type AnyAdapter = IOneBotNetworkAdapter; +export type NetworkAdapterKind = AdapterStatus['kind']; +export type DesiredNetworkAdapter = + | { name: string; kind: 'httpServer'; config: HttpServerNetwork } + | { name: string; kind: 'httpClient'; config: HttpClientNetwork } + | { name: string; kind: 'wsServer'; config: WsServerNetwork } + | { name: string; kind: 'wsClient'; config: WsClientNetwork }; + +export type NetworkApplyPhase = 'open' | 'reload' | 'close' | 'replace' | 'restore' | 'shutdown'; + +export interface NetworkApplyError { + name: string; + kind: NetworkAdapterKind; + phase: NetworkApplyPhase; + message: string; + at: number; + /** True when the previous live adapter/config was restored. The desired + * config remains unapplied and the adapter stays visibly degraded. */ + restored?: boolean; +} + +export interface NetworkReconcileResult { + applied: boolean; + errors: NetworkApplyError[]; + statuses: AdapterStatus[]; +} + +export interface NetworkShutdownResult { + closed: boolean; + errors: NetworkApplyError[]; +} + +export type NetworkAdapterFactory = (desired: DesiredNetworkAdapter) => AnyAdapter; + +interface ManagedAdapter { + kind: NetworkAdapterKind; + adapter: AnyAdapter; +} + +/** + * Single owner of the configured network topology. + * + * Configs are first compiled into a globally-name-unique desired plan. Every + * startup/reload/shutdown operation then runs through one FIFO, so a reload can + * never race another reload or teardown. Runtime failures are isolated per + * adapter and returned as data; deterministic plan errors throw before the + * operation is queued. + */ export class OneBotNetworkManager { - private readonly adapters = new Map(); + private readonly adapters = new Map(); + private readonly factory: NetworkAdapterFactory | null; + private operationTail: Promise = Promise.resolve(); + private acceptingReconciles = true; + private acceptingEvents = true; + private readonly inFlightEmits = new Set>(); + private shutdownPromise: Promise | null = null; + private shutdownResult: NetworkShutdownResult | null = null; + /** Debug-stream taps — notified for every emitted event regardless of adapter * state. Attached on-demand (ref-counted) by the WebUI debug stream. */ private readonly debugSubscribers = new Set<(event: JsonObject) => void>(); + constructor(factory?: NetworkAdapterFactory) { + this.factory = factory ?? null; + } + subscribeDebug(cb: (event: JsonObject) => void): () => void { this.debugSubscribers.add(cb); return () => { this.debugSubscribers.delete(cb); }; } + /** Test/embedding seam for pre-built adapters. Production topology changes + * go through reconcile(), which refuses duplicate names. */ register(adapter: IOneBotNetworkAdapter): void { - const existing = this.adapters.get(adapter.name); - if (existing) { - log.info('replacing adapter [%s]', adapter.name); - Promise.resolve(existing.close()).catch(() => { - /* best-effort */ - // 应该该打个日志以便排查问题,但不应当让调用者感知到这个失败。 - }); + if (!this.acceptingReconciles) { + throw new Error('network manager is shutting down'); } - this.adapters.set(adapter.name, adapter as AnyAdapter); + if (this.adapters.has(adapter.name)) { + throw new Error(`network adapter name already registered: ${adapter.name}`); + } + const kind = adapter.describeStatus().kind; + this.adapters.set(adapter.name, { kind, adapter: adapter as AnyAdapter }); } has(name: string): boolean { return this.adapters.has(name); } get(name: string): AnyAdapter | null { - return this.adapters.get(name) ?? null; + return this.adapters.get(name)?.adapter ?? null; } - list(): AnyAdapter[] { return [...this.adapters.values()]; } + list(): AnyAdapter[] { return [...this.adapters.values()].map((entry) => entry.adapter); } - /** Live status of every registered adapter, for the WebUI dashboard. */ + /** Live status of every registered adapter, including desired/live apply + * failures even when an older binding was restored and remains active. */ describeStatuses(): AdapterStatus[] { - return this.list().map((a) => a.describeStatus()); + return this.list().map((adapter) => adapter.describeManagedStatus()); } hasActiveAdapters(): boolean { - for (const a of this.adapters.values()) if (a.isActive) return true; + for (const { adapter } of this.adapters.values()) if (adapter.isActive) return true; return false; } - async openAll(): Promise { - const tasks = this.list().map(async (a) => { - try { - await a.open(); - } catch (err) { - log.error('adapter [%s] open failed: %s', a.name, errMessage(err)); - } - }); - await Promise.all(tasks); + /** Compile and validate outside the queue: deterministic errors never wait + * behind network I/O and can be rejected before a WebUI save. */ + compileDesiredPlan(config: OneBotConfig): DesiredNetworkAdapter[] { + assertValidOneBotConfig(config); + return [ + ...config.networks.httpServers.map((network) => ({ + name: network.name, + kind: 'httpServer' as const, + config: structuredClone(network), + })), + ...config.networks.httpClients.map((network) => ({ + name: network.name, + kind: 'httpClient' as const, + config: structuredClone(network), + })), + ...config.networks.wsServers.map((network) => ({ + name: network.name, + kind: 'wsServer' as const, + config: structuredClone(network), + })), + ...config.networks.wsClients.map((network) => ({ + name: network.name, + kind: 'wsClient' as const, + config: structuredClone(network), + })), + ]; } - async closeAll(): Promise { - const tasks = this.list().map(async (a) => { - try { - await a.close(); - } catch (err) { - log.warn('adapter [%s] close failed: %s', a.name, errMessage(err)); - } - }); - await Promise.all(tasks); - this.adapters.clear(); - } - - async closeOne(name: string): Promise { - const adapter = this.adapters.get(name); - if (!adapter) return; - this.adapters.delete(name); - try { - await adapter.close(); - } catch (err) { - log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err)); + reconcile(config: OneBotConfig): Promise { + const desired = this.compileDesiredPlan(config); + if (!this.acceptingReconciles) { + return Promise.reject(new Error('network manager is shutting down')); } + return this.enqueue(() => this.reconcileNow(desired)); } - async emitEvent(event: JsonObject): Promise { + /** Compatibility seam for tests/pre-built adapters. Opens sequentially and + * reports each failure instead of hiding it in a detached Promise. */ + openAll(): Promise { + if (!this.acceptingReconciles) return Promise.reject(new Error('network manager is shutting down')); + return this.enqueue(async () => { + const errors: NetworkApplyError[] = []; + for (const entry of this.adapters.values()) { + try { + await entry.adapter.open(); + entry.adapter.clearApplyFailure(); + } catch (error) { + entry.adapter.markApplyFailure(error); + errors.push(this.report(entry.adapter.name, entry.kind, 'open', error)); + } + } + return this.result(errors); + }); + } + + closeOne(name: string): Promise { + if (!this.acceptingReconciles) return Promise.reject(new Error('network manager is shutting down')); + return this.enqueue(async () => { + const entry = this.adapters.get(name); + if (!entry) return; + await entry.adapter.close(); + this.adapters.delete(name); + }); + } + + /** Ordered, idempotent shutdown. Reconcile calls made before shutdown finish + * first; calls made after shutdown is requested fail immediately. */ + shutdown(): Promise { + if (this.shutdownResult?.closed) return Promise.resolve(this.shutdownResult); + if (this.shutdownPromise) return this.shutdownPromise; + this.acceptingReconciles = false; + this.acceptingEvents = false; + const attempt = this.enqueue(async () => { + const errors: NetworkApplyError[] = []; + const dispatches = await Promise.allSettled([...this.inFlightEmits]); + for (const dispatch of dispatches) { + if (dispatch.status === 'rejected') { + log.error('in-flight event dispatch failed during shutdown: %s', errMessage(dispatch.reason)); + } + } + const entries = [...this.adapters.entries()].reverse(); + for (const [name, entry] of entries) { + try { + await entry.adapter.close(); + this.adapters.delete(name); + } catch (error) { + entry.adapter.markApplyFailure(error); + errors.push(this.report(name, entry.kind, 'shutdown', error)); + } + } + this.debugSubscribers.clear(); + return { closed: errors.length === 0, errors }; + }); + this.shutdownPromise = attempt; + void attempt.then( + (result) => { + this.shutdownResult = result.closed ? result : null; + this.shutdownPromise = null; + }, + () => { + this.shutdownPromise = null; + }, + ); + return attempt; + } + + closeAll(): Promise { + return this.shutdown(); + } + + emitEvent(event: JsonObject): Promise { + if (!this.acceptingEvents) { + return Promise.reject(new Error('network manager is shutting down; event dispatch rejected')); + } + const operation = this.emitEventNow(event); + this.inFlightEmits.add(operation); + void operation.then( + () => { this.inFlightEmits.delete(operation); }, + () => { this.inFlightEmits.delete(operation); }, + ); + return operation; + } + + private async emitEventNow(event: JsonObject): Promise { // Notify debug taps first — before the adapter check — so the debug stream - // sees every event even when no adapter is connected. Never let a tap throw - // into the dispatch path. + // sees every event even when no adapter is connected. A diagnostic tap is + // isolated, but its failure is always logged with the root message. if (this.debugSubscribers.size) { for (const cb of this.debugSubscribers) { - try { cb(event); } catch (err) { log.warn('debug subscriber error: %s', errMessage(err)); } + try { cb(event); } catch (error) { log.warn('debug subscriber error: %s', errMessage(error)); } } } if (!this.hasActiveAdapters()) return; const payload = buildDispatchPayload(event); const tasks: Promise[] = []; - for (const adapter of this.adapters.values()) { + for (const { adapter } of this.adapters.values()) { if (!adapter.isActive) continue; tasks.push( Promise.resolve() .then(() => adapter.onEvent(event, payload)) - .catch((err) => { - log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err)); + .catch((error) => { + log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(error)); }), ); } await Promise.allSettled(tasks); } + + private async reconcileNow(desired: DesiredNetworkAdapter[]): Promise { + const errors: NetworkApplyError[] = []; + const desiredByName = new Map(desired.map((entry) => [entry.name, entry])); + + // Retire removed adapters first so their ports/resources are available to + // newly added entries in the same plan. Close is deliberately sequential. + for (const [name, live] of [...this.adapters]) { + if (desiredByName.has(name)) continue; + try { + await live.adapter.close(); + this.adapters.delete(name); + } catch (error) { + live.adapter.markApplyFailure(error); + errors.push(this.report(name, live.kind, 'close', error)); + } + } + + for (const next of desired) { + const live = this.adapters.get(next.name); + if (!live) { + await this.createAndOpen(next, errors); + } else if (live.kind === next.kind) { + await this.reloadSameKind(live, next, errors); + } else { + await this.replaceKind(live, next, errors); + } + } + + return this.result(errors); + } + + private async createAndOpen(next: DesiredNetworkAdapter, errors: NetworkApplyError[]): Promise { + let adapter: AnyAdapter; + try { + adapter = this.create(next); + } catch (error) { + errors.push(this.report(next.name, next.kind, 'open', error)); + return; + } + this.adapters.set(next.name, { kind: next.kind, adapter }); + try { + await adapter.open(); + adapter.clearApplyFailure(); + } catch (error) { + adapter.markApplyFailure(error); + errors.push(this.report(next.name, next.kind, 'open', error)); + } + } + + private async reloadSameKind( + live: ManagedAdapter, + next: DesiredNetworkAdapter, + errors: NetworkApplyError[], + ): Promise { + const previous = structuredClone(live.adapter.currentConfig); + try { + // A degraded adapter may still own a failed/ambiguous transport even if + // the desired binding signature is unchanged. Force a real release and + // reopen instead of letting reload() return Normal and clearing the + // evidence without recovery. + if (live.adapter.hasApplyFailure) await live.adapter.close(); + await live.adapter.reload(next.config); + live.adapter.clearApplyFailure(); + } catch (error) { + let restored = false; + try { + await live.adapter.reload(previous); + restored = true; + } catch (restoreError) { + errors.push(this.report(next.name, live.kind, 'restore', restoreError)); + } + live.adapter.markApplyFailure(error); + errors.push(this.report(next.name, next.kind, 'reload', error, restored)); + } + } + + private async replaceKind( + live: ManagedAdapter, + next: DesiredNetworkAdapter, + errors: NetworkApplyError[], + ): Promise { + try { + await live.adapter.close(); + } catch (error) { + live.adapter.markApplyFailure(error); + errors.push(this.report(next.name, live.kind, 'replace', error)); + return; + } + + let replacement: AnyAdapter; + try { + replacement = this.create(next); + } catch (error) { + let restored = false; + try { + await live.adapter.open(); + restored = true; + } catch (restoreError) { + errors.push(this.report(next.name, live.kind, 'restore', restoreError)); + } + // Whether restoration succeeds or not, the desired kind was not + // applied. Preserve that root failure on the still-managed old adapter. + live.adapter.markApplyFailure(error); + errors.push(this.report(next.name, next.kind, 'replace', error, restored)); + return; + } + this.adapters.set(next.name, { kind: next.kind, adapter: replacement }); + try { + await replacement.open(); + replacement.clearApplyFailure(); + return; + } catch (error) { + // The desired kind failed after the old resource was released. Clean up + // the partial replacement, then make a best-effort restoration of the + // previous live adapter. The original apply error remains the primary + // degraded reason even when restoration succeeds. + try { + await replacement.close(); + } catch (cleanupError) { + // The replacement may still own a bound resource. Keep it in the map + // and do not start the old adapter: overwriting this reference would + // orphan a potentially-live transport and could double-bind a port. + replacement.markApplyFailure(error); + errors.push(this.report(next.name, next.kind, 'close', cleanupError)); + errors.push(this.report(next.name, next.kind, 'replace', error, false)); + return; + } + + let restored = false; + try { + await live.adapter.open(); + live.adapter.markApplyFailure(error); + this.adapters.set(next.name, live); + restored = true; + } catch (restoreError) { + replacement.markApplyFailure(error); + errors.push(this.report(next.name, live.kind, 'restore', restoreError)); + } + errors.push(this.report(next.name, next.kind, 'replace', error, restored)); + } + } + + private create(next: DesiredNetworkAdapter): AnyAdapter { + if (!this.factory) throw new Error(`no network adapter factory configured for ${next.name}`); + const adapter = this.factory(next); + if (adapter.name !== next.name) { + throw new Error(`network adapter factory returned name ${adapter.name} for desired ${next.name}`); + } + return adapter; + } + + private result(errors: NetworkApplyError[]): NetworkReconcileResult { + return { + applied: errors.length === 0, + errors, + statuses: this.describeStatuses(), + }; + } + + private report( + name: string, + kind: NetworkAdapterKind, + phase: NetworkApplyPhase, + error: unknown, + restored?: boolean, + ): NetworkApplyError { + const detail: NetworkApplyError = { + name, + kind, + phase, + message: errMessage(error), + at: Date.now(), + ...(restored === undefined ? {} : { restored }), + }; + log.error( + 'adapter [%s] kind=%s phase=%s failed%s: %s', + name, + kind, + phase, + restored === undefined ? '' : ` restored=${String(restored)}`, + detail.message, + ); + return detail; + } + + private enqueue(operation: () => Promise): Promise { + const result = this.operationTail.then(operation); + // Keep the FIFO usable after a rejected invariant/programming error. The + // returned promise still rejects, so no error is hidden from its caller. + this.operationTail = result.then( + () => undefined, + () => undefined, + ); + return result; + } } -function errMessage(err: unknown): string { - return err instanceof Error ? err.message : String(err); +function errMessage(error: unknown): string { + return error instanceof Error ? error.message : String(error); } diff --git a/packages/onebot/src/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts index 910e1495..baa73f17 100644 --- a/packages/onebot/src/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -27,6 +27,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { private options: EventReportOptions; private role: WsRole; private explicitlyClosed = false; + private acceptingActions = false; + private readonly inFlightActions = new Set>(); // Stop fn for the CURRENT socket's keepalive, so close()/reload can halt it // immediately instead of waiting for the deferred 'close' event. The per-socket // closure in connect() still owns the #97 stale-socket case; this is idempotent @@ -45,11 +47,22 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { if (!this.config.url) return; this.explicitlyClosed = false; this.isEnabled = true; - this.connect(); + try { + this.connect(); + this.acceptingActions = true; + this.clearApplyFailure(); + } catch (error) { + this.isEnabled = false; + this.explicitlyClosed = true; + this.acceptingActions = false; + this.recordTransportFailure(error); + throw error; + } } - close(): void { + async close(): Promise { this.explicitlyClosed = true; + this.acceptingActions = false; this.isEnabled = false; this.connected = false; this.cancelReconnect(); @@ -59,6 +72,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { safeClose(this.socket); this.socket = null; } + await Promise.all(this.inFlightActions); } override describeStatus(): AdapterStatus { @@ -131,9 +145,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { }); socket.on('message', (raw: Buffer) => { - void this.handleApiMessage(socket, raw).catch((err) => { - this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); - }); + if (this.socket !== socket) { + this.log.warn('[%s] rejected inbound action from stale socket', this.name); + return; + } + this.trackInboundAction(() => this.handleApiMessage(socket, raw)); }); socket.on('close', () => { @@ -193,9 +209,30 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { ); } + private trackInboundAction(start: () => Promise): void { + if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) { + this.log.warn('[%s] rejected inbound action while adapter is closing', this.name); + return; + } + let action: Promise; + try { + action = start(); + } catch (error) { + this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error)); + return; + } + const tracked = action.then( + () => undefined, + (error) => { + this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error)); + }, + ); + this.inFlightActions.add(tracked); + void tracked.then(() => { this.inFlightActions.delete(tracked); }); + } + private sendBootstrapMetaEvents(socket: WebSocket): void { if (this.role !== 'Event' && this.role !== 'Universal') return; for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame); } } - diff --git a/packages/onebot/src/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts index 088d03a0..e7a0b2e3 100644 --- a/packages/onebot/src/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -30,6 +30,9 @@ interface ForwardConn { export class WsServerAdapter extends IOneBotNetworkAdapter { private wss: WebSocketServer | null = null; private listening = false; + private closePromise: Promise | null = null; + private acceptingActions = false; + private readonly inFlightActions = new Set>(); private connections = new Map(); private options: EventReportOptions; @@ -38,15 +41,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.options = resolveReportOptions(config); } - open(): void { - if (this.isEnabled) return; + async open(): Promise { + if (this.isEnabled && this.listening) return; if (this.config.enabled === false) return; - this.startServer(); + if (this.wss) throw new Error(`WebSocket adapter [${this.name}] still owns a previous server`); + await this.startServer(); this.isEnabled = true; + this.clearApplyFailure(); } - close(): void { - if (!this.isEnabled && this.connections.size === 0 && !this.wss) return; + async close(): Promise { + if (this.closePromise) return this.closePromise; + if (!this.isEnabled && this.connections.size === 0 && !this.wss && this.inFlightActions.size === 0) return; + const wasEnabled = this.isEnabled; + const wasListening = this.listening; + const wasAcceptingActions = this.acceptingActions; + this.acceptingActions = false; // Final lifecycle broadcast before tearing down so attached event clients // see the disable transition. const lifecycle = this.ctx.buildLifecycleEvent('disable'); @@ -63,8 +73,31 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { safeClose(conn.socket); } this.connections.clear(); - this.wss?.close(); - this.wss = null; + const wss = this.wss; + const releaseResult: Promise<{ error?: Error }> = wss + ? new Promise<{ error?: Error }>((resolve) => { + wss.close((error) => resolve(error && !isAlreadyClosedError(error) ? { error } : {})); + }) + : Promise.resolve({}); + const attempt = (async () => { + await Promise.all(this.inFlightActions); + const release = await releaseResult; + if (release.error) throw release.error; + })(); + this.closePromise = attempt; + try { + await attempt; + if (wss && this.wss === wss) this.wss = null; + } catch (error) { + // A failed close callback leaves release ambiguous. Retain the server + // reference and active binding state so a later shutdown can retry. + this.isEnabled = wasEnabled; + this.listening = wasListening; + this.acceptingActions = wasAcceptingActions; + throw error; + } finally { + this.closePromise = null; + } } override describeStatus(): AdapterStatus { @@ -92,34 +125,67 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { } } - private startServer(): void { - const wss = new WebSocketServer({ - host: this.config.host ?? '0.0.0.0', - port: this.config.port, - path: this.config.path ?? '/', - }); - this.wss = wss; + private startServer(): Promise { + return new Promise((resolve, reject) => { + let wss: WebSocketServer; + try { + wss = new WebSocketServer({ + host: this.config.host ?? '0.0.0.0', + port: this.config.port, + path: normalizePath(this.config.path), + }); + } catch (error) { + this.recordTransportFailure(error); + reject(error); + return; + } + this.wss = wss; + let opening = true; - wss.on('listening', () => { - this.listening = true; - this.log.success( - '[%s] listening %s:%d%s', - this.name, - this.config.host ?? '0.0.0.0', - this.config.port, - this.config.path ?? '/', - ); - }); + wss.once('listening', () => { + opening = false; + if (this.wss !== wss || this.closePromise) { + wss.close(); + reject(new Error(`WebSocket adapter [${this.name}] was closed while binding`)); + return; + } + this.listening = true; + this.isEnabled = true; + this.acceptingActions = true; + this.log.success( + '[%s] listening %s:%d%s', + this.name, + this.config.host ?? '0.0.0.0', + this.config.port, + this.config.path ?? '/', + ); + resolve(); + }); - wss.on('error', (err: Error) => { - this.listening = false; - this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); - }); + wss.on('error', (error: Error) => { + if (this.wss === wss) { + this.listening = false; + this.isEnabled = false; + this.acceptingActions = false; + this.recordTransportFailure(error); + if (opening) this.wss = null; + } + this.log.error('[%s] server error: %s', this.name, error instanceof Error ? error.message : String(error)); + if (opening) { + opening = false; + reject(error); + } + }); - wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request)); + wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request)); + }); } private onConnection(socket: WebSocket, request: IncomingMessage): void { + if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) { + safeClose(socket, 1012, 'server closing'); + return; + } if (!isAuthorized(request, this.config.accessToken ?? '')) { safeClose(socket, 1008, 'invalid access token'); return; @@ -138,9 +204,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.connections.set(socket, conn); socket.on('message', (raw: Buffer) => { - void this.handleApiMessage(socket, role, raw).catch((err) => { - this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); - }); + this.trackInboundAction(() => this.handleApiMessage(socket, role, raw)); }); socket.on('close', () => { stopHeartbeat(); @@ -170,11 +234,37 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { ); } + private trackInboundAction(start: () => Promise): void { + if (!this.acceptingActions || this.ctx.api.isAcceptingActions === false) { + this.log.warn('[%s] rejected inbound action while adapter is closing', this.name); + return; + } + let action: Promise; + try { + action = start(); + } catch (error) { + this.log.error('[%s] inbound action start failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error)); + return; + } + const tracked = action.then( + () => undefined, + (error) => { + this.log.error('[%s] inbound action failed: %s', this.name, error instanceof Error ? (error.stack ?? error.message) : String(error)); + }, + ); + this.inFlightActions.add(tracked); + void tracked.then(() => { this.inFlightActions.delete(tracked); }); + } + private sendBootstrapMetaEvents(socket: WebSocket): void { for (const frame of this.bootstrapMetaFrames(this.options)) safeSend(socket, frame); } } +function isAlreadyClosedError(error: Error): boolean { + return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING'; +} + function classifyForwardRole(request: IncomingMessage): WsRole { const path = parseRequestPath(request.url ?? '/'); if (path.endsWith('/api')) return 'Api'; diff --git a/packages/onebot/src/temp-session-store.ts b/packages/onebot/src/temp-session-store.ts new file mode 100644 index 00000000..713811c9 --- /dev/null +++ b/packages/onebot/src/temp-session-store.ts @@ -0,0 +1,51 @@ +/** + * Records the group temp sessions the bot has received a message from, so a + * reply can be limited to sessions the peer opened. Written only on the receive + * path, read only on the send path. Keyed by `${userUin}:${groupUin}` — a user + * may hold sessions from several groups. Entries expire after + * {@link TEMP_SESSION_TTL_MS}. + */ + +/** Reply window: 7 days after the last inbound temp message. */ +export const TEMP_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000; + +export class TempSessionStore { + /** key → expiry epoch ms. */ + private readonly sessions = new Map(); + + private static key(userUin: number, groupUin: number): string { + return `${userUin}:${groupUin}`; + } + + /** + * Record (or refresh) an inbound temp session. Called from the receive path. + * No-op without a source group (groupUin<=0) — the session stays receive-only. + */ + record(userUin: number, groupUin: number, now: number = Date.now()): void { + if (userUin <= 0 || groupUin <= 0) return; + // Opportunistically prune expired entries here — `has` only removes keys it + // reads, so a stream of never-replied sessions would otherwise grow the map + // unbounded. + this.sweep(now); + this.sessions.set(TempSessionStore.key(userUin, groupUin), now + TEMP_SESSION_TTL_MS); + } + + /** True iff a reply is allowed for this exact (user, group). Prunes on read. */ + has(userUin: number, groupUin: number, now: number = Date.now()): boolean { + const key = TempSessionStore.key(userUin, groupUin); + const expiresAt = this.sessions.get(key); + if (expiresAt === undefined) return false; + if (expiresAt <= now) { + this.sessions.delete(key); + return false; + } + return true; + } + + /** Drop all expired entries. `has` also prunes lazily. */ + sweep(now: number = Date.now()): void { + for (const [key, expiresAt] of this.sessions) { + if (expiresAt <= now) this.sessions.delete(key); + } + } +} diff --git a/packages/onebot/tests/action-registry.test.ts b/packages/onebot/tests/action-registry.test.ts new file mode 100644 index 00000000..8919e227 --- /dev/null +++ b/packages/onebot/tests/action-registry.test.ts @@ -0,0 +1,223 @@ +import { describe, expect, it } from 'vitest'; +import { defineAction, defineStreamAction, type RegisteredActionSpec } from '../src/action-kit'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import { + ACTION_REGISTRY, + HANDLE_QUICK_OPERATION_ACTION, + RAW_ACTION_RESERVATIONS, + compileActionRegistry, + type ActionGroup, + type RawActionReservation, +} from '../src/actions'; +import { collectActionDocs } from '../src/action-docs'; +import { okResponse } from '../src/types'; + +type ActionNames = string | readonly [string, ...string[]]; + +function normal(name: ActionNames): RegisteredActionSpec { + return defineAction({ name, params: {}, run: () => okResponse() }); +} + +function stream(name: ActionNames): RegisteredActionSpec { + return defineStreamAction({ name, params: {}, run: () => okResponse() }); +} + +function groups(...actions: RegisteredActionSpec[]): readonly ActionGroup[] { + return [{ category: 'test', actions }]; +} + +function conflict( + actionGroups: readonly ActionGroup[], + raw: readonly RawActionReservation[] = [], +): string { + try { + compileActionRegistry(actionGroups, raw); + } catch (error) { + if (error instanceof Error) return error.message; + throw error; + } + throw new Error('expected registry compilation to fail'); +} + +describe('compileActionRegistry namespace conflicts', () => { + it('rejects canonical ↔ canonical', () => { + const message = conflict(groups(normal('shared'), normal('shared'))); + expect(message).toContain('executable name "shared"'); + expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)'); + }); + + it.each([ + ['canonical first', [normal('shared'), normal(['owner', 'shared'])]], + ['alias first', [normal(['owner', 'shared']), normal('shared')]], + ] as const)('rejects canonical ↔ alias (%s)', (_label, specs) => { + const message = conflict(groups(...specs)); + expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)'); + expect(message).toContain('canonical "owner" (name "shared", kind normal, role alias)'); + }); + + it('rejects alias ↔ alias', () => { + const message = conflict(groups(normal(['first', 'shared']), normal(['second', 'shared']))); + expect(message).toContain('canonical "first" (name "shared", kind normal, role alias)'); + expect(message).toContain('canonical "second" (name "shared", kind normal, role alias)'); + }); + + it('rejects normal ↔ stream and reports both kinds', () => { + const message = conflict(groups(normal('shared'), stream('shared'))); + expect(message).toContain('canonical "shared" (name "shared", kind normal, role canonical)'); + expect(message).toContain('canonical "shared" (name "shared", kind stream, role canonical)'); + }); + + it.each([ + ['canonical', normal(HANDLE_QUICK_OPERATION_ACTION), 'role canonical'], + ['alias', normal(['owner', HANDLE_QUICK_OPERATION_ACTION]), 'role alias'], + ] as const)('rejects a declarative %s colliding with a reserved raw action', (_label, spec, role) => { + const message = conflict(groups(spec), [ + { name: HANDLE_QUICK_OPERATION_ACTION, canonical: HANDLE_QUICK_OPERATION_ACTION }, + ]); + expect(message).toContain(`name "${HANDLE_QUICK_OPERATION_ACTION}"`); + expect(message).toContain(`kind normal, ${role}`); + expect(message).toContain('kind raw, role raw'); + }); + + it('rejects duplicate raw reservations', () => { + const message = conflict([], [ + { name: 'raw', canonical: 'first-raw' }, + { name: 'raw', canonical: 'second-raw' }, + ]); + expect(message).toContain('canonical "first-raw" (name "raw", kind raw, role raw)'); + expect(message).toContain('canonical "second-raw" (name "raw", kind raw, role raw)'); + }); +}); + +describe('compiled production Action registry', () => { + it('preserves all 179 canonical Action docs', () => { + expect(ACTION_REGISTRY.actions).toHaveLength(179); + expect(collectActionDocs()).toHaveLength(179); + }); + + it('resolves every executable name to exactly one canonical doc', () => { + const docs = new Map(collectActionDocs().map((doc) => [doc.name, doc])); + + for (const executable of ACTION_REGISTRY.executableNames) { + expect(ACTION_REGISTRY.resolve(executable.name)).toBe(executable); + if (executable.kind === 'raw') { + expect(executable.name).toBe(HANDLE_QUICK_OPERATION_ACTION); + expect(docs.has(executable.canonical)).toBe(false); + continue; + } + + const doc = docs.get(executable.canonical); + expect(doc, executable.name).toBeDefined(); + expect(executable.action.doc).toEqual(doc); + expect(executable.action.kind).toBe(doc!.stream === true ? 'stream' : 'normal'); + expect([doc!.name, ...doc!.aliases]).toContain(executable.name); + } + }); + + it('registers the exact compiled executable-name/kind projection at runtime', () => { + const registered: Array<[string, 'normal' | 'stream']> = []; + const fakeHandler = { + registerAction: (name: string) => { registered.push([name, 'normal']); }, + registerStreamAction: (name: string) => { registered.push([name, 'stream']); }, + } as unknown as ApiHandler; + + ACTION_REGISTRY.register(fakeHandler, {} as ApiActionContext); + + expect(registered).toEqual( + ACTION_REGISTRY.executableNames + .filter((entry) => entry.kind !== 'raw') + .map((entry) => [entry.name, entry.kind]), + ); + }); +}); + +describe('ApiHandler constructor-time registry transaction', () => { + const handler = async () => okResponse(); + + function testRegistry(...specs: RegisteredActionSpec[]) { + return compileActionRegistry(groups(...specs), RAW_ACTION_RESERVATIONS); + } + + function withRegistration( + base: RegisteredActionSpec, + register: RegisteredActionSpec['register'], + ): RegisteredActionSpec { + return { kind: base.kind, names: base.names, describe: base.describe, register }; + } + + it('binds only names declared by the injected complete registry, then seals', async () => { + const api = new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(normal('__registry_normal__')), + ); + expect((await api.handle('__registry_normal__', {})).status).toBe('ok'); + expect(api.isStreamAction('__registry_normal__')).toBe(false); + expect(() => api.registerAction('__rogue__', handler)).toThrow(/Action registry is sealed/); + expect((await api.handle('__rogue__', {})).retcode).toBe(1404); + }); + + it('keeps stream classification bound to the sealed compiled claim', () => { + const api = new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(stream('__registry_stream__')), + ); + expect(() => api.registerAction('__registry_stream__', handler)).toThrow( + /Action registry is sealed/, + ); + expect(api.isStreamAction('__registry_stream__')).toBe(true); + }); + + it('rejects a spec that registers an undeclared executable name', () => { + const base = normal('declared'); + const malicious = withRegistration(base, (api) => api.registerAction('rogue', handler)); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/not declared.*canonical "rogue".*name "rogue".*kind normal/); + }); + + it('rejects a spec whose registration kind disagrees with its compiled claim', () => { + const base = normal('declared'); + const malicious = withRegistration(base, (api) => api.registerStreamAction('declared', handler)); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/kind mismatch.*canonical "declared".*registry kind normal, registration kind stream/); + }); + + it('rejects duplicate constructor-time handler binding', () => { + const base = normal('declared'); + const malicious = withRegistration(base, (api) => { + api.registerAction('declared', handler); + api.registerAction('declared', handler); + }); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/canonical "declared".*kind normal.*conflicts with.*canonical "declared".*kind normal/); + }); + + it('rejects a compiled claim that did not bind a handler', () => { + const base = normal('declared'); + const malicious = withRegistration(base, () => {}); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + testRegistry(malicious), + )).toThrow(/claim has no handler.*canonical "declared".*name "declared".*kind normal/); + }); + + it('requires the raw quick-operation reservation in an injected registry', () => { + const incomplete = compileActionRegistry(groups(normal('declared'))); + expect(() => new ApiHandler( + {} as ApiActionContext, + undefined, + incomplete, + )).toThrow(/not declared.*handle_quick_operation.*kind raw/); + }); +}); diff --git a/packages/onebot/tests/api-handler-lifecycle.test.ts b/packages/onebot/tests/api-handler-lifecycle.test.ts new file mode 100644 index 00000000..d24c232b --- /dev/null +++ b/packages/onebot/tests/api-handler-lifecycle.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it, vi } from 'vitest'; +import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler'; + +describe('ApiHandler lifecycle ingress', () => { + it('permanently rejects new Actions after quiesce', async () => { + const run = vi.fn(async () => ({ status: 'ok' as const, retcode: 0, data: null })); + const handler = createCompiledTestHandler({} as never, [testAction('probe', run)], 10001); + + expect(handler.isAcceptingActions).toBe(true); + handler.quiesce(); + handler.quiesce(); + + await expect(handler.handle('probe', {})).resolves.toMatchObject({ + status: 'failed', + retcode: 100, + wording: 'OneBot instance is shutting down', + }); + expect(handler.isAcceptingActions).toBe(false); + expect(run).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/api-handler-logging.test.ts b/packages/onebot/tests/api-handler-logging.test.ts index 5aef018f..d665814d 100644 --- a/packages/onebot/tests/api-handler-logging.test.ts +++ b/packages/onebot/tests/api-handler-logging.test.ts @@ -5,13 +5,13 @@ // from blowing the line width. import { afterEach, beforeEach, describe, expect, it } from 'vitest'; -import { ApiHandler } from '../src/api-handler'; +import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; import { OidbError } from '@snowluma/protocol/oidb-service'; import { subscribeLogs, type LogEntry } from '@snowluma/common/logger'; import { summarizeParams } from '@snowluma/common/log-summary'; +import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler'; -// Minimal context — we never reach the real action handlers; we -// register our own via registerAction. +// Minimal context — isolated test ActionSpecs never call these dependencies. function emptyContext(): any { return { bridge: {}, @@ -79,8 +79,9 @@ describe('summarizeParams', () => { describe('ApiHandler dispatch logging', () => { it('emits a debug entry under [Bridge.Action] when an action is called', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null })); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('echo', async () => ({ status: 'ok', retcode: 0, data: null })), + ], 12345); await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] }); @@ -93,10 +94,9 @@ describe('ApiHandler dispatch logging', () => { }); it('emits a warn line with the error stack when the handler throws', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('boom', async () => { - throw new Error('kapow'); - }); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('boom', async () => { throw new Error('kapow'); }), + ], 12345); const result = await handler.handle('boom', {}); expect(result.status).toBe('failed'); @@ -113,16 +113,37 @@ describe('ApiHandler dispatch logging', () => { // 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 handler = createCompiledTestHandler(emptyContext(), [ + testAction('kaboom', async () => { throw new Error('permission denied'); }), + ], 12345); const result = await handler.handle('kaboom', {}); expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'permission denied' }); }); + it('maps typed outbound message-contract failures to BAD_REQUEST', async () => { + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('bad_message', async () => { + throw new MessageElementValidationError( + 'UNKNOWN_TYPE', + 'unknown message segment type: surprise', + 'surprise', + ); + }), + ], 12345); + + const result = await handler.handle('bad_message', {}); + expect(result).toMatchObject({ + status: 'failed', + retcode: 1400, + wording: 'unknown message segment type: surprise', + }); + }); + 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 handler = createCompiledTestHandler(emptyContext(), [ + testAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); }), + ], 12345); const result = await handler.handle('oidb_boom', {}); expect(result).toMatchObject({ status: 'failed', retcode: 100 }); @@ -131,15 +152,16 @@ describe('ApiHandler dispatch logging', () => { }); it('renders a non-Error throw via String()', async () => { - const handler = new ApiHandler(emptyContext(), 12345); - handler.registerAction('weird', async () => { throw 'just a string'; }); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('weird', async () => { throw 'just a string'; }), + ], 12345); 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); + const handler = createCompiledTestHandler(emptyContext(), [], 99); await handler.handle('not_a_real_action', {}); const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action')); @@ -148,8 +170,9 @@ describe('ApiHandler dispatch logging', () => { }); it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => { - const handler = new ApiHandler(emptyContext()); - handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null })); + const handler = createCompiledTestHandler(emptyContext(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0, data: null })), + ]); await handler.handle('ping', {}); diff --git a/packages/onebot/tests/backfill-reply-target.test.ts b/packages/onebot/tests/backfill-reply-target.test.ts index 2c1436d6..a4d2413e 100644 --- a/packages/onebot/tests/backfill-reply-target.test.ts +++ b/packages/onebot/tests/backfill-reply-target.test.ts @@ -29,14 +29,14 @@ function groupEvent(replySeq: number | null) { const elements: any[] = replySeq != null ? [{ type: 'reply', replySeq }] : []; elements.push({ type: 'text', text: '同意' }); return { - kind: 'group_message', time: 1, selfUin: SELF, groupId: 700, senderUin: 900, + kind: 'group_message', groupName: '', time: 1, selfUin: SELF, groupId: 700, senderUin: 900, senderNick: '', senderCard: '', senderRole: 'member', msgSeq: 999, msgId: 2, elements, } as any; } function fetchedGroupMessage(msgSeq: number) { return { - kind: 'group_message', time: 1700000000, selfUin: SELF, groupId: 700, senderUin: 800, + kind: 'group_message', groupName: '', time: 1700000000, selfUin: SELF, groupId: 700, senderUin: 800, senderNick: 'orig', senderCard: '', senderRole: 'member', msgSeq, msgId: 1, elements: [{ type: 'text', text: 'quoted' }], } as any; @@ -153,7 +153,7 @@ describe('backfillReplyTarget', () => { bridge: { apis: { message: { getGroupMessageBySeq } }, resolveUserUid: vi.fn() }, } as any; const event = { - kind: 'group_message', time: 1, selfUin: SELF, groupId: 700, senderUin: 900, + kind: 'group_message', groupName: '', time: 1, selfUin: SELF, groupId: 700, senderUin: 900, senderNick: '', senderCard: '', senderRole: 'member', msgSeq: 999, msgId: 2, elements: [{ type: 'reply', replySeq: 123, replySenderUin: 800, replyElements: [{ type: 'text', text: 'quoted' }] }], } as any; diff --git a/packages/onebot/tests/config.test.ts b/packages/onebot/tests/config.test.ts index 9c0b39b9..c0cfdf94 100644 --- a/packages/onebot/tests/config.test.ts +++ b/packages/onebot/tests/config.test.ts @@ -1,8 +1,14 @@ -import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import fs from 'fs'; import os from 'os'; import path from 'path'; -import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig, STATUS_COMMAND_TRIGGER_MAX_LENGTH } from '../src/config'; +import { + assertValidOneBotConfig, + loadOneBotConfig, + makeDefaultOneBotConfig, + saveOneBotConfig, + STATUS_COMMAND_TRIGGER_MAX_LENGTH, +} from '../src/config'; const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/; @@ -29,6 +35,190 @@ describe('makeDefaultOneBotConfig', () => { }); }); +describe('assertValidOneBotConfig', () => { + it('rejects duplicate adapter names across different kinds', () => { + const config = makeDefaultOneBotConfig(); + config.networks.httpClients.push({ + name: 'http-default', + url: 'http://127.0.0.1:5700', + messageFormat: 'array', + reportSelfMessage: false, + }); + + expect(() => assertValidOneBotConfig(config)).toThrow( + /duplicated in httpServers and httpClients/, + ); + }); + + it('allows a disabled client draft with an empty URL', () => { + const config = makeDefaultOneBotConfig(); + config.networks.httpClients.push({ + name: 'disabled-draft', + enabled: false, + url: '', + messageFormat: 'array', + reportSelfMessage: false, + }); + + expect(() => assertValidOneBotConfig(config)).not.toThrow(); + }); + + it('rejects enabled clients with malformed or wrong-protocol URLs', () => { + const http = makeDefaultOneBotConfig(); + http.networks.httpClients.push({ + name: 'bad-http', + url: 'not a url', + messageFormat: 'array', + reportSelfMessage: false, + }); + expect(() => assertValidOneBotConfig(http)).toThrow(/valid absolute URL/); + + const ws = makeDefaultOneBotConfig(); + ws.networks.wsClients.push({ + name: 'bad-ws', + url: 'https://example.com/socket', + messageFormat: 'array', + reportSelfMessage: false, + }); + expect(() => assertValidOneBotConfig(ws)).toThrow(/protocol must be one of ws:, wss:/); + }); + + it('rejects enabled servers with the same normalized host and port', () => { + const config = makeDefaultOneBotConfig(); + config.networks.wsServers.push({ + name: 'conflicting-ws', + host: '0.0.0.0', + port: 3000, + path: '/different-path', + messageFormat: 'array', + reportSelfMessage: false, + }); + + expect(() => assertValidOneBotConfig(config)).toThrow( + /conflicts with networks\.httpServers\[0\] on server binding 0\.0\.0\.0:3000/, + ); + }); + + it('rejects blank hosts and wildcard/specific listeners on the same port', () => { + const blank = makeDefaultOneBotConfig(); + blank.networks.httpServers[0].host = ' '; + expect(() => assertValidOneBotConfig(blank)).toThrow(/\.host/); + + const wildcard = makeDefaultOneBotConfig(); + wildcard.networks.wsServers.push({ + name: 'specific-ws', + host: '127.0.0.1', + port: 3000, + path: '/ws', + messageFormat: 'array', + reportSelfMessage: false, + }); + expect(() => assertValidOneBotConfig(wildcard)).toThrow(/wildcard server port 3000/); + }); + + it('rejects timer values that Node would clamp to a 1ms loop', () => { + const http = makeDefaultOneBotConfig(); + http.networks.httpClients.push({ + name: 'overflow-http', + url: 'http://127.0.0.1:5700', + timeoutMs: 1e100, + messageFormat: 'array', + reportSelfMessage: false, + }); + expect(() => assertValidOneBotConfig(http)).toThrow(/timeoutMs/); + + const ws = makeDefaultOneBotConfig(); + ws.networks.wsClients.push({ + name: 'overflow-ws', + url: 'ws://127.0.0.1:5700', + reconnectIntervalMs: 2_147_483_648, + messageFormat: 'array', + reportSelfMessage: false, + }); + expect(() => assertValidOneBotConfig(ws)).toThrow(/reconnectIntervalMs/); + }); + + it('rejects server paths that cannot match a URL pathname', () => { + for (const invalidPath of ['api', '/api?token=x', '/api#fragment', ' /api']) { + const config = makeDefaultOneBotConfig(); + config.networks.httpServers[0].path = invalidPath; + expect(() => assertValidOneBotConfig(config), invalidPath).toThrow(/\.path/); + } + const valid = makeDefaultOneBotConfig(); + valid.networks.httpServers[0].path = ''; + expect(() => assertValidOneBotConfig(valid)).not.toThrow(); + }); +}); + +describe('saveOneBotConfig validation boundary', () => { + it('does not write an invalid enabled-client URL to disk', () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-invalid-save-')); + const previous = process.cwd(); + process.chdir(tempDir); + try { + const config = makeDefaultOneBotConfig(); + config.networks.wsClients.push({ + name: 'bad-client', + url: 'javascript:alert(1)', + messageFormat: 'array', + reportSelfMessage: false, + }); + + expect(() => saveOneBotConfig('10001', config)).toThrow(/protocol must be one of ws:, wss:/); + expect(fs.existsSync(path.join(tempDir, 'config', 'onebot_10001.json'))).toBe(false); + } finally { + process.chdir(previous); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it('does not write a deterministic server bind conflict to disk', () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-bind-conflict-')); + const previous = process.cwd(); + process.chdir(tempDir); + try { + const config = makeDefaultOneBotConfig(); + config.networks.wsServers.push({ + name: 'same-bind', + port: 3000, + path: '/ws', + messageFormat: 'array', + reportSelfMessage: false, + }); + + expect(() => saveOneBotConfig('10001', config)).toThrow(/server binding 0\.0\.0\.0:3000/); + expect(fs.existsSync(path.join(tempDir, 'config', 'onebot_10001.json'))).toBe(false); + } finally { + process.chdir(previous); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); + + it('preserves the previous desired config when the atomic rename fails', () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-atomic-save-')); + const previous = process.cwd(); + process.chdir(tempDir); + try { + const original = makeDefaultOneBotConfig(); + saveOneBotConfig('10001', original); + const changed = structuredClone(original); + changed.networks.httpServers[0].port = 3999; + const rename = vi.spyOn(fs, 'renameSync').mockImplementationOnce(() => { + throw new Error('injected rename failure'); + }); + expect(() => saveOneBotConfig('10001', changed)).toThrow(/injected rename failure/); + rename.mockRestore(); + + expect(loadOneBotConfig('10001').networks.httpServers[0].port).toBe(3000); + expect(fs.readdirSync(path.join(tempDir, 'config')).some((name) => name.endsWith('.tmp'))).toBe(false); + } finally { + vi.restoreAllMocks(); + process.chdir(previous); + fs.rmSync(tempDir, { recursive: true, force: true }); + } + }); +}); + describe('loadOneBotConfig', () => { let tempDir: string; let prevCwd: string; @@ -147,6 +337,52 @@ describe('loadOneBotConfig', () => { expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true); }); + it('replays a saved per-UIN snapshot without reviving deleted global adapters', () => { + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + const global = makeDefaultOneBotConfig(); + global.networks.httpServers[0].name = 'inherited'; + fs.writeFileSync(path.join(dir, 'onebot.json'), JSON.stringify(global), 'utf8'); + + const config = loadOneBotConfig('10004'); + expect(config.networks.httpServers.map((item) => item.name)).toContain('inherited'); + config.networks.httpServers = []; + config.networks.wsServers.push({ + name: 'inherited', + host: '127.0.0.1', + port: 3998, + path: '/', + role: 'Universal', + messageFormat: 'array', + reportSelfMessage: false, + }); + saveOneBotConfig('10004', config); + + const reloaded = loadOneBotConfig('10004'); + expect(reloaded.networks.httpServers).toEqual([]); + expect(reloaded.networks.wsServers.map((item) => item.name)).toContain('inherited'); + const disk = JSON.parse(fs.readFileSync(path.join(dir, 'onebot_10004.json'), 'utf8')); + expect(disk.mode).toBe('snapshot'); + }); + + it('fails fast instead of replacing a corrupt per-UIN desired config with defaults', () => { + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'onebot_10005.json'), '{broken', 'utf8'); + + expect(() => loadOneBotConfig('10005', { persistDefaults: true })).toThrow(/is corrupt/); + expect(fs.readFileSync(path.join(dir, 'onebot_10005.json'), 'utf8')).toBe('{broken'); + }); + + it('treats a valid JSON non-object root as corrupt desired state', () => { + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'onebot_10006.json'), '[]', 'utf8'); + + expect(() => loadOneBotConfig('10006', { persistDefaults: true })).toThrow(/root must be an object/); + expect(fs.readFileSync(path.join(dir, 'onebot_10006.json'), 'utf8')).toBe('[]'); + }); + it('fills new statusCommand fields with defaults when absent', () => { const uin = '10042'; const dir = path.join(tempDir, 'config'); @@ -337,4 +573,3 @@ describe('OneBotConfig.notifications (per-UIN channel opt-in)', () => { expect(onDisk.notifications).toEqual({ channelIds: ['discord', 'serverchan'] }); }); }); - diff --git a/packages/onebot/tests/contact-actions.test.ts b/packages/onebot/tests/contact-actions.test.ts index 1d3b5f03..34a3fb7c 100644 --- a/packages/onebot/tests/contact-actions.test.ts +++ b/packages/onebot/tests/contact-actions.test.ts @@ -6,7 +6,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { - FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, + FriendInfo, GroupMemberInfo, GroupRequestInfo, QQGroupInfo, UserProfileInfo, } from '@snowluma/protocol/qq-info'; import { getFriendList, @@ -14,6 +14,7 @@ import { getGroupList, getGroupMemberInfo, getGroupMemberList, + getGroupSystemMessages, getLoginInfo, getStrangerInfo, } from '../src/modules/contact-actions'; @@ -93,6 +94,28 @@ function makeProfile(uin: number, nickname: string, sex: 'male' | 'female' | 'un }; } +function makeGroupRequest(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 999, + groupName: 'group', + targetUid: 'u_target', + targetUin: 123, + targetName: 'target', + invitorUid: 'u_inviter', + invitorUin: 456, + invitorName: 'inviter', + operatorUid: 'u_operator', + operatorUin: 789, + operatorName: 'operator', + sequence: 123456, + state: 1, + eventType: 22, + comment: 'please', + filtered: false, + ...overrides, + }; +} + // ─── Tests ─── describe('onebot/contact-actions / getLoginInfo', () => { @@ -355,3 +378,22 @@ describe('onebot/contact-actions / getStrangerInfo', () => { expect(await getStrangerInfo(bridge, 99999)).toBeNull(); }); }); + +describe('onebot/contact-actions / getGroupSystemMessages', () => { + it('returns the same canonical flag accepted by set_group_add_request', async () => { + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async () => [ + makeGroupRequest({ sequence: 123456, groupId: 999, eventType: 22, filtered: true }), + ]), + }); + + const result = await getGroupSystemMessages(bridge); + + expect(result).toHaveLength(1); + expect(result[0]).toMatchObject({ + request_id: 123456, + group_id: 999, + flag: 'slreq:1:123456:999:22:1', + }); + }); +}); diff --git a/packages/onebot/tests/debug-seams.test.ts b/packages/onebot/tests/debug-seams.test.ts index 6102d230..9ac4f973 100644 --- a/packages/onebot/tests/debug-seams.test.ts +++ b/packages/onebot/tests/debug-seams.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi } from 'vitest'; import { OneBotNetworkManager } from '../src/network/network-manager'; -import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import type { ApiActionContext } from '../src/api-handler'; +import { createCompiledTestHandler, testAction } from './helpers/compiled-action-handler'; // ApiHandler's register* only define handlers (closures) at construction — they // don't touch ctx — so a throwing proxy is a safe minimal context. @@ -39,8 +40,9 @@ describe('OneBotNetworkManager.subscribeDebug', () => { describe('ApiHandler.setObserver', () => { it('fires after a successful action with {action, params, response, ms}', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' })); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0, data: 'pong' })), + ]); const recs: Array<{ action: string; response: { status: string } }> = []; h.setObserver((r) => recs.push(r as any)); const res = await h.handle('ping', { x: 1 }); @@ -51,8 +53,9 @@ describe('ApiHandler.setObserver', () => { }); it('fires on a thrown action with the failure response', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('boom', async () => { throw new Error('kaboom'); }); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('boom', async () => { throw new Error('kaboom'); }), + ]); const recs: any[] = []; h.setObserver((r) => recs.push(r)); await h.handle('boom', {}); @@ -61,8 +64,9 @@ describe('ApiHandler.setObserver', () => { }); it('unsubscribe stops observation', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 })); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0 })), + ]); const cb = vi.fn(); const off = h.setObserver(cb); await h.handle('ping', {}); @@ -72,8 +76,9 @@ describe('ApiHandler.setObserver', () => { }); it('a throwing observer does not break handle', async () => { - const h = new ApiHandler(fakeCtx()); - h.registerAction('ping', async () => ({ status: 'ok', retcode: 0 })); + const h = createCompiledTestHandler(fakeCtx(), [ + testAction('ping', async () => ({ status: 'ok', retcode: 0 })), + ]); h.setObserver(() => { throw new Error('observer boom'); }); await expect(h.handle('ping', {})).resolves.toMatchObject({ status: 'ok' }); }); diff --git a/packages/onebot/tests/element-manifest.test.ts b/packages/onebot/tests/element-manifest.test.ts index 69ce8f49..b5a2f915 100644 --- a/packages/onebot/tests/element-manifest.test.ts +++ b/packages/onebot/tests/element-manifest.test.ts @@ -34,8 +34,8 @@ describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', () expect(codecTypesWith('fromSegment')).toEqual(sorted(typesForDirection('P'))); }); - it('输入糖仍由 message-parser 前置处理,未被静默丢弃', () => { - // 输入糖(骰子/分享/…)不进 codec 表,留在 message-parser 当前置 normalize。 + it('OneBot 输入词仍由 message-parser 前置处理或明确拒绝,未被静默丢弃', () => { + // 输入词(骰子/分享/node/anonymous/…)不进 codec 表,留在 parser 前置处理。 // 用源码扫描锁住它们确实存在,防止将来重构时被悄悄删掉。 const abs = fileURLToPath(new URL('../src/message-parser.ts', import.meta.url)); const src = readFileSync(abs, 'utf8') @@ -51,4 +51,13 @@ describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', () const realLeftInParser = [...cases].filter((t) => !INPUT_SUGAR_SEGMENTS.has(t)); expect(realLeftInParser).toEqual([]); }); + + it('poke 的 P/S 字段都使用 subType,不再漂移到 faceId', async () => { + const parsed = await ELEMENT_CODECS.poke!.fromSegment!({ type: 7 }); + expect(parsed).toEqual({ type: 'poke', subType: 7 }); + expect(parsed).not.toHaveProperty('faceId'); + + const segment = await ELEMENT_CODECS.poke!.toSegment!(parsed!, {} as never); + expect(segment).toEqual({ type: 'poke', data: { type: 7 } }); + }); }); diff --git a/packages/onebot/tests/event-converter.test.ts b/packages/onebot/tests/event-converter.test.ts index 3ffc10ec..e59b7ec0 100644 --- a/packages/onebot/tests/event-converter.test.ts +++ b/packages/onebot/tests/event-converter.test.ts @@ -54,6 +54,7 @@ function makeGroupMessage(senderUin: number): GroupMessage { time: 1700000000, selfUin: SELF_ID, groupId: 99999, + groupName: 'Test Group 测试群', senderUin, senderNick: senderUin === SELF_ID ? 'me' : 'peer', senderCard: '', @@ -100,6 +101,7 @@ describe('convertEvent — message kinds', () => { expect(out!.message_type).toBe('group'); expect(out!.sub_type).toBe('normal'); expect(out!.group_id).toBe(GROUP_ID); + expect(out!.group_name).toBe('Test Group 测试群'); }); it('group_message self → post_type "message_sent"', async () => { @@ -107,10 +109,13 @@ describe('convertEvent — message kinds', () => { expect(out!.post_type).toBe('message_sent'); }); - it('temp_message peer → post_type "message", sub_type "group"', async () => { + it('temp_message peer → post_type "message", sub_type "group", sender.group_id set', async () => { const out = await convertEvent(bareCtx(), makeTempMessage(PEER_UIN)); expect(out!.post_type).toBe('message'); expect(out!.sub_type).toBe('group'); + // Source group is surfaced on sender.group_id so a client can reply via + // send_private_msg(user_id, group_id=...). + expect((out!.sender as { group_id?: number }).group_id).toBe(99999); }); it('temp_message self → post_type "message_sent"', async () => { @@ -378,6 +383,19 @@ describe('convertEvent — message elements (13 segment types)', () => { }); }); + it('image: preserves the flash marker on the OneBot segment', async () => { + const seg = await segment({ + type: 'image', + fileId: 'fid', + imageUrl: 'http://x', + flash: true, + }); + expect(seg).toMatchObject({ + type: 'image', + data: { type: 'flash' }, + }); + }); + it('at: targetUin -> qq string', async () => { const seg = await segment({ type: 'at', targetUin: PEER_UIN }); expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } }); diff --git a/packages/onebot/tests/event-pipeline.test.ts b/packages/onebot/tests/event-pipeline.test.ts index 9b765090..c558ed7b 100644 --- a/packages/onebot/tests/event-pipeline.test.ts +++ b/packages/onebot/tests/event-pipeline.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it, vi } from 'vitest'; +import { getRecentLogs } from '@snowluma/common/logger'; import { BridgeEventBus } from '@snowluma/protocol/event-bus'; // Wrap convertEvent in a vi.fn that delegates to the real impl by @@ -9,9 +10,16 @@ vi.mock('../src/event-converter', async () => { return { ...actual, convertEvent: vi.fn(actual.convertEvent) }; }); +vi.mock('../src/modules/message-actions', async () => { + const actual = await vi.importActual('../src/modules/message-actions'); + return { ...actual, backfillReplyTarget: vi.fn(actual.backfillReplyTarget) }; +}); + import { convertEvent, type ConverterContext } from '../src/event-converter'; import { registerEventPipeline } from '../src/event-pipeline'; import type { OneBotInstanceContext } from '../src/instance-context'; +import { backfillReplyTarget } from '../src/modules/message-actions'; +import { TempSessionStore } from '../src/temp-session-store'; import type { FriendMessage, GroupMessage, @@ -45,7 +53,7 @@ function makeFriendMessage(): FriendMessage { function makeGroupMessage(): GroupMessage { return { - kind: 'group_message', + kind: 'group_message', groupName: '', time: 1700000000, selfUin: SELF_ID, groupId: GROUP_ID, @@ -115,6 +123,7 @@ function makeContext(extra: Partial = {}): { summarizeMessage: () => [], close: () => {}, } as never, + tempSessions: new TempSessionStore(), converterCtx, config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never, cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); }, @@ -177,20 +186,103 @@ describe('registerEventPipeline', () => { expect(dispatchCalls[0].notice_type).toBe('group_increase'); }); - it('returns a disposer that fully unsubscribes', async () => { + it('returns a lifecycle handle that fully unsubscribes', async () => { const { ctx, bus, metaCalls, dispatchCalls } = makeContext(); - const dispose = registerEventPipeline(ctx); + const pipeline = registerEventPipeline(ctx); await bus.emit(makeFriendMessage()); expect(dispatchCalls).toHaveLength(1); - dispose(); + pipeline.stop(); + await pipeline.drain(); await bus.emit(makeFriendMessage()); - // No new calls after dispose. + // No new calls after stop. expect(dispatchCalls).toHaveLength(1); expect(metaCalls).toHaveLength(1); }); + it('stops new bridge events and drains a conversion already in flight', async () => { + let markStarted!: () => void; + const started = new Promise((resolve) => { markStarted = resolve; }); + let releaseConversion!: () => void; + const conversionGate = new Promise((resolve) => { releaseConversion = resolve; }); + vi.mocked(convertEvent).mockImplementationOnce(async () => { + markStarted(); + await conversionGate; + return { post_type: 'message', message_type: 'private' }; + }); + const { ctx, bus, metaCalls, dispatchCalls } = makeContext(); + const pipeline = registerEventPipeline(ctx); + + const emitting = bus.emit(makeFriendMessage()); + await started; + pipeline.stop(); + let drained = false; + const draining = pipeline.drain().then(() => { drained = true; }); + await Promise.resolve(); + expect(drained).toBe(false); + + releaseConversion(); + await emitting; + await draining; + expect(drained).toBe(true); + expect(dispatchCalls).toHaveLength(1); + + await bus.emit(makeFriendMessage()); + expect(dispatchCalls).toHaveLength(1); + expect(metaCalls).toHaveLength(1); + }); + + it('drains a rejected listener and records its event kind and error', async () => { + const marker = `event-pipeline-rejection-${Date.now()}-${Math.random()}`; + let markStarted!: () => void; + const started = new Promise((resolve) => { markStarted = resolve; }); + let releaseConversion!: () => void; + const conversionGate = new Promise((resolve) => { releaseConversion = resolve; }); + vi.mocked(convertEvent).mockImplementationOnce(async () => { + markStarted(); + await conversionGate; + throw new Error(marker); + }); + const { ctx, bus, dispatchCalls } = makeContext(); + const pipeline = registerEventPipeline(ctx); + + const emitting = bus.emit(makeFriendMessage()); + await started; + pipeline.stop(); + const draining = pipeline.drain(); + releaseConversion(); + + await emitting; + await expect(draining).resolves.toBeUndefined(); + expect(dispatchCalls).toHaveLength(0); + expect(getRecentLogs(1000).some((entry) => ( + entry.scope === 'Event' + && entry.level === 'error' + && entry.message.includes('kind=friend_message') + && entry.message.includes(marker) + ))).toBe(true); + }); + + it('dispatches the live event and records a reply-backfill failure', async () => { + const marker = `reply-backfill-rejection-${Date.now()}-${Math.random()}`; + vi.mocked(backfillReplyTarget).mockRejectedValueOnce(new Error(marker)); + const { ctx, bus, dispatchCalls } = makeContext(); + const pipeline = registerEventPipeline(ctx); + + await bus.emit(makeFriendMessage()); + pipeline.stop(); + await pipeline.drain(); + + expect(dispatchCalls).toHaveLength(1); + expect(getRecentLogs(1000).some((entry) => ( + entry.scope === 'Event' + && entry.level === 'warn' + && entry.message.includes('kind=friend_message') + && entry.message.includes(marker) + ))).toBe(true); + }); + it('dispatches a separate event for every kind in parallel', async () => { const { ctx, bus, dispatchCalls } = makeContext(); registerEventPipeline(ctx); diff --git a/packages/onebot/tests/forward-nested.test.ts b/packages/onebot/tests/forward-nested.test.ts index 21623b3b..e5d18dc9 100644 --- a/packages/onebot/tests/forward-nested.test.ts +++ b/packages/onebot/tests/forward-nested.test.ts @@ -209,14 +209,144 @@ describe('forward — nested {type:"node"} content', () => { expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]); }); - it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => { + it('rejects an unknown top-level entry before uploading valid siblings', async () => { + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } }, + } as any); + const ctx = makeCtx(bridge); + const messages = [ + { + type: 'node', + data: { + user_id: 111, + nickname: 'valid', + content: [{ type: 'text', data: { text: 'must not upload' } }], + }, + }, + { type: 'surprise', data: { content: 'silently dropped before' } }, + ]; + + await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({ + code: 'UNKNOWN_TYPE', + elementType: 'surprise', + }); + expect(uploadForwardNodes).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('rejects object-valued node metadata before uploading', async () => { + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } }, + } as any); + const ctx = makeCtx(bridge); + + await expect(sendGroupForwardMessage(ctx, 12345, [{ + type: 'node', + data: { + user_id: { accidental: 111 }, + nickname: 'invalid', + content: [{ type: 'text', data: { text: 'must not upload' } }], + }, + }] as any)).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'node', + field: 'user_id', + }); + expect(uploadForwardNodes).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('rejects a cached message node with no valid sender instead of dropping it', async () => { + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } }, + } as any); + const ctx = makeCtx(bridge); + (ctx as any).messageStore = { + findEvent: () => ({ + user_id: 0, + message_type: 'group', + message: [{ type: 'text', data: { text: 'cached' } }], + sender: { nickname: 'missing-id' }, + }), + }; + + await expect(sendGroupForwardMessage(ctx, 12345, [ + { type: 'node', data: { id: 7 } }, + { type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'sibling' } }] } }, + ] as any)).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'node', + field: 'user_id', + }); + expect(uploadForwardNodes).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('resolves a cached node by a signed negative OneBot message_id', async () => { + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(async () => ({ + messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 1, + })); + const findEvent = vi.fn((id: number) => id === -123 ? ({ + user_id: 111, + message_id: -123, + message_seq: 42, + message_type: 'group', + group_id: 12345, + time: 1700000000, + message: [{ type: 'text', data: { text: 'cached negative id' } }], + sender: { nickname: 'alice' }, + }) : null); + const bridge = fakeBridge({ + apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } }, + } as any); + const ctx = makeCtx(bridge); + (ctx as any).messageStore = { findEvent }; + + await sendGroupForwardMessage(ctx, 12345, [ + { type: 'node', data: { id: -123 } }, + ] as any); + + expect(findEvent).toHaveBeenCalledWith(-123); + const [nodes] = uploadForwardNodes.mock.calls[0]!; + expect((nodes as any[])[0]).toMatchObject({ + userUin: 111, + msgId: -123, + elements: [{ type: 'text', text: 'cached negative id' }], + }); + }); + + it('reports a missing cached message_id as caller-invalid before upload', async () => { + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } }, + } as any); + const ctx = makeCtx(bridge); + + await expect(sendGroupForwardMessage(ctx, 12345, [ + { type: 'node', data: { id: -404 } }, + ] as any)).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'node', + field: 'message_id', + }); + expect(uploadForwardNodes).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('rejects mixed node/non-node content instead of partially dropping the node', async () => { // Recursion only kicks in when *all* content entries are nodes — // mixed content is ambiguous (do the non-node parts belong to the // outer node or are they parallel siblings?), so we keep the legacy - // behaviour and let parseMessage handle it. Non-node parts come - // through, node parts get parsed via `case 'node':` and then - // dropped by element-builder. A user who wants nested forward - // should pass a pure node list. + // behaviour is ambiguous, so reject it before upload. A user who wants a + // nested forward must pass a pure node list. const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES'); const sendGroupMessage = vi.fn(async () => ({ messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0, @@ -235,13 +365,12 @@ describe('forward — nested {type:"node"} content', () => { }, }]; - await sendGroupForwardMessage(ctx, 12345, messages as any); - expect(uploadForwardNodes).toHaveBeenCalledOnce(); - // Only the text element survives — the legacy "node MessageElement" - // that parseMessage produces is opaque to the element-builder. - const [nodes] = uploadForwardNodes.mock.calls[0]!; - const elements = (nodes as any[])[0]!.elements; - expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true); + await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'node', + }); + expect(uploadForwardNodes).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); }); it('[#203] node with user_id "0" or missing falls back to the bot self_id', async () => { diff --git a/packages/onebot/tests/helpers/compiled-action-handler.ts b/packages/onebot/tests/helpers/compiled-action-handler.ts new file mode 100644 index 00000000..352df836 --- /dev/null +++ b/packages/onebot/tests/helpers/compiled-action-handler.ts @@ -0,0 +1,33 @@ +import { defineAction, type RegisteredActionSpec } from '../../src/action-kit'; +import { ApiHandler, type ApiActionContext } from '../../src/api-handler'; +import { compileActionRegistry, RAW_ACTION_RESERVATIONS } from '../../src/actions'; +import type { ApiResponse, JsonObject } from '../../src/types'; + +type TestActionRun = ( + params: JsonObject, + context: ApiActionContext, +) => Promise | ApiResponse; + +/** A test-only normal ActionSpec that still travels through the complete + * compiled-registry constructor path. */ +export function testAction(name: string, run: TestActionRun): RegisteredActionSpec { + return defineAction({ + name, + params: {}, + run: (_params, context, raw) => run(raw, context), + }); +} + +/** Construct an ApiHandler from an isolated but complete namespace. The raw + * quick-operation reservation is mandatory, matching the production shape. */ +export function createCompiledTestHandler( + context: ApiActionContext, + specs: readonly RegisteredActionSpec[] = [], + uin?: number, +): ApiHandler { + const registry = compileActionRegistry( + [{ category: 'test', actions: specs }], + RAW_ACTION_RESERVATIONS, + ); + return new ApiHandler(context, uin, registry); +} diff --git a/packages/onebot/tests/http-post-lifecycle.test.ts b/packages/onebot/tests/http-post-lifecycle.test.ts new file mode 100644 index 00000000..7afb4aa1 --- /dev/null +++ b/packages/onebot/tests/http-post-lifecycle.test.ts @@ -0,0 +1,79 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { createHmac } from 'crypto'; +import { buildDispatchPayload } from '../src/event-filter'; +import { HttpPostAdapter } from '../src/network/http-post-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { HttpClientNetwork, JsonObject } from '../src/types'; + +const CTX: NetworkAdapterContext = { + uin: '10001', + api: {} as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), +}; + +afterEach(() => { vi.unstubAllGlobals(); }); + +describe('HttpPostAdapter event ownership', () => { + it('keeps onEvent pending until the webhook request completes', async () => { + let finishFetch!: () => void; + const fetchGate = new Promise((resolve) => { finishFetch = resolve; }); + vi.stubGlobal('fetch', vi.fn(async () => { + await fetchGate; + return new Response(null, { status: 204 }); + })); + const config: HttpClientNetwork = { + name: 'post', + url: 'http://127.0.0.1:5700/events', + messageFormat: 'array', + reportSelfMessage: false, + }; + const adapter = new HttpPostAdapter('post', config, CTX); + adapter.open(); + const event: JsonObject = { post_type: 'notice', notice_type: 'test' }; + + let completed = false; + const posting = adapter.onEvent(event, buildDispatchPayload(event)).then(() => { completed = true; }); + await Promise.resolve(); + expect(completed).toBe(false); + + finishFetch(); + await posting; + expect(completed).toBe(true); + }); + + it('uses one coherent config epoch when reload races HMAC computation', async () => { + const fetchMock = vi.fn(async () => new Response(null, { status: 204 })); + vi.stubGlobal('fetch', fetchMock); + const oldConfig: HttpClientNetwork = { + name: 'post', + url: 'http://127.0.0.1:5700/old', + accessToken: 'old-token', + timeoutMs: 1111, + messageFormat: 'array', + reportSelfMessage: false, + }; + const newConfig: HttpClientNetwork = { + ...oldConfig, + url: 'http://127.0.0.1:5700/new', + accessToken: 'new-token', + timeoutMs: 2222, + }; + const adapter = new HttpPostAdapter('post', oldConfig, CTX); + adapter.open(); + const event: JsonObject = { post_type: 'notice', notice_type: 'epoch' }; + const payload = buildDispatchPayload(event); + + const posting = adapter.onEvent(event, payload); + await adapter.reload(newConfig); + await posting; + + expect(fetchMock).toHaveBeenCalledOnce(); + const [url, init] = fetchMock.mock.calls[0]!; + expect(url).toBe(oldConfig.url); + const body = String(init?.body ?? ''); + expect((init?.headers as Record)['X-Signature']).toBe( + `sha1=${createHmac('sha1', oldConfig.accessToken!).update(body).digest('hex')}`, + ); + }); +}); diff --git a/packages/onebot/tests/http-server-action-lifecycle.test.ts b/packages/onebot/tests/http-server-action-lifecycle.test.ts new file mode 100644 index 00000000..70adefc9 --- /dev/null +++ b/packages/onebot/tests/http-server-action-lifecycle.test.ts @@ -0,0 +1,71 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import http from 'http'; +import type { AddressInfo } from 'net'; +import { HttpServerAdapter } from '../src/network/http-server-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { HttpServerNetwork } from '../src/types'; + +describe('HttpServerAdapter inbound Action ownership', () => { + let adapter: HttpServerAdapter | null = null; + + afterEach(async () => { + await adapter?.close(); + adapter = null; + }); + + it('waits for a detached Action after the HTTP client disconnects', async () => { + let releaseAction!: () => void; + const actionGate = new Promise((resolve) => { releaseAction = resolve; }); + let actionStarted!: () => void; + const started = new Promise((resolve) => { actionStarted = resolve; }); + const apiHandle = vi.fn(async () => { + actionStarted(); + await actionGate; + return { status: 'ok' as const, retcode: 0, data: { done: true } }; + }); + const ctx: NetworkAdapterContext = { + uin: '10001', + api: { handle: apiHandle, isStreamAction: () => false } as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), + }; + const config: HttpServerNetwork = { + name: 'http-action-drain', + host: '127.0.0.1', + port: 0, + path: '/', + messageFormat: 'array', + reportSelfMessage: false, + }; + adapter = new HttpServerAdapter(config.name, config, ctx); + await adapter.open(); + const server = (adapter as unknown as { server: http.Server }).server; + const port = (server.address() as AddressInfo).port; + const serverSocketClosed = new Promise((resolve) => { + server.once('connection', (socket) => { + socket.once('close', () => resolve()); + }); + }); + + const request = http.request({ host: '127.0.0.1', port, path: '/slow', method: 'GET' }); + request.on('error', () => { /* expected after destroy */ }); + request.end(); + await started; + request.destroy(); + // Prove the transport socket is already gone before close(). Otherwise + // server.close() itself could be the thing keeping this test pending and + // hide a missing detached-Action drain. + await serverSocketClosed; + + let closed = false; + const closing = adapter.close().then(() => { closed = true; }); + await new Promise((resolve) => setImmediate(resolve)); + expect(closed).toBe(false); + + releaseAction(); + await closing; + expect(closed).toBe(true); + expect(apiHandle).toHaveBeenCalledOnce(); + adapter = null; + }); +}); diff --git a/packages/onebot/tests/http-server-close-retry.test.ts b/packages/onebot/tests/http-server-close-retry.test.ts new file mode 100644 index 00000000..2d2984cb --- /dev/null +++ b/packages/onebot/tests/http-server-close-retry.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { IncomingMessage, ServerResponse } from 'http'; +import { HttpServerAdapter } from '../src/network/http-server-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { HttpServerNetwork } from '../src/types'; + +let apiAccepting = true; +const CTX: NetworkAdapterContext = { + uin: '10001', + api: { + get isAcceptingActions() { return apiAccepting; }, + } as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), +}; + +describe('HttpServerAdapter close ownership', () => { + it('retains the server reference after callback failure and retries it', async () => { + apiAccepting = true; + const config: HttpServerNetwork = { + name: 'http', + host: '127.0.0.1', + port: 3000, + messageFormat: 'array', + reportSelfMessage: false, + }; + const adapter = new HttpServerAdapter('http', config, CTX); + let callback: ((error?: Error) => void) | null = null; + const server = { + close(next: (error?: Error) => void) { callback = next; }, + }; + Object.assign(adapter as unknown as Record, { + server, + isEnabled: true, + listening: true, + acceptingActions: true, + }); + + const firstClose = adapter.close(); + callback!(new Error('release failed')); + await expect(firstClose).rejects.toThrow('release failed'); + expect((adapter as unknown as { server: unknown }).server).toBe(server); + expect(adapter.describeStatus().status).toBe('ok'); + + expect((adapter as unknown as { acceptingActions: boolean }).acceptingActions).toBe(true); + apiAccepting = false; + const response = { + headersSent: false, + writableEnded: false, + destroyed: false, + statusCode: 0, + setHeader: vi.fn(), + end: vi.fn(), + } as unknown as ServerResponse; + (adapter as unknown as { + trackInboundAction(req: IncomingMessage, res: ServerResponse): void; + }).trackInboundAction({} as IncomingMessage, response); + expect(response.statusCode).toBe(503); + expect(response.end).toHaveBeenCalledWith(expect.stringContaining('server closing')); + + const secondClose = adapter.close(); + callback!(); + await secondClose; + expect((adapter as unknown as { server: unknown }).server).toBeNull(); + expect(adapter.describeStatus().status).toBe('disabled'); + }); +}); diff --git a/packages/onebot/tests/http-server-content-type.test.ts b/packages/onebot/tests/http-server-content-type.test.ts index f3d350ad..72dfc5cb 100644 --- a/packages/onebot/tests/http-server-content-type.test.ts +++ b/packages/onebot/tests/http-server-content-type.test.ts @@ -56,13 +56,11 @@ describe('HttpServerAdapter content-type parsing', () => { const ctx = fakeCtx(handleFn); const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false }; adapter = new HttpServerAdapter('test-http', config, ctx); - adapter.open(); - // Wait for server to be listening - await new Promise((resolve) => setTimeout(resolve, 100)); + await adapter.open(); }); - afterAll(() => { - adapter.close(); + afterAll(async () => { + await adapter.close(); }); it('should parse application/json body', async () => { diff --git a/packages/onebot/tests/http-server-hot-reload.test.ts b/packages/onebot/tests/http-server-hot-reload.test.ts index beb6acfe..26bfae23 100644 --- a/packages/onebot/tests/http-server-hot-reload.test.ts +++ b/packages/onebot/tests/http-server-hot-reload.test.ts @@ -53,8 +53,8 @@ async function waitForListen(adapter: HttpServerAdapter): Promise { describe('HttpServerAdapter — accessToken hot reload', () => { let adapter: HttpServerAdapter | null = null; - afterEach(() => { - adapter?.close(); + afterEach(async () => { + await adapter?.close(); adapter = null; }); @@ -68,7 +68,7 @@ describe('HttpServerAdapter — accessToken hot reload', () => { messageFormat: 'array', reportSelfMessage: false, }; adapter = new HttpServerAdapter('hot', config, ctx); - adapter.open(); + await adapter.open(); const portBefore = await waitForListen(adapter); // Sanity: old token authorizes, anything else 401s. @@ -94,7 +94,7 @@ describe('HttpServerAdapter — accessToken hot reload', () => { messageFormat: 'array', reportSelfMessage: false, }; adapter = new HttpServerAdapter('hot-clear', config, ctx); - adapter.open(); + await adapter.open(); const port = await waitForListen(adapter); expect((await get(port, '/')).status).toBe(401); // no token header → 401 @@ -111,7 +111,7 @@ describe('HttpServerAdapter — accessToken hot reload', () => { messageFormat: 'array', reportSelfMessage: false, }; adapter = new HttpServerAdapter('hot-add', config, ctx); - adapter.open(); + await adapter.open(); const port = await waitForListen(adapter); expect((await get(port, '/')).status).toBe(200); // no auth configured @@ -129,7 +129,7 @@ describe('HttpServerAdapter — accessToken hot reload', () => { messageFormat: 'array', reportSelfMessage: false, }; adapter = new HttpServerAdapter('hot-type', config, ctx); - adapter.open(); + await adapter.open(); await waitForListen(adapter); const reloadType = await adapter.reload({ ...config, accessToken: 'b' }); @@ -138,4 +138,62 @@ describe('HttpServerAdapter — accessToken hot reload', () => { // touched the listener. expect(reloadType).toBe(NetworkReloadType.Normal); }); + + it('rejects open only after an occupied-port bind actually fails', async () => { + const blocker = http.createServer(); + await new Promise((resolve, reject) => { + blocker.once('error', reject); + blocker.listen(0, '127.0.0.1', resolve); + }); + const address = blocker.address() as AddressInfo; + const config: HttpServerNetwork = { + name: 'occupied', + host: '127.0.0.1', + port: address.port, + enabled: true, + messageFormat: 'array', + reportSelfMessage: false, + }; + adapter = new HttpServerAdapter('occupied', config, fakeCtx()); + + try { + await expect(adapter.open()).rejects.toMatchObject({ code: 'EADDRINUSE' }); + expect(adapter.describeManagedStatus()).toMatchObject({ + status: 'degraded', + lastError: expect.stringContaining('EADDRINUSE'), + }); + } finally { + await new Promise((resolve, reject) => { + blocker.close((error) => error ? reject(error) : resolve()); + }); + } + }); + + it('close resolves only after the port can be rebound', async () => { + const config: HttpServerNetwork = { + name: 'release', + host: '127.0.0.1', + port: 0, + enabled: true, + messageFormat: 'array', + reportSelfMessage: false, + }; + adapter = new HttpServerAdapter('release', config, fakeCtx()); + await adapter.open(); + const port = ((adapter as any).server as http.Server).address() as AddressInfo; + await adapter.close(); + adapter = null; + + const rebound = http.createServer(); + try { + await new Promise((resolve, reject) => { + rebound.once('error', reject); + rebound.listen(port.port, '127.0.0.1', resolve); + }); + } finally { + await new Promise((resolve, reject) => { + rebound.close((error) => error ? reject(error) : resolve()); + }); + } + }); }); diff --git a/packages/onebot/tests/instance-config-lifecycle.test.ts b/packages/onebot/tests/instance-config-lifecycle.test.ts new file mode 100644 index 00000000..377d6d2d --- /dev/null +++ b/packages/onebot/tests/instance-config-lifecycle.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from 'vitest'; +import { OneBotInstance } from '../src/instance'; +import type { NetworkReconcileResult } from '../src/network'; +import type { OneBotConfig } from '../src/types'; + +function config(trigger: string): OneBotConfig { + return { + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + statusCommand: { enabled: true, swallow: false, cooldownSeconds: 5, trigger }, + notifications: { channelIds: [] }, + }; +} + +describe('OneBotInstance config lifecycle FIFO', () => { + it('keeps ctx.config aligned with each ordered network reconcile', async () => { + const instance = Object.create(OneBotInstance.prototype) as OneBotInstance; + let finishFirst!: () => void; + const firstGate = new Promise((resolve) => { finishFirst = resolve; }); + const observations: Array<{ argument: OneBotConfig; current: OneBotConfig }> = []; + const ctx = { config: config('#initial') }; + let calls = 0; + const ok: NetworkReconcileResult = { applied: true, errors: [], statuses: [] }; + const networkManager = { + compileDesiredPlan: vi.fn(() => []), + reconcile: vi.fn(async (argument: OneBotConfig) => { + observations.push({ argument, current: ctx.config }); + calls += 1; + if (calls === 1) await firstGate; + return ok; + }), + }; + Object.assign(instance as unknown as Record, { + uin: '10001', + ctx, + networkManager, + lifecycleTail: Promise.resolve(), + disposeRequested: false, + }); + const a = config('#a'); + const b = config('#b'); + + const applyingA = instance.reloadConfig(a); + const applyingB = instance.reloadConfig(b); + await Promise.resolve(); + await Promise.resolve(); + expect(observations).toHaveLength(1); + expect(observations[0].argument.statusCommand.trigger).toBe('#a'); + expect(observations[0].current.statusCommand.trigger).toBe('#a'); + + finishFirst(); + await Promise.all([applyingA, applyingB]); + expect(observations.map((item) => item.argument.statusCommand.trigger)).toEqual(['#a', '#b']); + expect(observations.map((item) => item.current.statusCommand.trigger)).toEqual(['#a', '#b']); + expect(ctx.config.statusCommand.trigger).toBe('#b'); + }); +}); diff --git a/packages/onebot/tests/instance-network-dispose.test.ts b/packages/onebot/tests/instance-network-dispose.test.ts new file mode 100644 index 00000000..b8507ea2 --- /dev/null +++ b/packages/onebot/tests/instance-network-dispose.test.ts @@ -0,0 +1,144 @@ +import { describe, expect, it, vi } from 'vitest'; +import { OneBotInstance } from '../src/instance'; +import type { NetworkShutdownResult } from '../src/network'; + +function fabricatedInstance(results: NetworkShutdownResult[]) { + const instance = Object.create(OneBotInstance.prototype) as OneBotInstance; + const closeMessage = vi.fn(); + const closeMedia = vi.fn(); + const closeReaction = vi.fn(); + const shutdown = vi.fn(async () => results.shift() ?? { closed: true, errors: [] }); + + Object.assign(instance as unknown as Record, { + uin: '10001', + online: true, + heartbeatTimer: null, + eventPipeline: null, + eventPipelineDrain: Promise.resolve(), + disposePromise: null, + disposeRequested: false, + acceptingActions: true, + inFlightActions: new Set>(), + lifecycleTail: Promise.resolve(), + storeCloseState: { message: false, media: false, reaction: false }, + apiHandler: { quiesce: vi.fn() }, + networkManager: { shutdown }, + messageStore: { close: closeMessage }, + mediaStore: { close: closeMedia }, + reactionStore: { close: closeReaction }, + }); + + return { instance, shutdown, closeMessage, closeMedia, closeReaction }; +} + +describe('OneBotInstance.dispose network/store ordering', () => { + it('keeps stores open after an incomplete network shutdown and retries later', async () => { + const failure = { + name: 'http', + kind: 'httpServer' as const, + phase: 'shutdown' as const, + message: 'EADDRINUSE release failed', + at: Date.now(), + }; + const f = fabricatedInstance([ + { closed: false, errors: [failure] }, + { closed: true, errors: [] }, + ]); + + await expect(f.instance.dispose()).rejects.toThrow(/stores remain open/); + expect(f.closeMessage).not.toHaveBeenCalled(); + expect(f.closeMedia).not.toHaveBeenCalled(); + expect(f.closeReaction).not.toHaveBeenCalled(); + + await expect(f.instance.dispose()).resolves.toEqual({ closed: true, errors: [] }); + expect(f.shutdown).toHaveBeenCalledTimes(2); + expect(f.closeMessage).toHaveBeenCalledTimes(1); + expect(f.closeMedia).toHaveBeenCalledTimes(1); + expect(f.closeReaction).toHaveBeenCalledTimes(1); + }); + + it('retries only stores that did not close successfully', async () => { + const f = fabricatedInstance([ + { closed: true, errors: [] }, + { closed: true, errors: [] }, + ]); + f.closeReaction.mockImplementationOnce(() => { throw new Error('reaction close failed'); }); + + await expect(f.instance.dispose()).rejects.toThrow(/failed to close OneBot stores/); + expect(f.closeMessage).toHaveBeenCalledTimes(1); + expect(f.closeMedia).toHaveBeenCalledTimes(1); + expect(f.closeReaction).toHaveBeenCalledTimes(1); + + await expect(f.instance.dispose()).resolves.toEqual({ closed: true, errors: [] }); + expect(f.closeMessage).toHaveBeenCalledTimes(1); + expect(f.closeMedia).toHaveBeenCalledTimes(1); + expect(f.closeReaction).toHaveBeenCalledTimes(2); + }); + + it('does not close stores while network shutdown is still draining work', async () => { + const f = fabricatedInstance([]); + let finishShutdown!: (result: NetworkShutdownResult) => void; + const draining = new Promise((resolve) => { finishShutdown = resolve; }); + f.shutdown.mockImplementationOnce(() => draining); + + const disposing = f.instance.dispose(); + await Promise.resolve(); + await Promise.resolve(); + expect(f.closeMessage).not.toHaveBeenCalled(); + expect(f.closeMedia).not.toHaveBeenCalled(); + expect(f.closeReaction).not.toHaveBeenCalled(); + + finishShutdown({ closed: true, errors: [] }); + await disposing; + expect(f.closeMessage).toHaveBeenCalledTimes(1); + expect(f.closeMedia).toHaveBeenCalledTimes(1); + expect(f.closeReaction).toHaveBeenCalledTimes(1); + }); + + it('drains an in-flight instance action before network and stores close', async () => { + const f = fabricatedInstance([{ closed: true, errors: [] }]); + let finishAction!: () => void; + const actionGate = new Promise((resolve) => { finishAction = resolve; }); + const action = (f.instance as unknown as { + trackAction(label: string, start: () => Promise): Promise; + }).trackAction('status reply', () => actionGate); + + const disposing = f.instance.dispose(); + await Promise.resolve(); + await Promise.resolve(); + expect(f.shutdown).not.toHaveBeenCalled(); + expect(f.closeMessage).not.toHaveBeenCalled(); + + finishAction(); + await action; + await disposing; + expect(f.shutdown).toHaveBeenCalledTimes(1); + expect(f.closeMessage).toHaveBeenCalledTimes(1); + }); + + it('stops and drains the event pipeline before network and stores close', async () => { + const f = fabricatedInstance([{ closed: true, errors: [] }]); + let finishEvent!: () => void; + const eventGate = new Promise((resolve) => { finishEvent = resolve; }); + const stop = vi.fn(); + const drain = vi.fn(() => eventGate); + Object.assign(f.instance as unknown as Record, { + eventPipeline: { stop, drain }, + }); + + const disposing = f.instance.dispose(); + expect(stop).toHaveBeenCalledOnce(); + expect(drain).toHaveBeenCalledOnce(); + await Promise.resolve(); + await Promise.resolve(); + expect(f.shutdown).not.toHaveBeenCalled(); + expect(f.closeMessage).not.toHaveBeenCalled(); + + finishEvent(); + await disposing; + expect(f.shutdown).toHaveBeenCalledTimes(1); + expect(f.closeMessage).toHaveBeenCalledTimes(1); + expect(f.closeMedia).toHaveBeenCalledTimes(1); + expect(f.closeReaction).toHaveBeenCalledTimes(1); + }); +}); diff --git a/packages/onebot/tests/manager-config-apply.test.ts b/packages/onebot/tests/manager-config-apply.test.ts new file mode 100644 index 00000000..fc48eeff --- /dev/null +++ b/packages/onebot/tests/manager-config-apply.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it, vi } from 'vitest'; +import { OneBotManager } from '../src/manager'; +import type { OneBotConfig } from '../src/types'; + +function config(trigger: string): OneBotConfig { + return { + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + statusCommand: { enabled: true, swallow: false, cooldownSeconds: 5, trigger }, + notifications: { channelIds: [] }, + }; +} + +describe('OneBotManager config apply value ownership', () => { + it('passes each concurrent caller exact config value to the instance', async () => { + const manager = new OneBotManager(); + const seen: OneBotConfig[] = []; + const instance = { + reloadConfig: vi.fn(async (value: OneBotConfig) => { + seen.push(value); + return { applied: true, errors: [], statuses: [] }; + }), + }; + (manager as unknown as { instances: Map }).instances.set('10001', instance); + const a = config('#a'); + const b = config('#b'); + + await Promise.all([ + manager.reloadConfig('10001', a), + manager.reloadConfig('10001', b), + ]); + + expect(seen).toEqual([a, b]); + expect(instance.reloadConfig).toHaveBeenNthCalledWith(1, a); + expect(instance.reloadConfig).toHaveBeenNthCalledWith(2, b); + }); +}); diff --git a/packages/onebot/tests/manager-lifecycle.test.ts b/packages/onebot/tests/manager-lifecycle.test.ts new file mode 100644 index 00000000..761a7a42 --- /dev/null +++ b/packages/onebot/tests/manager-lifecycle.test.ts @@ -0,0 +1,165 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { AdapterStatus } from '../src/network'; +import type { OneBotInstance } from '../src/instance'; +import { OneBotManager } from '../src/manager'; + +function fakeInstance( + uin: string, + dispose: () => Promise, + statuses: AdapterStatus[] = [], + quiesce: () => void = () => {}, +): OneBotInstance { + return { + uin, + nickname: `retiring-${uin}`, + quiesce, + dispose, + getConnectionStatuses: () => statuses, + } as unknown as OneBotInstance; +} + +describe('OneBotManager lifecycle failure accounting', () => { + it('quiesces active instances before waiting for pending lifecycle work', async () => { + const manager = new OneBotManager(); + let finishLifecycle!: () => void; + const lifecycleGate = new Promise((resolve) => { finishLifecycle = resolve; }); + const quiesce = vi.fn(); + const dispose = vi.fn(async () => ({ closed: true, errors: [] })); + const instance = fakeInstance('10001', dispose, [], quiesce); + const internals = manager as unknown as { + instances: Map; + trackLifecycle(label: string, operation: Promise): void; + }; + internals.instances.set('10001', instance); + internals.trackLifecycle('deferred startup', lifecycleGate); + + const disposing = manager.dispose(); + expect(quiesce).toHaveBeenCalledOnce(); + expect(dispose).not.toHaveBeenCalled(); + + finishLifecycle(); + await disposing; + expect(dispose).toHaveBeenCalledOnce(); + }); + + it('retains a tracked rejection until final dispose reports it', async () => { + const manager = new OneBotManager(); + (manager as unknown as { + trackLifecycle(label: string, operation: Promise): void; + }).trackLifecycle('probe shutdown', Promise.reject(new Error('release failed'))); + + await expect(manager.dispose()).rejects.toThrow(/failed to dispose OneBot manager cleanly/); + }); + + it('keeps a failed retire visible and blocks a conflicting same-UIN generation', async () => { + const manager = new OneBotManager(); + const degraded: AdapterStatus = { + name: 'old-http', + kind: 'httpServer', + status: 'degraded', + detail: 'release failed', + lastError: 'release failed', + lastErrorAt: Date.now(), + }; + const old = fakeInstance('10001', async () => { throw new Error('release failed'); }, [degraded]); + (manager as unknown as { retiringInstances: Set }).retiringInstances.add(old); + const bridge = {} as never; + + (manager as unknown as { onSessionStarted(uin: string, bridge: never): void }) + .onSessionStarted('10001', bridge); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + + expect(manager.getInstance('10001')).toBeNull(); + expect(manager.getConnectionStatuses()).toEqual([{ + uin: '10001', + nickname: 'retiring-10001', + adapters: [degraded], + }]); + expect((manager as unknown as { pendingStarts: Map }).pendingStarts.has('10001')).toBe(false); + }); + + it('allows a later same-UIN start observation to retry a failed handoff', async () => { + const manager = new OneBotManager(); + let attempts = 0; + let finishRetry!: () => void; + const retryGate = new Promise((resolve) => { finishRetry = resolve; }); + const old = fakeInstance('10001', async () => { + attempts += 1; + if (attempts === 1) throw new Error('first release failed'); + await retryGate; + return { closed: true, errors: [] }; + }); + const internals = manager as unknown as { + retiringInstances: Set; + onSessionStarted(uin: string, bridge: never): void; + onSessionClosed(uin: string): void; + pendingStarts: Map; + }; + internals.retiringInstances.add(old); + internals.onSessionStarted('10001', {} as never); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + expect(internals.pendingStarts.has('10001')).toBe(false); + + internals.onSessionStarted('10001', {} as never); + expect(internals.pendingStarts.has('10001')).toBe(true); + // The replacement session disappears while the retry is pending; cancel + // creation so the test never needs a concrete Bridge. + internals.onSessionClosed('10001'); + finishRetry(); + await Promise.resolve(); + await Promise.resolve(); + expect(attempts).toBe(2); + expect(manager.getInstance('10001')).toBeNull(); + await expect(manager.dispose()).resolves.toBeUndefined(); + }); + + it('binds a multi-generation handoff failure only to the generation that failed', async () => { + const manager = new OneBotManager(); + const a = fakeInstance('10001', async () => ({ closed: true, errors: [] })); + let bAttempts = 0; + const b = fakeInstance('10001', async () => { + bAttempts += 1; + if (bAttempts === 1) throw new Error('B release failed'); + return { closed: true, errors: [] }; + }); + const internals = manager as unknown as { + retiringInstances: Set; + onSessionStarted(uin: string, bridge: never): void; + }; + internals.retiringInstances.add(a); + internals.retiringInstances.add(b); + internals.onSessionStarted('10001', {} as never); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + await Promise.resolve(); + + expect(internals.retiringInstances.has(a)).toBe(false); + expect(internals.retiringInstances.has(b)).toBe(true); + await expect(manager.dispose()).resolves.toBeUndefined(); + expect(bAttempts).toBe(2); + }); + + it('does not let a successful same-UIN generation clear another generation failure', async () => { + const manager = new OneBotManager(); + const a = fakeInstance('10001', async () => { throw new Error('A still owns port'); }); + const b = fakeInstance('10001', async () => undefined); + const internals = manager as unknown as { + retiringInstances: Set; + trackLifecycle(label: string, operation: Promise, instances?: OneBotInstance[]): void; + }; + internals.retiringInstances.add(a); + internals.retiringInstances.add(b); + internals.trackLifecycle( + 'network shutdown UIN=10001', + Promise.reject(new Error('A previous failure')), + [a], + ); + + await expect(manager.dispose()).rejects.toThrow(/failed to dispose OneBot manager cleanly/); + }); +}); diff --git a/packages/onebot/tests/media-store.test.ts b/packages/onebot/tests/media-store.test.ts index bb471fc5..8cd6180f 100644 --- a/packages/onebot/tests/media-store.test.ts +++ b/packages/onebot/tests/media-store.test.ts @@ -34,7 +34,7 @@ function recordElement(overrides: Partial = {}): MessageElement function makeGroupMessage(elements: MessageElement[]): GroupMessage { return { - kind: 'group_message', + kind: 'group_message', groupName: '', time: 1700000000, selfUin: SELF_ID, groupId: GROUP_ID, diff --git a/packages/onebot/tests/message-action-validation.test.ts b/packages/onebot/tests/message-action-validation.test.ts new file mode 100644 index 00000000..773a058a --- /dev/null +++ b/packages/onebot/tests/message-action-validation.test.ts @@ -0,0 +1,73 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; +import type { OneBotInstanceContext } from '../src/instance-context'; +import { sendGroupMessage } from '../src/modules/message-actions'; + +function instanceContext(sendGroup: ReturnType): OneBotInstanceContext { + const bridge = { + apis: { message: { sendGroup } }, + resolveUserUid: vi.fn(async () => 'u_peer'), + } as unknown as BridgeInterface; + + return { + uin: '10001', + selfId: 10001, + bridge, + messageStore: { + resolveReplySequence: () => 0, + findEvent: () => null, + findMeta: () => null, + } as never, + cacheMessageMeta: vi.fn(), + mediaStore: {} as never, + musicSignUrl: '', + } as unknown as OneBotInstanceContext; +} + +describe('outbound message validation at the Action boundary', () => { + it('returns BAD_REQUEST and performs no send when a later segment is unknown', async () => { + const bridgeSend = vi.fn(); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [ + { type: 'text', data: { text: 'must not be sent' } }, + { type: 'unknown_late_segment', data: {} }, + ], + }); + + expect(response).toMatchObject({ + status: 'failed', + retcode: 1400, + wording: expect.stringContaining('unknown message segment type'), + }); + expect(bridgeSend).not.toHaveBeenCalled(); + }); + + it('returns BAD_REQUEST and performs no send for malformed JSON cards', async () => { + const bridgeSend = vi.fn(); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [{ type: 'json', data: { data: 'not-json' } }], + }); + + expect(response).toMatchObject({ + status: 'failed', + retcode: 1400, + wording: expect.stringContaining('must contain a JSON object'), + }); + expect(bridgeSend).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/message-parser.test.ts b/packages/onebot/tests/message-parser.test.ts index 42d75b34..4081754d 100644 --- a/packages/onebot/tests/message-parser.test.ts +++ b/packages/onebot/tests/message-parser.test.ts @@ -3,7 +3,7 @@ import os from 'os'; import path from 'path'; import { describe, it, expect, vi } from 'vitest'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; -import { parseMessage } from '../src/message-parser'; +import { MessageElementValidationError, parseMessage } from '../src/message-parser'; import { buildSendElems } from '@snowluma/protocol/element-builder'; import type { MentionExtraSend } from '@snowluma/proto-defs/action'; import type { MarketFacePbReserve } from '@snowluma/proto-defs/element'; @@ -17,9 +17,12 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'text', text: 'hello world' }]); }); - it('returns empty for empty string', async () => { - const result = await parseMessage('', false); - expect(result).toEqual([]); + it('rejects an empty string', async () => { + await expect(parseMessage('', false)).rejects.toMatchObject({ + name: 'MessageElementValidationError', + code: 'MISSING_FIELD', + field: 'message', + }); }); it('autoEscape treats CQ codes as text', async () => { @@ -62,6 +65,21 @@ describe('parseMessage', () => { const result = await parseMessage('a&b[c]d', false); expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]); }); + + it('recognizes underscored CQ types and rejects receive-only flash_file', async () => { + await expect(parseMessage('[CQ:flash_file,file_set_id=x]', false)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'flash_file', + message: expect.stringContaining('send_flash_msg'), + }); + }); + + it('does not send an unknown underscored CQ code as literal text', async () => { + await expect(parseMessage('[CQ:unknown_segment]', false)).rejects.toMatchObject({ + code: 'UNKNOWN_TYPE', + elementType: 'unknown_segment', + }); + }); }); describe('JSON segment array', () => { @@ -73,6 +91,25 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'text', text: 'hello' }]); }); + it('rejects object-valued fields instead of stringifying caller input', async () => { + await expect(parseMessage( + [{ type: 'text', data: { text: { bad: true } } }] as any, + false, + )).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'text', + field: 'text', + }); + await expect(parseMessage( + [{ type: 'json', data: { data: { app: 'unexpected-object' } } }] as any, + false, + )).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'json', + field: 'data', + }); + }); + it('parses face segment', async () => { const result = await parseMessage( [{ type: 'face', data: { id: 123 } }] as any, @@ -83,6 +120,21 @@ describe('parseMessage', () => { expect(result[0].faceId).toBe(123); }); + it('rejects numeric fields with suffix garbage or fractional values', async () => { + await expect(parseMessage( + [{ type: 'at', data: { qq: '123abc' } }] as any, + false, + )).rejects.toMatchObject({ code: 'INVALID_FIELD' }); + await expect(parseMessage( + [{ type: 'reply', data: { id: '456junk' } }] as any, + false, + )).rejects.toMatchObject({ code: 'INVALID_FIELD' }); + await expect(parseMessage( + [{ type: 'face', data: { id: 1.9 } }] as any, + false, + )).rejects.toMatchObject({ code: 'INVALID_FIELD' }); + }); + it('parses image segment', async () => { const result = await parseMessage( [{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any, @@ -111,6 +163,7 @@ describe('parseMessage', () => { ); expect(result[0].type).toBe('image'); expect(result[0].url).toBe('https://multimedia.nt.qq.com.cn/download?fileid=abc&rkey=xyz'); + expect(result[0].subType).toBe(1); }); it('keeps file when it is itself loadable even if a url is also present', async () => { @@ -167,12 +220,15 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]); }); - it('drops video segment with empty source', async () => { - const result = await parseMessage( + it('rejects a video segment with an empty source', async () => { + await expect(parseMessage( [{ type: 'video', data: {} }] as any, false, - ); - expect(result).toEqual([]); + )).rejects.toMatchObject({ + name: 'MessageElementValidationError', + code: 'MISSING_FIELD', + elementType: 'video', + }); }); it('parses record segment from data.path (NapCat parity)', async () => { @@ -183,12 +239,15 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'record', url: 'C:\\voices\\hi.silk' }]); }); - it('drops record segment with empty source', async () => { - const result = await parseMessage( + it('rejects a record segment with an empty source', async () => { + await expect(parseMessage( [{ type: 'record', data: {} }] as any, false, - ); - expect(result).toEqual([]); + )).rejects.toMatchObject({ + name: 'MessageElementValidationError', + code: 'MISSING_FIELD', + elementType: 'record', + }); }); it('parses at segment', async () => { @@ -248,11 +307,7 @@ describe('parseMessage', () => { expect(protoElems[0].text?.str).toBe('@User '); }); - it('skips record send when SendContext is absent (graceful no-bridge path)', async () => { - // Without a SendContext, buildSendElems can't run highway upload — - // it should warn and drop the element instead of throwing into the - // ffmpegAddon (which would explode for callers that don't actually - // need to send). + it('rejects the whole message when record SendContext is absent', async () => { const elements = await parseMessage( [ { type: 'text', data: { text: 'hi ' } }, @@ -260,13 +315,10 @@ describe('parseMessage', () => { ] as any, false, ); - const protoElems = await buildSendElems(elements); - // Only the leading text should make it through. - expect(protoElems).toHaveLength(1); - expect(protoElems[0].text?.str).toBe('hi '); + await expect(buildSendElems(elements)).rejects.toBeInstanceOf(MessageElementValidationError); }); - it('skips video send when SendContext is absent (graceful no-bridge path)', async () => { + it('rejects the whole message when video SendContext is absent', async () => { const elements = await parseMessage( [ { type: 'text', data: { text: 'hi ' } }, @@ -274,9 +326,7 @@ describe('parseMessage', () => { ] as any, false, ); - const protoElems = await buildSendElems(elements); - expect(protoElems).toHaveLength(1); - expect(protoElems[0].text?.str).toBe('hi '); + await expect(buildSendElems(elements)).rejects.toBeInstanceOf(MessageElementValidationError); }); it('builds video commonElem through NTV2 fast-upload response', async () => { @@ -357,16 +407,18 @@ describe('parseMessage', () => { expect(result[2].type).toBe('text'); }); - it('skips unknown segment types', async () => { - const result = await parseMessage( + it('rejects the whole message when one segment type is unknown', async () => { + await expect(parseMessage( [ { type: 'text', data: { text: 'ok' } }, { type: 'unknown_type_xyz', data: {} }, ] as any, false, - ); - expect(result).toHaveLength(1); - expect(result[0].type).toBe('text'); + )).rejects.toMatchObject({ + name: 'MessageElementValidationError', + code: 'UNKNOWN_TYPE', + elementType: 'unknown_type_xyz', + }); }); }); @@ -409,12 +461,22 @@ describe('parseMessage', () => { expect((result[0] as any).emojiId).toBeUndefined(); }); - it('drops an mface segment without emoji_id', async () => { - const result = await parseMessage( + it('rejects an mface segment without emoji_id', async () => { + await expect(parseMessage( [{ type: 'mface', data: { emoji_package_id: 12, summary: 'x' } }] as any, false, - ); - expect(result).toEqual([]); + )).rejects.toMatchObject({ code: 'MISSING_FIELD', elementType: 'mface' }); + }); + + it('rejects a non-hex market-face GUID before wire encoding', async () => { + await expect(parseMessage( + [{ type: 'mface', data: { emoji_id: 'zz', summary: 'broken' } }] as any, + false, + )).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'mface', + field: 'emojiId', + }); }); it('builds the wire marketFace element (faceId = hex(emoji_id), NapCat constants)', async () => { @@ -447,6 +509,32 @@ describe('parseMessage', () => { expect(result[0].text).toBe('{"app":"test"}'); }); + it('reads canonical xml resid and file_size fields', async () => { + const xml = await parseMessage( + [{ type: 'xml', data: { data: '', resid: '35' } }] as any, + false, + ); + expect(xml).toEqual([{ type: 'xml', text: '', subType: 35 }]); + + const file = await parseMessage( + [{ type: 'file', data: { file_id: 'fid', file_size: '4096' } }] as any, + false, + ); + expect(file).toEqual([{ type: 'file', fileId: 'fid', fileSize: 4096 }]); + + await expect(parseMessage([{ + type: 'file', + data: { file: 'report.pdf', url: 'https://example.com/report.pdf' }, + }] as any, false)).resolves.toEqual([{ + type: 'file', + url: 'https://example.com/report.pdf', + }]); + + await expect(parseMessage('[CQ:file,id=fid-from-raw]', false)).resolves.toEqual([ + { type: 'file', fileId: 'fid-from-raw' }, + ]); + }); + it('parses reply segment with resolveReplySequence', async () => { const result = await parseMessage( [{ type: 'reply', data: { id: 42 } }] as any, @@ -471,6 +559,29 @@ describe('parseMessage', () => { expect(parsed.meta.news.title).toBe('Test'); }); + it('rejects malformed rich input sugar before resolver or signer side effects', async () => { + const resolveContactArk = vi.fn(); + const fetchMock = vi.fn(); + vi.stubGlobal('fetch', fetchMock); + try { + await expect(parseMessage([{ type: 'share', data: {} }] as any, false)) + .rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'share' }); + await expect(parseMessage([{ type: 'location', data: { lat: '', lon: '181' } }] as any, false)) + .rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'location' }); + await expect(parseMessage( + [{ type: 'contact', data: { type: 'channel', id: '123' } }] as any, + false, + { resolveContactArk }, + )).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'contact' }); + await expect(parseMessage([{ type: 'music', data: { type: '163' } }] as any, false)) + .rejects.toMatchObject({ code: 'MISSING_FIELD', elementType: 'music' }); + } finally { + vi.unstubAllGlobals(); + } + expect(resolveContactArk).not.toHaveBeenCalled(); + expect(fetchMock).not.toHaveBeenCalled(); + }); + it('parses rps as face', async () => { const result = await parseMessage( [{ type: 'rps', data: {} }] as any, @@ -491,25 +602,36 @@ describe('parseMessage', () => { expect(result[0].faceId).toBe(358); }); - it('parses shake as poke', async () => { - const result = await parseMessage( + it('rejects shake/poke with a dedicated-Action hint', async () => { + await expect(parseMessage( [{ type: 'shake', data: {} }] as any, false, - ); - expect(result).toHaveLength(1); - expect(result[0].type).toBe('poke'); + )).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'poke', + message: expect.stringContaining('dedicated poke Action'), + }); + + await expect(parseMessage( + [{ type: 'poke', data: { type: 7 } }] as any, + false, + )).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'poke', + }); }); - it('ignores anonymous segment', async () => { - const result = await parseMessage( + it('rejects anonymous because it has no executable send semantics', async () => { + await expect(parseMessage( [ { type: 'anonymous', data: {} }, { type: 'text', data: { text: 'hi' } }, ] as any, false, - ); - expect(result).toHaveLength(1); - expect(result[0].type).toBe('text'); + )).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'anonymous', + }); }); it('parses location as json card', async () => { @@ -576,14 +698,20 @@ describe('parseMessage', () => { }); describe('edge cases', () => { - it('returns empty for null', async () => { - const result = await parseMessage(null as any, false); - expect(result).toEqual([]); + it('rejects null', async () => { + await expect(parseMessage(null as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD' }); }); - it('returns empty for number', async () => { - const result = await parseMessage(42 as any, false); - expect(result).toEqual([]); + it('rejects a number', async () => { + await expect(parseMessage(42 as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD' }); + }); + + it('rejects an empty segment array and an object without type', async () => { + await expect(parseMessage([] as any, false)).rejects.toMatchObject({ code: 'MISSING_FIELD' }); + await expect(parseMessage({ data: { text: 'x' } } as any, false)).rejects.toMatchObject({ + code: 'MISSING_FIELD', + field: 'type', + }); }); }); @@ -615,24 +743,44 @@ describe('parseMessage', () => { expect(result).toEqual([{ type: 'file', url: '/local/path/a.bin' }]); }); - it('drops a file segment with neither file_id nor file/url', async () => { + it('does not let an empty file field mask a valid url', async () => { const result = await parseMessage( - [{ type: 'file', data: {} } as any], + [{ type: 'file', data: { file: '', url: 'https://example.com/a.bin' } } as any], false, ); - expect(result).toEqual([]); + expect(result).toEqual([{ type: 'file', url: 'https://example.com/a.bin' }]); + }); + + it('rejects a file segment with neither file_id nor file/url', async () => { + await expect(parseMessage( + [{ type: 'file', data: {} } as any], + false, + )).rejects.toMatchObject({ code: 'MISSING_FIELD', elementType: 'file' }); }); it('accepts fileId / filename / fileName / md5 / sha1 aliases', async () => { const result = await parseMessage( [{ type: 'file', - data: { fileId: 'fid-2', filename: 'b.zip', fileSize: 456, md5: 'AB', sha1: 'CD' }, + data: { + fileId: 'fid-2', + filename: 'b.zip', + fileSize: 456, + md5: 'ab'.repeat(16), + sha1: 'cd'.repeat(20), + }, } as any], false, ); expect(result).toEqual([ - { type: 'file', fileId: 'fid-2', fileName: 'b.zip', fileSize: 456, md5Hex: 'AB', sha1Hex: 'CD' }, + { + type: 'file', + fileId: 'fid-2', + fileName: 'b.zip', + fileSize: 456, + md5Hex: 'ab'.repeat(16), + sha1Hex: 'cd'.repeat(20), + }, ]); }); }); diff --git a/packages/onebot/tests/network-bootstrap-meta.test.ts b/packages/onebot/tests/network-bootstrap-meta.test.ts index cb26808c..3c114f5b 100644 --- a/packages/onebot/tests/network-bootstrap-meta.test.ts +++ b/packages/onebot/tests/network-bootstrap-meta.test.ts @@ -163,6 +163,7 @@ describe('WsServerAdapter — bootstrap on connect + disable on close (character it('sends the bootstrap triplet to a new Event connection', () => { const adapter = new WsServerAdapter('wss', cfg(), ctx()); adapter.open(); + servers[0].emit('listening'); const sock = new FakeWebSocket(); servers[0].simulateConnection(sock, req); @@ -174,6 +175,7 @@ describe('WsServerAdapter — bootstrap on connect + disable on close (character it('broadcasts a single disable lifecycle to connected event clients on close()', () => { const adapter = new WsServerAdapter('wss', cfg(), ctx()); adapter.open(); + servers[0].emit('listening'); const sock = new FakeWebSocket(); servers[0].simulateConnection(sock, req); sock.sent.length = 0; // drop the bootstrap frames; we only care about close @@ -192,6 +194,7 @@ describe('WsServerAdapter — bootstrap on connect + disable on close (character // the disable broadcast — the close()-side Api guard the lift reroutes. const adapter = new WsServerAdapter('wss', cfg({ role: undefined }), ctx()); adapter.open(); + servers[0].emit('listening'); const eventSock = new FakeWebSocket(); const apiSock = new FakeWebSocket(); servers[0].simulateConnection(eventSock, { headers: {}, url: '/event' }); diff --git a/packages/onebot/tests/network-manager.test.ts b/packages/onebot/tests/network-manager.test.ts index 758ed382..24843390 100644 --- a/packages/onebot/tests/network-manager.test.ts +++ b/packages/onebot/tests/network-manager.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from 'vitest'; -import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/network'; +import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager, type AdapterStatus } from '../src/network'; import type { NetworkAdapterContext } from '../src/network'; import type { JsonObject, NetworkBase } from '../src/types'; import type { DispatchPayload } from '../src/event-filter'; @@ -16,6 +16,7 @@ class FakeAdapter extends IOneBotNetworkAdapter { reloads = 0; // Last dispatch payload object identity, to assert it was reused per emit. lastPayloads: DispatchPayload[] = []; + waitForEvent: Promise | undefined; open(): void { this.opens++; @@ -43,10 +44,19 @@ class FakeAdapter extends IOneBotNetworkAdapter { protected bindingSignature(config: FakeNetworkConfig): string { return JSON.stringify(config); } - onEvent(event: JsonObject, payload: DispatchPayload): void { + describeStatus(): AdapterStatus { + return { + name: this.name, + kind: 'httpClient', + status: this.isActive ? 'ok' : 'disabled', + detail: this.isActive ? 'active' : 'disabled', + }; + } + async onEvent(event: JsonObject, payload: DispatchPayload): Promise { this.events.push(event); this.lastPayloads.push(payload); if (this.config.failOnEvent) throw new Error('boom'); + await this.waitForEvent; } } @@ -83,7 +93,7 @@ const SAMPLE_EVENT: JsonObject = { }; describe('OneBotNetworkManager', () => { - it('opens and emits to every active adapter in parallel', async () => { + it('opens every adapter and emits to every active adapter', async () => { const mgr = new OneBotNetworkManager(); const a = makeAdapter('a'); const b = makeAdapter('b'); @@ -129,17 +139,17 @@ describe('OneBotNetworkManager', () => { expect(bad.events).toHaveLength(1); }); - it('replaces an existing adapter under the same name and closes the old one', async () => { + it('rejects duplicate registration instead of detaching the old close', async () => { const mgr = new OneBotNetworkManager(); const first = makeAdapter('dup'); mgr.register(first); await mgr.openAll(); const second = makeAdapter('dup'); - mgr.register(second); + expect(() => mgr.register(second)).toThrow(/already registered/); - expect(mgr.get('dup')).toBe(second); - expect(first.closes).toBe(1); + expect(mgr.get('dup')).toBe(first); + expect(first.closes).toBe(0); }); it('closeOne shuts down a single adapter and removes it', async () => { @@ -182,4 +192,35 @@ describe('OneBotNetworkManager', () => { await mgr.closeAll(); expect(mgr.hasActiveAdapters()).toBe(false); }); + + it('rejects compatibility registration after shutdown', async () => { + const mgr = new OneBotNetworkManager(); + await mgr.shutdown(); + + expect(() => mgr.register(makeAdapter('late'))).toThrow(/shutting down/); + await expect(mgr.shutdown()).resolves.toEqual({ closed: true, errors: [] }); + expect(mgr.list()).toEqual([]); + }); + + it('stops new emits and drains an in-flight emit before adapter close', async () => { + let release!: () => void; + const eventGate = new Promise((resolve) => { release = resolve; }); + const mgr = new OneBotNetworkManager(); + const adapter = makeAdapter('slow'); + adapter.waitForEvent = eventGate; + mgr.register(adapter); + await mgr.openAll(); + + const emitting = mgr.emitEvent(SAMPLE_EVENT); + const closing = mgr.shutdown(); + await expect(mgr.emitEvent(SAMPLE_EVENT)).rejects.toThrow(/shutting down/); + await Promise.resolve(); + await Promise.resolve(); + expect(adapter.closes).toBe(0); + + release(); + await emitting; + await closing; + expect(adapter.closes).toBe(1); + }); }); diff --git a/packages/onebot/tests/network-reconcile.test.ts b/packages/onebot/tests/network-reconcile.test.ts new file mode 100644 index 00000000..1515d3e3 --- /dev/null +++ b/packages/onebot/tests/network-reconcile.test.ts @@ -0,0 +1,340 @@ +import { describe, expect, it } from 'vitest'; +import { + IOneBotNetworkAdapter, + OneBotNetworkManager, + type AdapterStatus, + type DesiredNetworkAdapter, + type NetworkAdapterKind, + type NetworkAdapterContext, +} from '../src/network'; +import type { DispatchPayload } from '../src/event-filter'; +import type { JsonObject, NetworkBase, OneBotConfig } from '../src/types'; + +const CTX: NetworkAdapterContext = { + uin: '10001', + api: {} as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), +}; + +interface Gate { + promise: Promise; + release(): void; +} + +function gate(): Gate { + let release!: () => void; + return { + promise: new Promise((resolve) => { release = resolve; }), + release: () => release(), + }; +} + +class ProbeAdapter extends IOneBotNetworkAdapter { + private closeAttempts = 0; + failNextOpen = false; + constructor( + name: string, + config: NetworkBase, + readonly kind: NetworkAdapterKind, + private readonly trace: string[], + private readonly slowOpen: Gate, + ) { + super(name, config, CTX); + } + + async open(): Promise { + const marker = this.config.accessToken ?? ''; + this.trace.push(`open:${this.kind}:${this.name}:${marker}`); + if (this.failNextOpen) { + this.failNextOpen = false; + throw new Error(`restore failed for ${this.name}`); + } + if (marker === 'slow') await this.slowOpen.promise; + if (marker === 'fail' || marker === 'fail-open-close') throw new Error(`bind failed for ${this.name}`); + if (this.config.enabled !== false) this.isEnabled = true; + } + + async close(): Promise { + const marker = this.config.accessToken ?? ''; + this.trace.push(`close:${this.kind}:${this.name}:${marker}`); + this.closeAttempts += 1; + if ( + marker === 'fail-close' || + marker === 'fail-open-close' || + (marker === 'fail-close-once' && this.closeAttempts === 1) + ) { + throw new Error(`close failed for ${this.name}`); + } + this.isEnabled = false; + } + + protected bindingSignature(config: NetworkBase): string { + return config.accessToken ?? ''; + } + + describeStatus(): AdapterStatus { + return { + name: this.name, + kind: this.kind, + status: this.isActive ? 'ok' : 'disabled', + detail: this.isActive ? 'active' : 'disabled', + }; + } + + onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* unused */ } +} + +function emptyConfig(): OneBotConfig { + return { + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + statusCommand: { enabled: true, swallow: false, cooldownSeconds: 5, trigger: '#sl' }, + notifications: { channelIds: [] }, + }; +} + +function httpClient(name: string, marker: string, enabled = true) { + return { + name, + enabled, + url: `http://localhost/${name}`, + accessToken: marker, + messageFormat: 'array' as const, + reportSelfMessage: false, + }; +} + +function wsClient(name: string, marker: string) { + return { + name, + url: `ws://localhost/${name}`, + accessToken: marker, + role: 'Universal' as const, + reconnectIntervalMs: 1000, + messageFormat: 'array' as const, + reportSelfMessage: false, + }; +} + +function manager(trace: string[], slowOpen: Gate): OneBotNetworkManager { + return new OneBotNetworkManager((desired: DesiredNetworkAdapter) => + new ProbeAdapter(desired.name, desired.config, desired.kind, trace, slowOpen)); +} + +describe('OneBotNetworkManager desired-plan reconciliation', () => { + it('rejects a duplicate name across kinds before creating any adapter', () => { + const trace: string[] = []; + const config = emptyConfig(); + config.networks.httpClients.push(httpClient('shared', 'a')); + config.networks.wsClients.push(wsClient('shared', 'b')); + const mgr = manager(trace, gate()); + + expect(() => mgr.reconcile(config)).toThrow(/duplicated in httpClients and wsClients/); + expect(trace).toEqual([]); + }); + + it('closes and recreates when a name changes kind', async () => { + const trace: string[] = []; + const mgr = manager(trace, gate()); + const first = emptyConfig(); + first.networks.httpClients.push(httpClient('edge', 'old')); + await mgr.reconcile(first); + trace.length = 0; + + const next = emptyConfig(); + next.networks.wsClients.push(wsClient('edge', 'new')); + const result = await mgr.reconcile(next); + + expect(result.applied).toBe(true); + expect(trace).toEqual([ + 'close:httpClient:edge:old', + 'open:wsClient:edge:new', + ]); + expect(result.statuses[0]).toMatchObject({ name: 'edge', kind: 'wsClient', status: 'ok' }); + }); + + it('serializes consecutive reconciles in invocation order', async () => { + const trace: string[] = []; + const slow = gate(); + const mgr = manager(trace, slow); + const first = emptyConfig(); + first.networks.httpClients.push(httpClient('edge', 'old')); + await mgr.reconcile(first); + trace.length = 0; + + const second = emptyConfig(); + second.networks.httpClients.push(httpClient('edge', 'slow')); + const third = emptyConfig(); + third.networks.httpClients.push(httpClient('edge', 'final')); + const applyingSecond = mgr.reconcile(second); + const applyingThird = mgr.reconcile(third); + await Promise.resolve(); + await Promise.resolve(); + + expect(trace).toEqual(['close:httpClient:edge:old', 'open:httpClient:edge:slow']); + slow.release(); + await Promise.all([applyingSecond, applyingThird]); + expect(trace).toEqual([ + 'close:httpClient:edge:old', + 'open:httpClient:edge:slow', + 'close:httpClient:edge:slow', + 'open:httpClient:edge:final', + ]); + }); + + it('restores the previous live config and exposes degraded status when reload fails', async () => { + const trace: string[] = []; + const mgr = manager(trace, gate()); + const first = emptyConfig(); + first.networks.httpClients.push(httpClient('edge', 'old')); + await mgr.reconcile(first); + trace.length = 0; + + const next = emptyConfig(); + next.networks.httpClients.push(httpClient('edge', 'fail')); + const result = await mgr.reconcile(next); + + expect(result.applied).toBe(false); + expect(result.errors).toEqual([ + expect.objectContaining({ name: 'edge', phase: 'reload', restored: true, message: 'bind failed for edge' }), + ]); + expect(trace).toEqual([ + 'close:httpClient:edge:old', + 'open:httpClient:edge:fail', + 'open:httpClient:edge:old', + ]); + expect(mgr.get('edge')?.currentConfig.accessToken).toBe('old'); + expect(result.statuses[0]).toMatchObject({ + name: 'edge', + status: 'degraded', + lastError: 'bind failed for edge', + }); + }); + + it('queues shutdown behind an active reload and rejects later reloads', async () => { + const trace: string[] = []; + const slow = gate(); + const mgr = manager(trace, slow); + const first = emptyConfig(); + first.networks.httpClients.push(httpClient('edge', 'old')); + await mgr.reconcile(first); + trace.length = 0; + + const next = emptyConfig(); + next.networks.httpClients.push(httpClient('edge', 'slow')); + const applying = mgr.reconcile(next); + const closing = mgr.shutdown(); + await expect(mgr.reconcile(first)).rejects.toThrow(/shutting down/); + await Promise.resolve(); + await Promise.resolve(); + expect(trace).toEqual(['close:httpClient:edge:old', 'open:httpClient:edge:slow']); + + slow.release(); + await applying; + await expect(closing).resolves.toMatchObject({ closed: true, errors: [] }); + expect(trace.at(-1)).toBe('close:httpClient:edge:slow'); + }); + + it('shuts adapters down sequentially in reverse creation order', async () => { + const trace: string[] = []; + const mgr = manager(trace, gate()); + const config = emptyConfig(); + config.networks.httpClients.push(httpClient('a', '1'), httpClient('b', '2')); + await mgr.reconcile(config); + trace.length = 0; + + await mgr.shutdown(); + expect(trace).toEqual(['close:httpClient:b:2', 'close:httpClient:a:1']); + }); + + it('retains failed shutdown adapters and allows a later close retry', async () => { + const trace: string[] = []; + const mgr = manager(trace, gate()); + const config = emptyConfig(); + config.networks.httpClients.push(httpClient('edge', 'fail-close-once')); + await mgr.reconcile(config); + trace.length = 0; + + const first = await mgr.shutdown(); + expect(first.closed).toBe(false); + expect(mgr.get('edge')).not.toBeNull(); + expect(mgr.describeStatuses()[0]).toMatchObject({ status: 'degraded', lastError: 'close failed for edge' }); + + const second = await mgr.shutdown(); + expect(second).toEqual({ closed: true, errors: [] }); + expect(mgr.get('edge')).toBeNull(); + expect(trace).toEqual([ + 'close:httpClient:edge:fail-close-once', + 'close:httpClient:edge:fail-close-once', + ]); + }); + + it('keeps a replacement managed when its cleanup close fails', async () => { + const trace: string[] = []; + const mgr = manager(trace, gate()); + const first = emptyConfig(); + first.networks.httpClients.push(httpClient('edge', 'old')); + await mgr.reconcile(first); + trace.length = 0; + + const next = emptyConfig(); + next.networks.wsClients.push(wsClient('edge', 'fail-open-close')); + const result = await mgr.reconcile(next); + + expect(result.applied).toBe(false); + expect(trace).toEqual([ + 'close:httpClient:edge:old', + 'open:wsClient:edge:fail-open-close', + 'close:wsClient:edge:fail-open-close', + ]); + expect(mgr.describeStatuses()[0]).toMatchObject({ + name: 'edge', + kind: 'wsClient', + status: 'degraded', + lastError: 'bind failed for edge', + }); + expect(result.errors.map((error) => error.phase)).toEqual(['close', 'replace']); + }); + + it('marks the old adapter degraded when factory creation and restoration both fail', async () => { + const trace: string[] = []; + const slow = gate(); + const mgr = new OneBotNetworkManager((desired) => { + if (desired.kind === 'wsClient') throw new Error('factory failed'); + return new ProbeAdapter(desired.name, desired.config, desired.kind, trace, slow); + }); + const first = emptyConfig(); + first.networks.httpClients.push(httpClient('edge', 'old')); + await mgr.reconcile(first); + (mgr.get('edge') as ProbeAdapter).failNextOpen = true; + + const next = emptyConfig(); + next.networks.wsClients.push(wsClient('edge', 'new')); + const result = await mgr.reconcile(next); + + expect(result.applied).toBe(false); + expect(result.errors.map((error) => error.phase)).toEqual(['restore', 'replace']); + expect(mgr.describeStatuses()[0]).toMatchObject({ + name: 'edge', + kind: 'httpClient', + status: 'degraded', + lastError: 'factory failed', + }); + }); + + it('isolates one failed adapter while applying the remaining plan', async () => { + const trace: string[] = []; + const mgr = manager(trace, gate()); + const config = emptyConfig(); + config.networks.httpClients.push(httpClient('bad', 'fail'), httpClient('good', 'ok')); + + const result = await mgr.reconcile(config); + + expect(result.applied).toBe(false); + expect(result.errors).toHaveLength(1); + expect(result.statuses).toEqual([ + expect.objectContaining({ name: 'bad', status: 'degraded' }), + expect.objectContaining({ name: 'good', status: 'ok' }), + ]); + }); +}); diff --git a/packages/onebot/tests/request-actions.test.ts b/packages/onebot/tests/request-actions.test.ts index 0b63f6be..a5c86a6f 100644 --- a/packages/onebot/tests/request-actions.test.ts +++ b/packages/onebot/tests/request-actions.test.ts @@ -8,7 +8,7 @@ const APIS_ROUTING: Record = { fetchFriendList: 'contacts', fetchGroupList: 'contacts', fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts', fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts', - getGroupInviteCardSequence: 'contacts', + getGroupInviteCardSequence: 'contacts', findGroupInviteCardGroupBySequence: 'contacts', }; function fakeBridge(overrides: Record = {}): BridgeInterface { @@ -52,6 +52,63 @@ function fakeRequest(overrides: Partial = {}): GroupRequestInf } describe('onebot/modules/request-actions / handleGroupAddRequest', () => { + it('uses a canonical self-contained flag without refetching the request queue', async () => { + const setAddRequest = vi.fn(async () => {}); + const fetchGroupRequests = vi.fn(async () => []); + const bridge = fakeBridge({ + fetchGroupRequests, + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await handleGroupAddRequest(bridge, 'slreq:1:123456:999:22:1', true, 'ok'); + + expect(fetchGroupRequests).not.toHaveBeenCalled(); + expect(setAddRequest).toHaveBeenCalledWith(999, 123456, 22, true, 'ok', true); + }); + + it('accepts a NapCat numeric sequence and resolves the exact main-inbox request', async () => { + const setAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + fetchGroupRequests: vi.fn(async (filtered: boolean) => filtered ? [] : [ + fakeRequest({ groupId: 999, sequence: 261237407, eventType: 7, filtered: false }), + ]), + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await handleGroupAddRequest(bridge, '261237407', false, 'no'); + + expect(setAddRequest).toHaveBeenCalledWith(999, 261237407, 7, false, 'no', false); + }); + + it('accepts a NapCat numeric sequence from the filtered inbox', async () => { + const setAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + fetchGroupRequests: vi.fn(async (filtered: boolean) => filtered ? [ + fakeRequest({ groupId: 999, sequence: 55, eventType: 2, filtered: true }), + ] : []), + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await handleGroupAddRequest(bridge, '55', true, 'ok'); + + expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true); + }); + + it('resolves a private invite-card msgseq by its cached group', async () => { + const setAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => 999), + fetchGroupRequests: vi.fn(async () => []), + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await handleGroupAddRequest(bridge, '778899', true, 'ok'); + + expect(setAddRequest).toHaveBeenCalledWith(999, 778899, 2, true, 'ok', false); + }); + it('matches add requests by groupId and targetUid', async () => { const setAddRequest = vi.fn(async () => {}); const bridge = fakeBridge({ @@ -111,4 +168,60 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => { await expect(handleGroupAddRequest(bridge, 'invite:999:u_i', true, 'ok')) .rejects.toThrow(/matching group request not found/); }); + + it('does not treat an inviter QQ number as a request sequence (#213)', async () => { + const setAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + fetchGroupRequests: vi.fn(async () => [ + fakeRequest({ groupId: 888, invitorUin: 261237407, sequence: 123456 }), + ]), + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await expect(handleGroupAddRequest(bridge, '261237407', true, 'ok')) + .rejects.toThrow(/sequence 261237407 not found/); + expect(setAddRequest).not.toHaveBeenCalled(); + }); + + it('does not fall back to another request from the same group', async () => { + const setAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async () => [ + fakeRequest({ groupId: 999, targetUid: 'u_someone_else' }), + ]), + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await expect(handleGroupAddRequest(bridge, 'add:999:u_missing', true, 'ok')) + .rejects.toThrow(/matching group request not found/); + expect(setAddRequest).not.toHaveBeenCalled(); + }); + + it('uses the surviving inbox when the other request lookup fails', async () => { + const setAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + fetchGroupRequests: vi.fn(async (filtered: boolean) => { + if (!filtered) throw new Error('main inbox down'); + return [fakeRequest({ groupId: 999, sequence: 55, eventType: 2, filtered: true })]; + }), + apis: { groupAdmin: { setAddRequest } } as any, + }); + + await handleGroupAddRequest(bridge, '55', true, 'ok'); + + expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true); + }); + + it('distinguishes request-queue failure from a genuine missing request', async () => { + const bridge = fakeBridge({ + findGroupInviteCardGroupBySequence: vi.fn(() => undefined), + fetchGroupRequests: vi.fn(async () => { throw new Error('OIDB unavailable'); }), + apis: { groupAdmin: { setAddRequest: vi.fn(async () => {}) } } as any, + }); + + await expect(handleGroupAddRequest(bridge, '55', true, 'ok')) + .rejects.toThrow(/failed to fetch group requests/); + }); }); diff --git a/packages/onebot/tests/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts index 18745383..0d265382 100644 --- a/packages/onebot/tests/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -104,7 +104,7 @@ describe('send_group_msg with {type:"file"} segment', () => { expect(fileFileId).toBe('gfid-xyz'); }); - it('file segment without file_id is skipped (with a warn-level log)', async () => { + it('rejects the whole message when a file segment has neither file_id nor url', async () => { const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); const publish = vi.fn(); const upload = vi.fn(); @@ -117,12 +117,15 @@ describe('send_group_msg with {type:"file"} segment', () => { } as any); const ctx = makeCtx(bridge); - await sendGroupMessage(ctx, 12345, [ + await expect(sendGroupMessage(ctx, 12345, [ { type: 'text', data: { text: 'with bad file segment' } }, { type: 'file', data: {} }, // no file_id and no url - ] as any, false); + ] as any, false)).rejects.toMatchObject({ + code: 'MISSING_FIELD', + elementType: 'file', + }); - expect(sendGroupMessage_bridge).toHaveBeenCalledOnce(); + expect(sendGroupMessage_bridge).not.toHaveBeenCalled(); expect(publish).not.toHaveBeenCalled(); expect(upload).not.toHaveBeenCalled(); }); diff --git a/packages/onebot/tests/send-private-c2c-file.test.ts b/packages/onebot/tests/send-private-c2c-file.test.ts index fb1e8ab8..3f2868a0 100644 --- a/packages/onebot/tests/send-private-c2c-file.test.ts +++ b/packages/onebot/tests/send-private-c2c-file.test.ts @@ -3,8 +3,7 @@ // Symptom in the wild: bot called `send_private_msg` with a // `{type:'file', file_id}` segment; the OneBot module passed it // straight to `bridge.sendPrivateMessage(userId, [fileElement])`; -// `buildSendElems` warned ("file send via elems[] is group-only") -// and dropped it; the resulting wire send had 0 elems and the chat +// `buildSendElems` used to warn and drop it; the resulting wire send had 0 elems and the chat // rendered "[空消息]". // // Fix: c2c file segments are split out at the OneBot layer in @@ -60,7 +59,7 @@ describe('send_private_msg with {type:"file"} segment', () => { await sendPrivateMessage(ctx, 67890, [{ type: 'file', - data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233' }, + data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233445566778899aabbccddeeff' }, }] as any, false); expect(sendC2cFileMessage).toHaveBeenCalledOnce(); @@ -74,8 +73,7 @@ describe('send_private_msg with {type:"file"} segment', () => { fileName: 'doc.txt', fileSize: 123, }); - // md5 decoded from hex (4 bytes for '00112233') - expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex')); + expect(info.fileMd5).toEqual(Buffer.from('00112233445566778899aabbccddeeff', 'hex')); }); it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => { @@ -142,7 +140,13 @@ describe('send_private_msg with {type:"file"} segment', () => { const ctx = makeCtx(bridge); await sendPrivateMessage(ctx, 67890, [{ - type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' }, + type: 'file', data: { + file_id: 'uuid-x', + name: 'inline.txt', + size: 200, + md5: '11223344556677889900aabbccddeeff', + file_hash: 'inline-hash', + }, }] as any, false); const [, , info] = sendC2cFileMessage.mock.calls[0]!; @@ -151,7 +155,7 @@ describe('send_private_msg with {type:"file"} segment', () => { fileSize: 200, fileHash: 'inline-hash', }); - expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex')); + expect(info.fileMd5).toEqual(Buffer.from('11223344556677889900aabbccddeeff', 'hex')); }); it('mixed file + text splits across two sends (text first, file second)', async () => { @@ -185,10 +189,7 @@ describe('send_private_msg with {type:"file"} segment', () => { expect(fileInfo).toMatchObject({ fileId: 'uuid-xyz', fileName: 'pkg.zip' }); }); - it('file segment without file_id is skipped (with a warn-level log)', async () => { - // OneBot11 file segments are upload-by-reference — without a - // file_id there's nothing to send. Previously these slipped - // through to the elems[] path and shipped empty messages. + it('rejects the whole message when a file segment has neither file_id nor url', async () => { const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const sendC2cFileMessage = vi.fn(); const bridge = fakeBridge({ @@ -198,13 +199,15 @@ describe('send_private_msg with {type:"file"} segment', () => { } as any); const ctx = makeCtx(bridge); - await sendPrivateMessage(ctx, 67890, [ + await expect(sendPrivateMessage(ctx, 67890, [ { type: 'text', data: { text: 'with bad file segment' } }, { type: 'file', data: {} }, // no file_id - ] as any, false); + ] as any, false)).rejects.toMatchObject({ + code: 'MISSING_FIELD', + elementType: 'file', + }); - // Text still went out, file dropped (no c2c file call). - expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce(); + expect(sendPrivateMessage_bridge).not.toHaveBeenCalled(); expect(sendC2cFileMessage).not.toHaveBeenCalled(); }); @@ -228,6 +231,25 @@ describe('send_private_msg with {type:"file"} segment', () => { expect(sendC2cFileMessage).not.toHaveBeenCalled(); }); + it('does not send preceding text when a mixed file message cannot resolve uid', async () => { + const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt); + const sendC2cFileMessage = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any, + resolveUserUid: vi.fn(async () => ''), + recallUploadedFile: vi.fn(() => undefined), + } as any); + const ctx = makeCtx(bridge); + + await expect(sendPrivateMessage(ctx, 67890, [ + { type: 'text', data: { text: 'must remain unsent' } }, + { type: 'file', data: { file_id: 'uuid-orphan', name: 'x.txt' } }, + ] as any, false)).rejects.toThrow(/could not resolve uid/); + + expect(sendPrivateMessage_bridge).not.toHaveBeenCalled(); + expect(sendC2cFileMessage).not.toHaveBeenCalled(); + }); + it('file segment with url (no file_id) auto-uploads via groupFile.uploadPrivate (not sendC2cFile)', async () => { // uploadPrivate() internally calls sendC2cFile() — must NOT call it again. const uploadPrivate = vi.fn(async (_uid: number, _src: string, _name: string, _doUpload: boolean) => diff --git a/packages/onebot/tests/send-private-strip-at.test.ts b/packages/onebot/tests/send-private-strip-at.test.ts index 97115e53..5c846741 100644 --- a/packages/onebot/tests/send-private-strip-at.test.ts +++ b/packages/onebot/tests/send-private-strip-at.test.ts @@ -7,11 +7,7 @@ // broken-looking wire message (the recipient sees a phantom "@QQ号" // that can't be clicked). // -// Fix: `sendPrivateMessage` now strips all `at` elements before -// handing the array to the protocol layer. When the message also -// contains a `reply` segment the strip is silent (it's the normal -// OneBot convention and the caller didn't do anything wrong); without -// a `reply` the strip still happens but a warn is logged. +// Fix: every private at is rejected before anything reaches the bridge. import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; @@ -47,34 +43,26 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { } as unknown as OneBotInstanceContext; } -describe('send_private_msg strips at segments', () => { - it('reply + at + text → only reply + text reach the wire', async () => { - const sendPrivate = vi.fn(async (_uin: number, elements: any[]) => { - // Verify no `at` element reaches the bridge - const types = elements.map((e: any) => e.type); - expect(types).not.toContain('at'); - return goodReceipt; - }); +describe('send_private_msg rejects at segments', () => { + it('reply + at + text rejects the whole message', async () => { + const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const bridge = fakeBridge({ apis: { message: { sendPrivate } } as any, resolveUserUid: vi.fn(async () => 'u_peer'), } as any); const ctx = makeCtx(bridge); - await sendPrivateMessage(ctx, 67890, [ + await expect(sendPrivateMessage(ctx, 67890, [ { type: 'reply', data: { id: '-2050237785' } }, { type: 'at', data: { qq: '67890' } }, { type: 'text', data: { text: ' ' } }, { type: 'text', data: { text: 'quoted reply text' } }, - ] as any, false); + ] as any, false)).rejects.toMatchObject({ code: 'UNSENDABLE_TYPE', elementType: 'at' }); - expect(sendPrivate).toHaveBeenCalledOnce(); - const sentElements = sendPrivate.mock.calls[0]![1] as any[]; - const sentTypes = sentElements.map(e => e.type); - expect(sentTypes).toEqual(['reply', 'text', 'text']); + expect(sendPrivate).not.toHaveBeenCalled(); }); - it('at-only message (no reply) is also stripped, throws "message is empty"', async () => { + it('at-only message (no reply) is rejected as unsendable', async () => { const sendPrivate = vi.fn(); const bridge = fakeBridge({ apis: { message: { sendPrivate } } as any, @@ -84,12 +72,15 @@ describe('send_private_msg strips at segments', () => { await expect(sendPrivateMessage(ctx, 67890, [ { type: 'at', data: { qq: '67890' } }, - ] as any, false)).rejects.toThrow('message is empty'); + ] as any, false)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'at', + }); expect(sendPrivate).not.toHaveBeenCalled(); }); - it('text + at (without reply) strips at and sends remaining text', async () => { + it('text + at (without reply) rejects the whole message', async () => { const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const bridge = fakeBridge({ apis: { message: { sendPrivate } } as any, @@ -97,17 +88,15 @@ describe('send_private_msg strips at segments', () => { } as any); const ctx = makeCtx(bridge); - await sendPrivateMessage(ctx, 67890, [ + await expect(sendPrivateMessage(ctx, 67890, [ { type: 'text', data: { text: 'hello' } }, { type: 'at', data: { qq: '67890' } }, - ] as any, false); + ] as any, false)).rejects.toMatchObject({ code: 'UNSENDABLE_TYPE', elementType: 'at' }); - expect(sendPrivate).toHaveBeenCalledOnce(); - const sentElements = sendPrivate.mock.calls[0]![1] as any[]; - expect(sentElements).toEqual([{ type: 'text', text: 'hello' }]); + expect(sendPrivate).not.toHaveBeenCalled(); }); - it('multiple at segments are all stripped', async () => { + it('multiple at segments reject the whole message', async () => { const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt); const bridge = fakeBridge({ apis: { message: { sendPrivate } } as any, @@ -115,26 +104,21 @@ describe('send_private_msg strips at segments', () => { } as any); const ctx = makeCtx(bridge); - await sendPrivateMessage(ctx, 67890, [ + await expect(sendPrivateMessage(ctx, 67890, [ { type: 'reply', data: { id: '123' } }, { type: 'at', data: { qq: '67890' } }, { type: 'at', data: { qq: '12345' } }, { type: 'text', data: { text: 'hi' } }, - ] as any, false); + ] as any, false)).rejects.toMatchObject({ code: 'UNSENDABLE_TYPE', elementType: 'at' }); - expect(sendPrivate).toHaveBeenCalledOnce(); - const sentElements = sendPrivate.mock.calls[0]![1] as any[]; - const sentTypes = sentElements.map((e: any) => e.type); - expect(sentTypes).not.toContain('at'); - expect(sentTypes).toContain('reply'); - expect(sentTypes).toContain('text'); + expect(sendPrivate).not.toHaveBeenCalled(); }); it('group messages are NOT affected (at segments preserved)', async () => { // Sanity: import sendGroupMessage and verify at segments pass through const { sendGroupMessage } = await import('../src/modules/message-actions'); - const sendGroup = vi.fn(async (_groupId: number, elements: any[]) => { + const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => { return goodReceipt; }); const bridge = fakeBridge({ diff --git a/packages/onebot/tests/streaming.test.ts b/packages/onebot/tests/streaming.test.ts index 6f4818bc..11d141a4 100644 --- a/packages/onebot/tests/streaming.test.ts +++ b/packages/onebot/tests/streaming.test.ts @@ -4,30 +4,30 @@ // `stream:'stream-action'`), normal actions stay single-frame, and failures // terminate with an error frame. Wire format mirrors NapCat's Stream API. import { describe, it, expect } from 'vitest'; -import { ApiHandler, type ApiActionContext } from '../src/api-handler'; -import { defineAction, defineStreamAction, f } from '../src/action-kit'; +import type { ApiHandler, ApiActionContext } from '../src/api-handler'; +import { defineAction, defineStreamAction, f, type RegisteredActionSpec } from '../src/action-kit'; import { okResponse, failedResponse } from '../src/types'; import { wrapStreamFrame, wrapStreamTerminal, STREAM_MARK } from '../src/streaming'; +import { createCompiledTestHandler } from './helpers/compiled-action-handler'; -function newHandler(): ApiHandler { - // The real register* run lazily (handlers capture ctx, never call it at - // registration), so an empty ctx is enough to exercise the dispatch seam. - return new ApiHandler({} as ApiActionContext); +function newHandler(...specs: RegisteredActionSpec[]): ApiHandler { + // ActionSpecs bind during the constructor but call ctx only when dispatched. + return createCompiledTestHandler({} as ApiActionContext, specs); } const parse = (frames: string[]) => frames.map((f) => JSON.parse(f) as Record); describe('Stream API plumbing', () => { it('streams N intermediate frames + a terminal frame, all echo-tagged', async () => { - const h = newHandler(); - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_stream', params: { n: f.uint() }, run: async (p, _ctx, _raw, sink) => { for (let i = 0; i < p.n; i++) await sink.send({ type: 'stream', index: i }); return okResponse({ type: 'response', total: p.n }); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest( @@ -43,17 +43,17 @@ describe('Stream API plumbing', () => { }); it('marks the action as a stream action; normal actions are not', () => { - const h = newHandler(); - defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext); - defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext); + const streamAction = defineStreamAction({ name: 'demo_stream', params: {}, run: () => okResponse({ type: 'response' }) }); + const normalAction = defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }); + const h = newHandler(streamAction, normalAction); expect(h.isStreamAction('demo_stream')).toBe(true); expect(h.isStreamAction('demo_normal')).toBe(false); expect(h.isStreamAction('nope')).toBe(false); }); it('a normal action through processStreamRequest emits exactly one un-marked frame', async () => { - const h = newHandler(); - defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }).register(h, {} as ApiActionContext); + const action = defineAction({ name: 'demo_normal', params: {}, run: () => okResponse({ ok: true }) }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_normal', params: {}, echo: 'e2' }), (j) => frames.push(j)); @@ -65,12 +65,12 @@ describe('Stream API plumbing', () => { }); it('a throwing stream action terminates with a single error frame', async () => { - const h = newHandler(); - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_boom', params: {}, run: async () => { throw new Error('boom'); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_boom', params: {}, echo: 'e3' }), (j) => frames.push(j)); @@ -82,15 +82,15 @@ describe('Stream API plumbing', () => { }); it('emits already-sent frames before the terminal error when a stream throws mid-way', async () => { - const h = newHandler(); - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_partial', params: {}, run: async (_p, _ctx, _raw, sink) => { await sink.send({ type: 'stream', index: 0 }); throw new Error('mid'); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_partial', params: {} }), (j) => frames.push(j)); @@ -102,8 +102,8 @@ describe('Stream API plumbing', () => { }); it('stream param validation fails terminate with an error frame', async () => { - const h = newHandler(); - defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }).register(h, {} as ApiActionContext); + const action = defineStreamAction({ name: 'demo_needs', params: { n: f.uint() }, run: () => okResponse({ type: 'response' }) }); + const h = newHandler(action); const frames: string[] = []; await h.processStreamRequest(JSON.stringify({ action: 'demo_needs', params: {} }), (j) => frames.push(j)); @@ -112,16 +112,16 @@ describe('Stream API plumbing', () => { }); it('aborts a stream when isAlive turns false (client disconnect)', async () => { - const h = newHandler(); let sent = 0; - defineStreamAction({ + const action = defineStreamAction({ name: 'demo_abort', params: {}, run: async (_p, _ctx, _raw, sink) => { for (let i = 0; i < 5; i++) { await sink.send({ type: 'stream', index: i }); sent++; } return okResponse({ type: 'response' }); }, - }).register(h, {} as ApiActionContext); + }); + const h = newHandler(action); const frames: string[] = []; let alive = true; @@ -164,4 +164,20 @@ describe('Stream API plumbing', () => { expect(frames).toHaveLength(3); for (const f of parse(frames)) expect(f).toMatchObject({ status: 'failed' }); }); + + it('waits for an async bad-request frame to flush', async () => { + const h = newHandler(); + let release!: () => void; + const flushed = new Promise((resolve) => { release = resolve; }); + let completed = false; + + const request = h.processStreamRequest('', async () => flushed); + void request.then(() => { completed = true; }); + await Promise.resolve(); + expect(completed).toBe(false); + + release(); + await request; + expect(completed).toBe(true); + }); }); diff --git a/packages/onebot/tests/temp-session-send.test.ts b/packages/onebot/tests/temp-session-send.test.ts new file mode 100644 index 00000000..4e0db146 --- /dev/null +++ b/packages/onebot/tests/temp-session-send.test.ts @@ -0,0 +1,60 @@ +import { describe, expect, it, vi } from 'vitest'; +import { sendPrivateMessage } from '../src/modules/message-actions'; +import { TempSessionStore } from '../src/temp-session-store'; +import type { OneBotInstanceContext } from '../src/instance-context'; + +// The passive gate lives at the very top of sendPrivateMessage, before any +// message parsing or network call. These tests exercise that gate directly: +// a temp reply (tempGroupId set) into a session the peer never opened MUST be +// refused, without ever reaching the send path. This is the structural +// guarantee that the public build cannot initiate a temp session. + +function refWith(store: TempSessionStore): OneBotInstanceContext { + const sendGroupTempMessage = vi.fn(); + const sendPrivate = vi.fn(); + return { + tempSessions: store, + // If the gate ever let a send through, these would be called — the tests + // assert they are NOT for the refused case. + bridge: { apis: { message: { sendGroupTempMessage, sendPrivate } } }, + } as unknown as OneBotInstanceContext; +} + +describe('sendPrivateMessage temp-session gate (passive-only)', () => { + it('refuses a temp reply to an unrecorded (user, group) and never sends', async () => { + const store = new TempSessionStore(); + const ref = refWith(store); + await expect( + sendPrivateMessage(ref, 1001, [{ type: 'text', data: { text: 'hi' } }], false, /* tempGroupId */ 700), + ).rejects.toThrow(/passive-only|temp session/i); + // The gate threw before any wire call. + expect((ref.bridge.apis.message as { sendGroupTempMessage: ReturnType }).sendGroupTempMessage) + .not.toHaveBeenCalled(); + }); + + it('refuses when a DIFFERENT group is recorded (exact (user, group) match required)', async () => { + const store = new TempSessionStore(); + store.record(1001, 701); // user opened a session from group 701, not 700 + const ref = refWith(store); + await expect( + sendPrivateMessage(ref, 1001, [{ type: 'text', data: { text: 'hi' } }], false, 700), + ).rejects.toThrow(/passive-only|temp session/i); + }); + + it('rejects text + file before sending a partial temp-session message', async () => { + const store = new TempSessionStore(); + store.record(1001, 700); + const ref = refWith(store); + + await expect(sendPrivateMessage(ref, 1001, [ + { type: 'text', data: { text: 'must not be sent' } }, + { type: 'file', data: { file_id: 'friend-file-id' } }, + ], false, 700)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'file', + }); + + expect((ref.bridge.apis.message as { sendGroupTempMessage: ReturnType }).sendGroupTempMessage) + .not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/temp-session-store.test.ts b/packages/onebot/tests/temp-session-store.test.ts new file mode 100644 index 00000000..6bf0de17 --- /dev/null +++ b/packages/onebot/tests/temp-session-store.test.ts @@ -0,0 +1,57 @@ +import { describe, expect, it } from 'vitest'; +import { TempSessionStore, TEMP_SESSION_TTL_MS } from '../src/temp-session-store'; + +const T0 = 1_700_000_000_000; + +describe('TempSessionStore (passive temp-session gate, #212-temp)', () => { + it('a recorded session is authorized; an unrecorded one is NOT (the core gate)', () => { + const s = new TempSessionStore(); + s.record(1001, 700, T0); + // Recorded (user, group) → allowed. + expect(s.has(1001, 700, T0)).toBe(true); + // Never recorded → refused. This is what makes send passive-only: the bot + // cannot reply to a (user, group) that never messaged it first. + expect(s.has(1001, 701, T0)).toBe(false); // same user, different group + expect(s.has(1002, 700, T0)).toBe(false); // different user, same group + expect(s.has(9999, 9999, T0)).toBe(false); // wholly unknown + }); + + it('sessions are keyed per (user, group) — one user, many groups', () => { + const s = new TempSessionStore(); + s.record(1001, 700, T0); + s.record(1001, 800, T0); + expect(s.has(1001, 700, T0)).toBe(true); + expect(s.has(1001, 800, T0)).toBe(true); + expect(s.has(1001, 900, T0)).toBe(false); + }); + + it('expires exactly at TTL and prunes on read', () => { + const s = new TempSessionStore(); + s.record(1001, 700, T0); + // Just before expiry: still valid. + expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS - 1)).toBe(true); + // At/after expiry: gone. + expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS)).toBe(false); + // A later inbound message refreshes the window. + s.record(1001, 700, T0 + TEMP_SESSION_TTL_MS); + expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS + 1)).toBe(true); + }); + + it('ignores invalid records (no group / no user) — stays receive-only', () => { + const s = new TempSessionStore(); + s.record(1001, 0, T0); // no source group + s.record(0, 700, T0); // no user + s.record(-5, -5, T0); + expect(s.has(1001, 0, T0)).toBe(false); + expect(s.has(0, 700, T0)).toBe(false); + }); + + it('sweep drops expired entries', () => { + const s = new TempSessionStore(); + s.record(1001, 700, T0); + s.record(1002, 700, T0 + TEMP_SESSION_TTL_MS); // expires later + s.sweep(T0 + TEMP_SESSION_TTL_MS + 1); + expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS + 1)).toBe(false); + expect(s.has(1002, 700, T0 + TEMP_SESSION_TTL_MS + 1)).toBe(true); + }); +}); diff --git a/packages/onebot/tests/ws-client-stale-close.test.ts b/packages/onebot/tests/ws-client-stale-close.test.ts index 49407ca2..2ed4d79d 100644 --- a/packages/onebot/tests/ws-client-stale-close.test.ts +++ b/packages/onebot/tests/ws-client-stale-close.test.ts @@ -29,6 +29,7 @@ const { FakeWebSocket, instances } = vi.hoisted(() => { constructor(url: string, _opts: unknown) { super(); + if (url.includes('throw-sync')) throw new Error('invalid websocket url'); this.url = url; instances.push(this); } @@ -91,6 +92,40 @@ describe('WsClientAdapter — stale-socket close guard (issue #97)', () => { instances.length = 0; }); + it('rolls back enabled state when socket construction throws synchronously', () => { + const adapter = new WsClientAdapter('ws', cfg({ url: 'ws://throw-sync/' }), ctx()); + + expect(() => adapter.open()).toThrow('invalid websocket url'); + expect(adapter.isActive).toBe(false); + expect(adapter.describeManagedStatus()).toMatchObject({ + status: 'degraded', + lastError: 'invalid websocket url', + }); + }); + + it('closes the socket but waits for an in-flight inbound action to drain', async () => { + let finishAction!: () => void; + const actionGate = new Promise((resolve) => { finishAction = resolve; }); + const gatedCtx: NetworkAdapterContext = { + ...ctx(), + api: { processStreamRequest: vi.fn(() => actionGate) } as never, + }; + const adapter = new WsClientAdapter('ws', cfg(), gatedCtx); + adapter.open(); + const socket = instances[0]; + socket.emit('message', Buffer.from('{"action":"get_status"}')); + + let closed = false; + const closing = adapter.close().then(() => { closed = true; }); + await Promise.resolve(); + expect(socket.readyState).toBe(2); + expect(closed).toBe(false); + + finishAction(); + await closing; + expect(closed).toBe(true); + }); + it('ignores the close event from a socket replaced by a hot reload', async () => { vi.useFakeTimers(); try { diff --git a/packages/onebot/tests/ws-server-lifecycle.test.ts b/packages/onebot/tests/ws-server-lifecycle.test.ts new file mode 100644 index 00000000..bc858282 --- /dev/null +++ b/packages/onebot/tests/ws-server-lifecycle.test.ts @@ -0,0 +1,154 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +const { FakeWebSocketServer, servers } = vi.hoisted(() => { + // eslint-disable-next-line @typescript-eslint/no-require-imports + const { EventEmitter } = require('node:events') as typeof import('node:events'); + const servers: FakeWebSocketServer[] = []; + + class FakeWebSocketServer extends EventEmitter { + closeCallback: ((error?: Error) => void) | null = null; + constructor(_options: unknown) { + super(); + servers.push(this); + } + close(callback?: (error?: Error) => void): void { + this.closeCallback = callback ?? null; + } + finishClose(error?: Error): void { + this.closeCallback?.(error); + } + } + + return { FakeWebSocketServer, servers }; +}); + +vi.mock('@snowluma/websocket', () => ({ + WebSocket: class {}, + WebSocketServer: FakeWebSocketServer, +})); + +import { WsServerAdapter } from '../src/network/ws-server-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { WsServerNetwork } from '../src/types'; + +let apiAccepting = true; +const CTX: NetworkAdapterContext = { + uin: '10001', + api: { + get isAcceptingActions() { return apiAccepting; }, + } as never, + buildLifecycleEvent: () => ({}), + buildHeartbeatEvent: () => ({}), +}; + +function config(): WsServerNetwork { + return { + name: 'ws', + host: '127.0.0.1', + port: 8080, + path: '/', + role: 'Universal', + messageFormat: 'array', + reportSelfMessage: false, + }; +} + +describe('WsServerAdapter bind/release lifecycle promises', () => { + beforeEach(() => { + servers.length = 0; + apiAccepting = true; + }); + + it('does not resolve open before the listening event', async () => { + const adapter = new WsServerAdapter('ws', config(), CTX); + let resolved = false; + const opening = adapter.open().then(() => { resolved = true; }); + await Promise.resolve(); + expect(resolved).toBe(false); + expect(adapter.describeStatus().status).toBe('disabled'); + + servers[0].emit('listening'); + await opening; + expect(resolved).toBe(true); + expect(adapter.describeStatus().status).toBe('ok'); + }); + + it('rejects bind errors and exposes them as degraded', async () => { + const adapter = new WsServerAdapter('ws', config(), CTX); + const opening = adapter.open(); + servers[0].emit('error', Object.assign(new Error('address in use'), { code: 'EADDRINUSE' })); + + await expect(opening).rejects.toMatchObject({ code: 'EADDRINUSE' }); + expect(adapter.describeManagedStatus()).toMatchObject({ + status: 'degraded', + lastError: 'address in use', + }); + }); + + it('does not resolve close before the server release callback', async () => { + const adapter = new WsServerAdapter('ws', config(), CTX); + const opening = adapter.open(); + servers[0].emit('listening'); + await opening; + + let resolved = false; + const closing = adapter.close().then(() => { resolved = true; }); + await Promise.resolve(); + expect(resolved).toBe(false); + + servers[0].finishClose(); + await closing; + expect(resolved).toBe(true); + expect(adapter.describeStatus().status).toBe('disabled'); + }); + + it('retains server ownership after close callback failure and retries it', async () => { + const adapter = new WsServerAdapter('ws', config(), CTX); + const opening = adapter.open(); + servers[0].emit('listening'); + await opening; + + const firstClose = adapter.close(); + servers[0].finishClose(new Error('release failed')); + await expect(firstClose).rejects.toThrow('release failed'); + expect((adapter as unknown as { wss: unknown }).wss).toBe(servers[0]); + expect(adapter.describeStatus().status).toBe('ok'); + + // The ambiguous transport failure restores its local live-state, but a + // final instance shutdown has a sticky ApiHandler gate and must not admit + // a new Action through the retiring generation. + expect((adapter as unknown as { acceptingActions: boolean }).acceptingActions).toBe(true); + apiAccepting = false; + const startAction = vi.fn(async () => {}); + (adapter as unknown as { trackInboundAction(start: () => Promise): void }) + .trackInboundAction(startAction); + expect(startAction).not.toHaveBeenCalled(); + + const secondClose = adapter.close(); + servers[0].finishClose(); + await secondClose; + expect((adapter as unknown as { wss: unknown }).wss).toBeNull(); + expect(adapter.describeStatus().status).toBe('disabled'); + }); + + it('releases the listener but waits for an in-flight inbound action to drain', async () => { + const adapter = new WsServerAdapter('ws', config(), CTX); + const opening = adapter.open(); + servers[0].emit('listening'); + await opening; + let finishAction!: () => void; + const actionGate = new Promise((resolve) => { finishAction = resolve; }); + (adapter as unknown as { trackInboundAction(start: () => Promise): void }) + .trackInboundAction(() => actionGate); + + let closed = false; + const closing = adapter.close().then(() => { closed = true; }); + servers[0].finishClose(); + await Promise.resolve(); + expect(closed).toBe(false); + + finishAction(); + await closing; + expect(closed).toBe(true); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 7de9613a..22fbcd28 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.12.0", + "version": "1.12.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/proto-defs/src/action.ts b/packages/proto-defs/src/action.ts index fbd94d9e..4142412e 100644 --- a/packages/proto-defs/src/action.ts +++ b/packages/proto-defs/src/action.ts @@ -21,9 +21,17 @@ export interface RoutingTrans0x211 { uid?: pb<8, string>; } +// Group temp-session routing head — RoutingHead field 3. Inner shape +// { 群号 (source group), 对端 uid }. +export interface RoutingGrpTmp { + groupUin?: pb<3, uint_64>; + toUid?: pb<4, string>; +} + export interface RoutingHead { c2c?: pb<1, RoutingC2C>; grp?: pb<2, RoutingGroup>; + grpTmp?: pb<3, RoutingGrpTmp>; trans0x211?: pb<15, RoutingTrans0x211>; } diff --git a/packages/proto-defs/src/message.ts b/packages/proto-defs/src/message.ts index 73f2d75b..a540ee4d 100644 --- a/packages/proto-defs/src/message.ts +++ b/packages/proto-defs/src/message.ts @@ -18,8 +18,12 @@ export interface ResponseGrp { groupName?: pb<7, string>; } +// ResponseHead field 7 is multi-purpose: a forward message carries +// `friendName` (field 6); a group temp-session push carries the source group +// (field 4). Subfields don't collide, so one interface covers both. export interface ResponseForward { - friendName?: pb<6, string>; + tempGroupUin?: pb<4, uint_32>; + friendName?: pb<6, string>; } // ResponseHead diff --git a/packages/protocol/package.json b/packages/protocol/package.json index 3411423b..37abf2d1 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.12.0", + "version": "1.12.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/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index 2b28ffb7..3e78bb9f 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -9,6 +9,10 @@ import { deflateSync } from 'zlib'; import type { BridgeContext } from './bridge-context'; import { sysFaceStore } from './sys-face-store'; import type { MessageElement } from './events'; +import { + assertValidMessageElements, + MessageElementValidationError, +} from './element-manifest'; import { uploadImageMsgInfo } from './highway/image-upload'; import { hexToBytes } from './highway/pipeline'; import { uploadPttMsgInfo } from './highway/ptt-upload'; @@ -435,6 +439,27 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise * Image, record and video elements trigger NTV2 highway upload via the SendContext. */ export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise { + // Validate the whole message before the first upload or packet build. This + // preserves all-or-nothing semantics: a malformed later segment cannot make + // an earlier media segment perform side effects before the send is rejected. + assertValidMessageElements(elements, 'W'); + for (const element of elements) { + if ((element.type === 'image' || element.type === 'record' || element.type === 'video') && !ctx) { + throw new MessageElementValidationError( + 'MISSING_FIELD', + `message element "${element.type}" requires SendContext`, + element.type, + ); + } + if (element.type === 'file' && !ctx?.forwardFake) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'message element "file" must use the group/private file upload pipeline', + element.type, + ); + } + } + const result: ProtoElem[] = []; // A user-supplied @ that lands immediately after a reply's srcMsg isn't // honored by the QQ NT group server (the @ shows but never notifies, #129). @@ -446,15 +471,15 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte for (const elem of elements) { switch (elem.type) { case 'text': - if (elem.text) result.push(makeTextElem(elem.text)); + result.push(makeTextElem(elem.text)); break; case 'face': - if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId, ctx)); + result.push(makeFaceElem(elem.faceId, ctx)); break; case 'mface': - if (elem.emojiId) result.push(makeMarketFaceElem(elem)); + result.push(makeMarketFaceElem(elem)); break; case 'at': @@ -462,53 +487,39 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'reply': - if (elem.replySeq) { - result.push(makeReplyElem(elem)); - if (hasUserAt && ctx?.groupId !== undefined && elem.replySenderUin) { - const replyMention = await makeReplyMentionElem(ctx, elem.replySenderUin); - if (replyMention) result.push(replyMention); - } + result.push(makeReplyElem(elem)); + if (hasUserAt && ctx?.groupId !== undefined && elem.replySenderUin) { + const replyMention = await makeReplyMentionElem(ctx, elem.replySenderUin); + if (replyMention) result.push(replyMention); } break; case 'json': - if (elem.text) result.push(makeJsonElem(elem)); + result.push(makeJsonElem(elem)); break; case 'xml': - if (elem.text) result.push(makeXmlElem(elem)); + result.push(makeXmlElem(elem)); break; case 'markdown': - if (elem.text) result.push(makeMarkdownElem(elem)); + result.push(makeMarkdownElem(elem)); break; case 'image': - if (ctx) { - result.push(await makeImageElem(ctx, elem)); - } else { - console.warn('[ElemBuilder] image send requires SendContext'); - } + result.push(await makeImageElem(ctx!, elem)); break; case 'forward': - if (elem.resId) result.push(makeForwardElem(elem)); + result.push(makeForwardElem(elem)); break; case 'record': - if (ctx) { - result.push(await makePttElem(ctx, elem)); - } else { - console.warn('[ElemBuilder] record send requires SendContext'); - } + result.push(await makePttElem(ctx!, elem)); break; case 'video': - if (ctx) { - result.push(await makeVideoElem(ctx, elem)); - } else { - console.warn('[ElemBuilder] video send requires SendContext'); - } + result.push(await makeVideoElem(ctx!, elem)); break; case 'file': @@ -523,8 +534,8 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte // * group: split → `bridge.sendGroupFileMessage` // (OIDB 0x6d9_4 publish). // The QQ-NT server REJECTS outgoing PbSendMsg with a - // transElem(24) (result=79), so an element reaching here - // in live-send mode is a routing bug — drop with a warn. + // transElem(24) (result=79), so the all-message preflight above + // raises a typed validation error when a live file reaches here. // // 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`. // The long-msg service stores the gzipped protobuf verbatim @@ -536,20 +547,21 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte // the file segment off and writes msgContent // separately (because RichText.notOnlineFile + // FileExtra both live outside elems[]). - if (ctx && ctx.forwardFake) { - if (ctx.groupId !== undefined) { - result.push(makeGroupFileElem(elem, ctx)); - } - // c2c forwardFake intentionally falls through — handled by - // the forward-builder at the msgContent level. - } else { - console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)'); + if (!ctx?.forwardFake) { + throw new Error('element-builder file routing invariant failed after preflight'); } + if (ctx.groupId !== undefined) { + result.push(makeGroupFileElem(elem, ctx)); + } + // c2c forwardFake intentionally emits no Elem — handled by the + // forward-builder at the msgContent level. break; default: - console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`); - break; + // assertValidMessageElements above rejects every non-W type before any + // side effect. Reaching this branch means the manifest and dispatcher + // drifted despite their reconciliation test. + throw new Error(`element-builder dispatch invariant failed: ${elem.type}`); } } diff --git a/packages/protocol/src/element-manifest.ts b/packages/protocol/src/element-manifest.ts index 07521f1d..8a235b3a 100644 --- a/packages/protocol/src/element-manifest.ts +++ b/packages/protocol/src/element-manifest.ts @@ -26,100 +26,452 @@ * 'by-design-no' 该方向按设计不支持(QQ 协议限制),缺席是正确的。 */ +import type { + MessageElement, + MessageElementOf, + MessageElementType, +} from './events'; + 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 { +type ElementField = Exclude, 'type'> & string; + +export interface ElementSpec { /** 每个方向的支持状态。 */ readonly directions: Readonly>; /** - * 该元素类型在 `MessageElement` 上「属于自己」的字段 —— 字段契约的文档基准, - * 供各方向读写时对齐(例如 poke 统一用 `subType`,不再收侧 `subType` / 发侧 - * `faceId` 打架)。当前为文档性声明,字段级强制留待后续阶段。 + * 该元素类型允许的全部字段。`fieldsFor` 在编译期要求它与判别联合完全一致, + * `validateMessageElement` 在运行时据此拒绝越界字段。 */ - readonly fields: readonly string[]; + readonly fields: readonly ElementField[]; + /** 运行时必须存在(不能为 undefined/null)的字段。 */ + readonly requiredFields: readonly ElementField[]; /** 备注:媒体上传、三角映射、协议限制等需要跨方向知道的事。 */ readonly note?: string; } +type ManifestShape = { readonly [T in MessageElementType]: ElementSpec }; + +/** + * Compile-time exact-field guard: an unknown field is rejected by the tuple's + * element type; omitting a legal field makes the synthetic __missingFields + * property unsatisfied. The returned tuple remains available at runtime. + */ +function fieldsFor() { + return []>( + fields: F & (Exclude, F[number]> extends never + ? unknown + : { readonly __missingFields: Exclude, F[number]> }), + ): F => fields; +} + /** * 全部规范元素类型 × 四向支持。此表须与那 4 处派发代码逐字一致,否则对账测试报红。 */ export const ELEMENT_MANIFEST = { text: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['text'], + fields: fieldsFor<'text'>()(['text']), + requiredFields: ['text'], }, at: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['targetUin', 'uid', 'text'], + fields: fieldsFor<'at'>()(['targetUin', 'uid', 'text']), + requiredFields: ['targetUin'], }, face: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['faceId'], + fields: fieldsFor<'face'>()(['faceId']), + requiredFields: ['faceId'], }, reply: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['replySeq', 'replyMessageId', 'replySenderUin', 'replyTime', 'replyRandom', 'replyElements'], + fields: fieldsFor<'reply'>()(['replySeq', 'replyMessageId', 'replySenderUin', 'replyTime', 'replyRandom', 'replyElements']), + requiredFields: ['replySeq'], }, json: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['text'], + fields: fieldsFor<'json'>()(['text']), + requiredFields: ['text'], }, xml: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['text', 'subType'], + fields: fieldsFor<'xml'>()(['text', 'subType']), + requiredFields: ['text'], }, forward: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['resId', 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardNews', 'forwardTSum', 'forwardUuid'], + fields: fieldsFor<'forward'>()(['resId', 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardNews', 'forwardTSum', 'forwardUuid']), + requiredFields: ['resId'], }, 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'], + fields: fieldsFor<'image'>()(['imageUrl', 'fileId', 'fileName', 'fileSize', 'url', 'subType', 'summary', 'width', 'height', 'flash', 'md5Hex', 'sha1Hex', 'picFormat', 'noByteFallback']), + requiredFields: [], 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'], + fields: fieldsFor<'record'>()(['fileName', 'fileId', 'fileSize', 'fileHash', 'url', 'duration', 'md5Hex', 'sha1Hex', 'voiceFormat', 'noByteFallback', 'mediaNode']), + requiredFields: [], 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'], + fields: fieldsFor<'video'>()(['fileName', 'fileId', 'fileSize', 'fileHash', 'url', 'thumbUrl', 'duration', 'width', 'height', 'md5Hex', 'sha1Hex', 'videoFormat', 'noByteFallback', 'mediaNode']), + requiredFields: [], note: 'media', }, mface: { directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' }, - fields: ['emojiId', 'emojiPackageId', 'emojiKey', 'text', 'summary'], + fields: fieldsFor<'mface'>()(['emojiId', 'emojiPackageId', 'emojiKey', 'text']), + requiredFields: ['emojiId'], 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'], + fields: fieldsFor<'file'>()(['fileId', 'fileName', 'fileSize', 'fileHash', 'url', 'md5Hex', 'sha1Hex']), + requiredFields: [], 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 为准', + fields: fieldsFor<'poke'>()(['subType']), + requiredFields: ['subType'], + note: 'P 仅负责把 OneBot 段规范化为 subType;W 会明确拒绝,因为 QQ 不允许戳一戳作为消息元素发送。请使用独立 poke Action', }, markdown: { directions: { D: 'no', S: 'no', P: 'yes', W: 'yes' }, - fields: ['text'], + fields: fieldsFor<'markdown'>()(['text']), + requiredFields: ['text'], note: '收侧(D/S)无对应,仅发送方向存在', }, flash_file: { directions: { D: 'yes', S: 'yes', P: 'by-design-no', W: 'by-design-no' }, - fields: ['filesetId', 'sceneType', 'fileName'], + fields: fieldsFor<'flash_file'>()(['filesetId', 'sceneType', 'fileName']), + requiredFields: ['filesetId'], note: '闪传文件(#199/#200):旧客户端(≤9.9.30)的 richui markdown 卡片才有;仅收侧解码上报,发送走 send_flash_msg 动作,故 P/W 按设计不支持', }, -} as const satisfies Record; +} as const satisfies ManifestShape; export type ElementType = keyof typeof ELEMENT_MANIFEST; +export type MessageElementValidationCode = + | 'UNKNOWN_TYPE' + | 'UNSENDABLE_TYPE' + | 'MISSING_FIELD' + | 'UNEXPECTED_FIELD' + | 'INVALID_FIELD'; + +/** Stable typed error for callers that map invalid messages to BAD_REQUEST. */ +export class MessageElementValidationError extends Error { + override readonly name = 'MessageElementValidationError'; + + constructor( + readonly code: MessageElementValidationCode, + message: string, + readonly elementType?: string, + readonly field?: string, + ) { + super(message); + } +} + +export type MessageElementValidationResult = + | { readonly ok: true; readonly element: MessageElement } + | { readonly ok: false; readonly error: MessageElementValidationError }; + +const STRING_FIELDS: ReadonlySet = new Set([ + 'text', 'uid', 'imageUrl', 'fileId', 'fileName', 'fileHash', 'url', + 'thumbUrl', 'summary', 'emojiId', 'emojiKey', 'resId', 'filesetId', + 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardUuid', + 'md5Hex', 'sha1Hex', +]); +const NUMBER_FIELDS: ReadonlySet = new Set([ + 'faceId', 'targetUin', 'fileSize', 'replySeq', 'replyMessageId', + 'replySenderUin', 'replyTime', 'replyRandom', 'subType', 'duration', + 'width', 'height', 'emojiPackageId', 'sceneType', 'forwardTSum', + 'picFormat', 'videoFormat', 'voiceFormat', +]); +const BOOLEAN_FIELDS: ReadonlySet = new Set(['flash', 'noByteFallback']); + +function throwValidation( + code: MessageElementValidationCode, + message: string, + elementType?: string, + field?: string, +): never { + throw new MessageElementValidationError(code, message, elementType, field); +} + +function validateFieldValue(type: ElementType, field: string, value: unknown): void { + if (value === undefined) return; + if (STRING_FIELDS.has(field)) { + if (typeof value !== 'string') { + throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must be a string`, type, field); + } + return; + } + if (NUMBER_FIELDS.has(field)) { + if (typeof value !== 'number' || !Number.isSafeInteger(value)) { + throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must be a safe integer`, type, field); + } + return; + } + if (BOOLEAN_FIELDS.has(field)) { + if (typeof value !== 'boolean') { + throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must be a boolean`, type, field); + } + return; + } + if (field === 'replyElements') { + if (!Array.isArray(value)) { + throwValidation('INVALID_FIELD', 'message element "reply" field "replyElements" must be an array', type, field); + } + for (const quoted of value) assertValidMessageElement(quoted); + return; + } + if (field === 'forwardNews') { + if (!Array.isArray(value) || value.some((item) => ( + typeof item !== 'object' || item === null || Array.isArray(item) + || typeof (item as { text?: unknown }).text !== 'string' + || Object.keys(item).some((key) => key !== 'text') + ))) { + throwValidation('INVALID_FIELD', 'message element "forward" field "forwardNews" must contain only { text: string } entries', type, field); + } + return; + } + if (field === 'mediaNode') { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + throwValidation('INVALID_FIELD', `message element "${type}" field "mediaNode" must be an object`, type, field); + } + return; + } + // This is an invariant failure in the executable contract, not bad user + // input: adding a manifest field without a runtime validator must be loud. + throw new Error(`element manifest field has no runtime validator: ${type}.${field}`); +} + +function requireNonEmptyString(element: Record, type: ElementType, field: string): void { + const value = element[field]; + if (typeof value !== 'string' || value.length === 0) { + throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must not be empty`, type, field); + } +} + +function validateSemantics( + element: MessageElement, + direction: ElementDirection | undefined, +): void { + const nonNegativeFields = [ + 'targetUin', 'faceId', 'fileSize', 'replySeq', + 'replySenderUin', 'replyTime', 'subType', 'duration', 'width', 'height', + 'emojiPackageId', 'sceneType', 'forwardTSum', 'picFormat', 'videoFormat', + 'voiceFormat', + ] as const; + const record = element as unknown as Record; + for (const field of nonNegativeFields) { + const value = record[field]; + if (typeof value === 'number' && value < 0) { + throwValidation( + 'INVALID_FIELD', + `message element "${element.type}" field "${field}" must be non-negative`, + element.type, + field, + ); + } + } + if (element.md5Hex !== undefined && !/^[0-9a-fA-F]{32}$/.test(element.md5Hex)) { + throwValidation( + 'INVALID_FIELD', + `message element "${element.type}" field "md5Hex" must be exactly 32 hexadecimal characters`, + element.type, + 'md5Hex', + ); + } + if (element.sha1Hex !== undefined && !/^[0-9a-fA-F]{40}$/.test(element.sha1Hex)) { + throwValidation( + 'INVALID_FIELD', + `message element "${element.type}" field "sha1Hex" must be exactly 40 hexadecimal characters`, + element.type, + 'sha1Hex', + ); + } + + switch (element.type) { + case 'text': + case 'xml': + case 'markdown': + requireNonEmptyString(element as unknown as Record, element.type, 'text'); + return; + case 'json': { + requireNonEmptyString(element as unknown as Record, element.type, 'text'); + if (direction !== 'P' && direction !== 'W') return; + try { + const parsed = JSON.parse(element.text) as unknown; + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('not an object'); + } catch { + throwValidation( + 'INVALID_FIELD', + 'message element "json" field "text" must contain a JSON object', + element.type, + 'text', + ); + } + return; + } + case 'at': + if (!Number.isInteger(element.targetUin) || element.targetUin < 0) { + throwValidation('INVALID_FIELD', 'message element "at" field "targetUin" must be a non-negative integer', element.type, 'targetUin'); + } + return; + case 'face': + if (!Number.isInteger(element.faceId) || element.faceId < 0) { + throwValidation('INVALID_FIELD', 'message element "face" field "faceId" must be a non-negative integer', element.type, 'faceId'); + } + return; + case 'reply': + if (!Number.isInteger(element.replySeq) || element.replySeq <= 0) { + throwValidation('INVALID_FIELD', 'message element "reply" field "replySeq" must be a positive integer', element.type, 'replySeq'); + } + return; + case 'mface': + if (!/^[0-9a-fA-F]{32}$/.test(element.emojiId)) { + throwValidation( + 'INVALID_FIELD', + 'message element "mface" field "emojiId" must be exactly 32 hexadecimal characters', + element.type, + 'emojiId', + ); + } + return; + case 'forward': + requireNonEmptyString(element as unknown as Record, element.type, 'resId'); + return; + case 'image': { + if (direction !== 'P' && direction !== 'W') return; + if (element.noByteFallback === true && (!element.md5Hex?.trim() || !element.sha1Hex?.trim())) { + throwValidation( + 'MISSING_FIELD', + `message element "${element.type}" with noByteFallback requires md5Hex + sha1Hex`, + element.type, + 'md5Hex', + ); + } + const hasSource = Boolean(element.url?.trim() || element.imageUrl?.trim() || element.fileId?.trim()); + const hasFingerprint = element.noByteFallback === true + && Boolean(element.md5Hex?.trim() && element.sha1Hex?.trim()); + if (!hasSource && !hasFingerprint) { + throwValidation( + 'MISSING_FIELD', + `message element "${element.type}" requires a file/url source or a complete fast-upload fingerprint`, + element.type, + 'url', + ); + } + return; + } + case 'record': + case 'video': { + if (direction !== 'P' && direction !== 'W') return; + if (element.noByteFallback === true && (!element.md5Hex?.trim() || !element.sha1Hex?.trim())) { + throwValidation( + 'MISSING_FIELD', + `message element "${element.type}" with noByteFallback requires md5Hex + sha1Hex`, + element.type, + 'md5Hex', + ); + } + const hasSource = Boolean(element.url?.trim() || element.fileId?.trim()); + const hasFingerprint = element.noByteFallback === true + && Boolean(element.md5Hex?.trim() && element.sha1Hex?.trim()); + if (!hasSource && !hasFingerprint) { + throwValidation( + 'MISSING_FIELD', + `message element "${element.type}" requires a file/url source or a complete fast-upload fingerprint`, + element.type, + 'url', + ); + } + return; + } + case 'file': + if ((direction === 'P' || direction === 'W') && !element.url?.trim() && !element.fileId?.trim()) { + throwValidation('MISSING_FIELD', 'message element "file" requires file_id or file/url', element.type, 'fileId'); + } + return; + case 'poke': + case 'flash_file': + return; + } +} + +/** + * Validate a runtime value against the same field table checked by TypeScript. + * P/W additionally enforce sendability and source requirements. + */ +export function assertValidMessageElement( + value: unknown, + direction?: ElementDirection, +): asserts value is MessageElement { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + throwValidation('INVALID_FIELD', 'message element must be an object'); + } + const element = value as Record; + const rawType = element.type; + if (typeof rawType !== 'string' || !Object.hasOwn(ELEMENT_MANIFEST, rawType)) { + throwValidation('UNKNOWN_TYPE', `unknown message element type: ${String(rawType)}`, String(rawType)); + } + const type = rawType as ElementType; + const spec = ELEMENT_MANIFEST[type]; + + if (direction && spec.directions[direction] !== 'yes') { + const hint = type === 'poke' + ? 'use the dedicated poke Action instead' + : type === 'flash_file' + ? 'use the send_flash_msg Action instead' + : `direction ${direction} is not supported`; + throwValidation('UNSENDABLE_TYPE', `message element "${type}" cannot be sent; ${hint}`, type); + } + + const allowed = new Set(['type', ...spec.fields]); + for (const key of Object.keys(element)) { + if (!allowed.has(key)) { + throwValidation('UNEXPECTED_FIELD', `message element "${type}" does not allow field "${key}"`, type, key); + } + } + for (const field of spec.requiredFields) { + if (element[field] === undefined || element[field] === null) { + throwValidation('MISSING_FIELD', `message element "${type}" requires field "${field}"`, type, field); + } + } + for (const field of spec.fields) validateFieldValue(type, field, element[field]); + validateSemantics(element as unknown as MessageElement, direction); +} + +export function validateMessageElement( + value: unknown, + direction?: ElementDirection, +): MessageElementValidationResult { + try { + assertValidMessageElement(value, direction); + return { ok: true, element: value }; + } catch (error) { + if (error instanceof MessageElementValidationError) return { ok: false, error }; + throw error; + } +} + +export function assertValidMessageElements( + values: readonly unknown[], + direction?: ElementDirection, +): asserts values is readonly MessageElement[] { + for (const value of values) assertValidMessageElement(value, direction); +} + /** * 某方向应被处理的元素类型集合(`directions[dir] === 'yes'`)—— 对账测试的基准。 */ @@ -132,10 +484,10 @@ export function typesForDirection(dir: ElementDirection): Set { } /** - * 发·解(P)侧还接收一批「纯 OneBot 输入糖」:它们不是某种真实消息元素,只是被 - * 塌缩成 json / face / poke 的输入便利(如骰子、猜拳、位置/音乐/名片分享、转发 - * node、匿名标记),没有收侧对应,也没有专属的 wire 形态,故不进本清单。对账 P - * 时须先从代码里剔除这些类型。 + * 发·解(P)侧还识别一批「纯 OneBot 输入词」:可执行的会塌缩成 json / face, + * node 仅允许在 forward node list 的专用解析器中使用,shake / anonymous 因没有 + * 合法消息元素语义而返回 typed validation error。它们没有收侧对应,也没有专属 + * wire 形态,故不进本清单;对账 P 时须先从代码里剔除这些类型。 */ export const INPUT_SUGAR_SEGMENTS: ReadonlySet = new Set([ 'node', 'share', 'music', 'location', 'contact', 'rps', 'dice', 'shake', 'anonymous', diff --git a/packages/protocol/src/events.ts b/packages/protocol/src/events.ts index dade5237..acc02003 100644 --- a/packages/protocol/src/events.ts +++ b/packages/protocol/src/events.ts @@ -1,95 +1,199 @@ -export interface MessageElement { - type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward' - text?: string; - faceId?: number; - targetUin?: number; - uid?: string; - imageUrl?: string; - fileId?: string; - thumbFileId?: string; - fileName?: string; - fileSize?: number; - replySeq?: number; - replyMessageId?: number; // For reply: original message ID (for logging) - replySenderUin?: number; // For reply: original sender's UIN - replyTime?: number; // For reply: original message timestamp - replyRandom?: number; // For reply: original message random/msgId - replyElements?: MessageElement[]; // Decoded elements of the quoted message (SrcMsg.elems) — lets a backfill reconstruct it for get_msg without a server round-trip - url?: string; - thumbUrl?: string; +/** Re-upload metadata carried by received record/video elements. */ +export interface MediaNode { + fileUuid?: string; + storeId?: number; + uploadTime?: number; + ttl?: number; subType?: number; - duration?: number; - width?: number; - height?: number; - summary?: string; - // Market face (商城表情). Decoded from the wire `marketFace` element; the - // OneBot layer surfaces it as an `image` segment carrying these as markers, - // and the send path rebuilds the wire `marketFace` from them. - // emojiId = hex(MarketFace.faceId) → also builds the gxh gif URL - // emojiPackageId = MarketFace.tabId - // emojiKey = MarketFace.key - emojiId?: string; - emojiPackageId?: number; - emojiKey?: string; - flash?: boolean; - resId?: string; - fileHash?: string; - // 闪传文件 (flash transfer) — decoded from an older-client richui markdown - // commonElem (svc=45, busId=FlashTransfer). #199/#200. title reuses fileName. - filesetId?: string; - sceneType?: number; - // Preview-bubble metadata for the `forward` element. Drives the - // `com.tencent.multimsg` LightApp JSON the recipient renders before - // they tap to expand. When unset, the element builder falls back to - // generic defaults so old call sites keep working. + info?: { + fileSize?: number; + fileHash?: string; + fileSha1?: string; + fileName?: string; + width?: number; + height?: number; + time?: number; + original?: number; + type?: { + type?: number; + picFormat?: number; + videoFormat?: number; + voiceFormat?: number; + }; + }; +} + +export interface TextElement { + type: 'text'; + text: string; +} + +export interface AtElement { + type: 'at'; + /** 0 denotes @all. */ + targetUin: number; + uid?: string; + text?: string; +} + +export interface FaceElement { + type: 'face'; + faceId: number; +} + +export interface ReplyElement { + type: 'reply'; + replySeq: number; + replyMessageId?: number; + replySenderUin?: number; + replyTime?: number; + replyRandom?: number; + /** Decoded quoted elements, used to backfill get_msg locally. */ + replyElements?: MessageElement[]; +} + +export interface JsonElement { + type: 'json'; + text: string; +} + +export interface XmlElement { + type: 'xml'; + text: string; + subType?: number; +} + +export interface MarkdownElement { + type: 'markdown'; + text: string; +} + +export interface ForwardElement { + type: 'forward'; + resId: string; forwardSource?: string; forwardSummary?: string; forwardPrompt?: string; forwardNews?: Array<{ text: string }>; forwardTSum?: number; - /** `uniseq` baked into the preview's LightApp JSON. For a nested - * forward, the *outer* upload uses this same uuid as the - * `actionCommand` for the piggyback entry carrying the inner - * layer's msgBody — so receivers (Mobile QQ / QQ-NT clients) can - * resolve the inner layer from the outer's single fetch instead of - * hitting the server again. Defaults to a fresh UUID on send when - * omitted (i.e. for non-nested forwards). */ + /** Links a nested preview to its piggybacked actionCommand. */ forwardUuid?: string; - // Server-side fingerprints carried from receive side so a forward can do a - // pure md5/sha1 fast-upload without re-downloading the original bytes. - // Set together with `noByteFallback: true` to make the upload modules throw - // instead of falling back to fetch(url). +} + +interface FingerprintFields { md5Hex?: string; sha1Hex?: string; - picFormat?: number; - videoFormat?: number; - voiceFormat?: number; + /** Disallow falling back to source bytes when a fast upload misses. */ noByteFallback?: boolean; - mediaNode?: { - fileUuid?: string; - storeId?: number; - uploadTime?: number; - ttl?: number; - subType?: number; - info?: { - fileSize?: number; - fileHash?: string; - fileSha1?: string; - fileName?: string; - width?: number; - height?: number; - time?: number; - original?: number; - type?: { - type?: number; - picFormat?: number; - videoFormat?: number; - voiceFormat?: number; - }; - }; - }; } +export interface ImageElement extends FingerprintFields { + type: 'image'; + imageUrl?: string; + fileId?: string; + fileName?: string; + fileSize?: number; + url?: string; + subType?: number; + summary?: string; + width?: number; + height?: number; + flash?: boolean; + picFormat?: number; +} + +export interface RecordElement extends FingerprintFields { + type: 'record'; + fileName?: string; + fileId?: string; + fileSize?: number; + fileHash?: string; + url?: string; + duration?: number; + voiceFormat?: number; + mediaNode?: MediaNode; +} + +export interface VideoElement extends FingerprintFields { + type: 'video'; + fileName?: string; + fileId?: string; + fileSize?: number; + fileHash?: string; + url?: string; + thumbUrl?: string; + duration?: number; + width?: number; + height?: number; + videoFormat?: number; + mediaNode?: MediaNode; +} + +/** Market face (商城表情); emojiId is the hex wire face GUID. */ +export interface MarketFaceElement { + type: 'mface'; + emojiId: string; + emojiPackageId?: number; + emojiKey?: string; + text?: string; +} + +export interface FileElement { + type: 'file'; + fileId?: string; + fileName?: string; + fileSize?: number; + fileHash?: string; + url?: string; + md5Hex?: string; + sha1Hex?: string; +} + +/** Receive-side representation only; sending uses the dedicated poke Action. */ +export interface PokeElement { + type: 'poke'; + subType: number; +} + +/** Receive-side flash-transfer card; sending uses send_flash_msg. */ +export interface FlashFileElement { + type: 'flash_file'; + filesetId: string; + sceneType?: number; + fileName?: string; +} + +type MessageElementVariant = + | TextElement + | AtElement + | FaceElement + | ReplyElement + | JsonElement + | XmlElement + | MarkdownElement + | ForwardElement + | ImageElement + | RecordElement + | VideoElement + | MarketFaceElement + | FileElement + | PokeElement + | FlashFileElement; + +type UnionKeys = T extends T ? keyof T : never; +type StrictUnionMember = T extends T + ? T & Partial, keyof T>, never>> + : never; + +/** + * Closed message-element vocabulary. The optional-never fields make excess + * fields fail at compile time even when assigning an object to the union + * directly (for example, `{ type: 'poke', faceId: 1 }` is illegal). + */ +export type MessageElement = StrictUnionMember; +export type MessageElementType = MessageElementVariant['type']; +export type MessageElementOf = Extract; + export interface ForwardNodePayload { userUin: number; nickname: string; @@ -133,6 +237,10 @@ export interface FriendMessage extends QQEvent { export interface GroupMessage extends QQEvent { kind: 'group_message'; groupId: number; + /** Group display name. From the message's own wire field (ResponseGrp + * field 7 — accurate even right after a rename), falling back to the + * identity group cache, else '' when neither is available. */ + groupName: string; senderUin: number; senderNick: string; senderCard: string; @@ -145,6 +253,7 @@ export interface GroupMessage extends QQEvent { export interface TempMessage extends QQEvent { kind: 'temp_message'; senderUin: number; + /** Source group of the temp session (from responseHead.forward), or 0. */ groupId: number; senderNick: string; msgSeq: number; diff --git a/packages/protocol/src/highway/highway-client.ts b/packages/protocol/src/highway/highway-client.ts index d5d38b3f..422c52e5 100644 --- a/packages/protocol/src/highway/highway-client.ts +++ b/packages/protocol/src/highway/highway-client.ts @@ -28,6 +28,14 @@ const HIGHWAY_BLOCK_SIZE = 1024 * 1024; const HIGHWAY_MAX_CHUNK_ATTEMPTS = 3; const HIGHWAY_RETRY_BASE_MS = 300; +// Idle read timeout for a highway response. tcpConnect() clears the socket's +// own timeout once connected, so a peer that accepts the connection but then +// neither responds nor FINs would hang the whole upload forever. The single +// persistent connection (issue #211) keeps a socket alive across the whole +// file, widening that exposure, so the response reader arms its own idle timer +// and treats a stall as a retryable transport failure. +const HIGHWAY_READ_IDLE_MS = 30000; + const sleepMs = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); export const PRIVATE_IMAGE_CMD_ID = 1003; @@ -184,7 +192,18 @@ function readHttpResponseBody(socket: net.Socket): Promise { let totalNeeded = 0; let settled = false; + // Reset on every inbound chunk; fire if the peer goes silent mid-response. + let idleTimer: ReturnType | null = null; + const armIdle = () => { + if (idleTimer) clearTimeout(idleTimer); + idleTimer = setTimeout( + () => finish(() => reject(new Error('highway response read timeout (peer idle)'))), + HIGHWAY_READ_IDLE_MS, + ); + }; + const detach = () => { + if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } socket.off('data', onData); socket.off('error', onError); socket.off('close', onClose); @@ -196,6 +215,7 @@ function readHttpResponseBody(socket: net.Socket): Promise { fn(); }; const onData = (chunk: Buffer) => { + armIdle(); chunks.push(chunk); const buf = Buffer.concat(chunks); if (headerEnd < 0) { @@ -215,17 +235,30 @@ function readHttpResponseBody(socket: net.Socket): Promise { const onError = (err: Error) => finish(() => reject(err)); const onClose = () => finish(() => { const buf = Buffer.concat(chunks); - if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd))); - // QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定: - // 第一次 POST 拿到响应后服务器经常立刻 FIN 关闭,下一次写入的请求体 - // 走到一个已被对端 close 的 socket 上,触发这里。诊断信息把已收到的 - // 字节数和是否解析到 header 一起带出来,便于区分 “连接刚握手就被关” - // 和 “响应读到一半被截断” 两种情况。 - else reject(new Error( - `connection closed before response (received=${buf.length}B, headerSeen=${headerEnd >= 0})` - )); + // A fully-received body would already have resolved in onData; reaching + // here means the peer FIN'd before the response completed. Only a + // close-delimited body (no Content-Length) is legitimately ended by the + // FIN — resolve that. A declared-but-unmet Content-Length, or a + // half-received header, is a TRUNCATED response: reject it as a + // retryable transport failure so the caller's attempt loop reconnects + // and re-sends this block, instead of resolving a partial frame that + // unpackHighwayFrame would fatally reject OUTSIDE that loop (turning a + // recoverable mid-body FIN into a failed upload). + // + // QQ 的 highway 边缘节点对单连接多 POST 的 keep-alive 支持不稳定,常在 + // 响应后立刻 FIN;诊断信息带上已收字节数、是否见到 header、需要多少, + // 便于区分 “连接刚握手就被关” 和 “响应读到一半被截断”。 + if (headerEnd >= 0 && contentLength === 0) { + resolve(new Uint8Array(buf.subarray(headerEnd))); + } else { + reject(new Error( + `connection closed before full response (received=${buf.length}B, ` + + `headerSeen=${headerEnd >= 0}${headerEnd >= 0 ? `, need=${totalNeeded}` : ''})`, + )); + } }); + armIdle(); socket.on('data', onData); socket.on('error', onError); socket.on('close', onClose); @@ -306,26 +339,39 @@ export async function uploadHighwayHttp( const pathStr = `/cgi-bin/httpconn?htcmd=0x6FF0087&uin=${bridge.identity.uin}`; const totalSize = source.size; - // 每个 chunk 一个独立的 TCP 连接。 + // Single-connection, in-order, pipelined upload (issue #211). // - // 旧实现整个文件复用同一个 socket,依赖 `Connection: keep-alive` 跑多次 - // POST。但 QQ highway 边缘节点(以及链路上的代理/NAT)经常在第一次响应 - // 之后立刻 FIN 关闭连接,导致第二个 chunk 写入一个已被对端关闭的 socket, - // `readHttpResponseBody` 立刻收到 `close` 事件并抛 `connection closed - // before response`。 + // Blocks are PUT in STRICT offset order over ONE persistent connection, + // reused across chunks via HTTP keep-alive. Two properties matter: + // - In order: QQ's highway server reassembles by offset but REJECTS a + // block that arrives after a later one (error_code=102902) — parallel or + // out-of-order PUTs do not work (proven on a real endpoint). Sequential + // send guarantees in-order arrival. + // - One warm connection: reusing the socket keeps the TCP congestion + // window open across the whole file instead of paying slow-start on a + // fresh connection for every 1 MiB block. That per-block cold start was + // the real throughput cap behind #211. // - // 现象上的体现:≤1 MB 的图片/PTT 因为只发一个 chunk,不会触发;超过 1 MB - // 的图片或视频(HIGHWAY_BLOCK_SIZE = 1 MiB)必然失败。 - // - // 改成每 chunk 一连接代价可忽略: - // - 单个 1 MB chunk 的传输时间远大于 TCP 建连开销; - // - QQ 服务端反正也不希望客户端长时间占用连接; - // - 与 NapCat / Lagrange 在大文件上传时的连接生命周期一致。 + // QQ's edge nodes (and proxies/NAT on the path) sometimes FIN between + // chunks — that is what forced the one-connection-per-chunk workaround in + // #118. We handle it adaptively: if reusing the socket fails, or the peer + // half-closed after a response, we drop it, reconnect, and re-send the SAME + // block (re-PUTting an offset is idempotent). Worst case — a server that + // closes after every response — degrades to one connection per block: no + // worse than the #118 behavior, and still strictly in order (so never + // error_code=102902). `connectCount` is logged so a real run reveals which + // regime we hit (1 connection = keep-alive honored; ~chunkCount = closed + // every time). // // `source` may buffer the whole file (BufferChunkSource) or stream it from // disk (FileChunkSource); either way one chunk is read/held at a time. We // own the source and close it exactly once in the `finally` below. let succeeded = false; + let socket: net.Socket | null = null; + let connectCount = 0; + const dropSocket = (): void => { + if (socket) { socket.destroy(); socket = null; } + }; try { let offset = 0; while (offset < totalSize) { @@ -338,39 +384,29 @@ export async function uploadHighwayHttp( ); const frame = packHighwayFrame(head, chunk); - // Retry the connect + POST for this chunk on transient transport errors - // (peer FIN before response, ECONNRESET, connect refused/timeout). Each - // attempt uses a fresh connection; re-sending the same offset range is - // idempotent on the server. + // Send this block, reusing the live connection when there is one. On any + // transport failure (peer FIN between chunks, ECONNRESET, connect + // refused/timeout) drop the socket, reconnect, and retry THIS block — + // re-sending the same offset range is idempotent on the server. let responseBody: Uint8Array | undefined; for (let attempt = 1; ; attempt++) { - let socket: net.Socket; try { - socket = await tcpConnect(session.host, session.port); - } catch (err) { - if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { - throw new Error( - `highway connect failed after ${attempt} attempts ` + - `(cmdId=${commandId} offset=${offset}/${totalSize}): ${String(err)}`, - ); + if (!socket) { + socket = await tcpConnect(session.host, session.port); + connectCount += 1; } - await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); - continue; - } - try { responseBody = await httpPostFrame(socket, session.host, pathStr, frame); break; } catch (err) { + dropSocket(); if (attempt >= HIGHWAY_MAX_CHUNK_ATTEMPTS) { throw new Error( `highway upload transport failed after ${attempt} attempts ` + `(cmdId=${commandId} chunk=${chunkSize}/${totalSize} offset=${offset}): ${String(err)}`, ); } - log.trace('chunk offset=%d attempt %d failed (%s), retrying', offset, attempt, String(err)); + log.trace('chunk offset=%d attempt %d failed (%s), reconnecting', offset, attempt, String(err)); await sleepMs(HIGHWAY_RETRY_BASE_MS * attempt); - } finally { - socket.destroy(); } } @@ -395,13 +431,26 @@ export async function uploadHighwayHttp( ` fileMd5=${fileMd5Hex.slice(0, 16)}…)`, ); } + + // If the peer half-closed after sending its response, the socket can no + // longer carry the next block — drop it now so the next iteration + // reconnects cleanly instead of writing into a dead socket. + if (socket && (socket.destroyed || socket.readableEnded || !socket.writable)) { + dropSocket(); + } + offset += chunkSize; log.trace('uploaded %d/%d bytes', offset, totalSize); } succeeded = true; + if (totalSize > 0) { + log.debug('highway upload done: %d bytes over %d connection(s) (cmdId=%d)', + totalSize, connectCount, commandId); + } } finally { // Best-effort close — never mask a primary upload error. A close failure // is only surfaced when the upload itself succeeded. + dropSocket(); try { await source.close(); } catch (closeErr) { diff --git a/packages/protocol/src/highway/image-upload.ts b/packages/protocol/src/highway/image-upload.ts index 78ff7b17..3924fc14 100644 --- a/packages/protocol/src/highway/image-upload.ts +++ b/packages/protocol/src/highway/image-upload.ts @@ -70,7 +70,7 @@ function loadImage(element: MessageElement): Promise { return Promise.resolve(imageDataFromFingerprint(element)); } return loadImageFromSource( - element.url || element.fileId || '', + element.url || element.imageUrl || element.fileId || '', element.fileName ?? '', element.subType ?? 0, element.summary ?? '', diff --git a/packages/protocol/src/identity-service.ts b/packages/protocol/src/identity-service.ts index 244b5d91..fec2b25e 100644 --- a/packages/protocol/src/identity-service.ts +++ b/packages/protocol/src/identity-service.ts @@ -12,6 +12,30 @@ import type { const moduleLogger = createLogger('Identity'); +const PERSISTENCE_QUEUE_CAPACITY = 256; +const PERSISTENCE_RETRY_DELAYS_MS = [100, 500, 2_000, 10_000, 30_000] as const; + +export type IdentityPersistenceState = 'memory-only' | 'healthy' | 'degraded' | 'closed'; + +export interface IdentityPersistenceStatus { + state: IdentityPersistenceState; + suspended: boolean; + pendingWrites: number; + queueCapacity: number; + lastFailedLabel: string; + lastError: string; + lastFailureAt: number | null; + retryAttempt: number; + nextRetryAt: number | null; + abandonedWrites: number; + skippedWrites: number; +} + +interface PendingIdentityWrite { + label: string; + write: () => void; +} + /** * Hooks Identity uses when its read methods miss every cache layer. Wired in * after construction (Bridge owns these methods, but Bridge can't exist @@ -91,9 +115,9 @@ interface MemberRow { * - In-memory state (this file) — O(1) for find* on the hot path. * - SQLite (optional, opened by openForUin) — survives restarts. * - * Both layers are kept in sync by the remember* / refresh paths. - * Callers should never reach below the public surface; the cascade and - * storage details are intentionally hidden. + * Memory is authoritative for the current process. SQLite is a rebuildable, + * best-effort snapshot: failures degrade into a bounded retry queue and are + * exposed through persistenceStatus instead of rolling back observations. */ export class IdentityService { // ─── Self identity ─── @@ -126,6 +150,17 @@ export class IdentityService { private inTransaction = false; private fetcher: IdentityFetcher | null = null; private readonly log: Logger; + private readonly pendingWrites_: PendingIdentityWrite[] = []; + private retryTimer_: ReturnType | null = null; + private retryAttempt_ = 0; + private nextRetryAt_: number | null = null; + private lastFailedLabel_ = ''; + private lastError_ = ''; + private lastFailureAt_: number | null = null; + private abandonedWrites_ = 0; + private skippedWrites_ = 0; + private persistenceSuspended_ = false; + private closed_ = false; constructor(uin: string, dbPath: string | null) { this.uin_ = uin; @@ -166,13 +201,68 @@ export class IdentityService { } close(): void { - this.db?.close(); + if (this.closed_) return; + if (this.retryTimer_) { + clearTimeout(this.retryTimer_); + this.retryTimer_ = null; + this.nextRetryAt_ = null; + } + this.flushPendingWrites(false); + const pendingAtClose = this.pendingWrites_.length; + if (pendingAtClose > 0) { + this.log.warn( + 'identity persistence close with pending writes: uin=%s label=%s pending=%d retry=%d err=%s', + this.uin_, this.lastFailedLabel_, pendingAtClose, this.retryAttempt_, this.lastError_, + ); + } + + try { + this.db?.close(); + } catch (err) { + this.lastError_ = err instanceof Error ? (err.stack ?? err.message) : String(err); + this.lastFailureAt_ = Date.now(); + this.log.error( + 'identity persistence close failed: uin=%s label=%s pending=%d retry=%d err=%s', + this.uin_, this.lastFailedLabel_, this.pendingWrites_.length, this.retryAttempt_, this.lastError_, + ); + this.schedulePersistenceRetry(); + throw err; + } + + if (pendingAtClose > 0) { + this.abandonedWrites_ += pendingAtClose; + this.pendingWrites_.length = 0; + } + this.closed_ = true; + this.stmtCache_.clear(); } get persistent(): boolean { return this.db !== null; } + get persistenceStatus(): IdentityPersistenceStatus { + let state: IdentityPersistenceState; + if (this.closed_) state = 'closed'; + else if (!this.db) state = 'memory-only'; + else if (this.persistenceSuspended_ || this.pendingWrites_.length > 0) state = 'degraded'; + else state = 'healthy'; + + return { + state, + suspended: this.persistenceSuspended_, + pendingWrites: this.pendingWrites_.length, + queueCapacity: PERSISTENCE_QUEUE_CAPACITY, + lastFailedLabel: this.lastFailedLabel_, + lastError: this.lastError_, + lastFailureAt: this.lastFailureAt_, + retryAttempt: this.retryAttempt_, + nextRetryAt: this.nextRetryAt_, + abandonedWrites: this.abandonedWrites_, + skippedWrites: this.skippedWrites_, + }; + } + setFetcher(fetcher: IdentityFetcher): void { this.fetcher = fetcher; } @@ -182,12 +272,18 @@ export class IdentityService { get uin(): string { return this.uin_; } get nickname(): string { return this.nickname_; } - set nickname(v: string) { this.nickname_ = v; } + set nickname(v: string) { + this.assertOpen('nickname'); + this.nickname_ = v; + } get selfProfile(): UserProfileInfo | null { return this.selfProfile_; } get selfUid(): string | null { return this.selfProfile_?.uid ?? null; } - setSelfProfile(info: UserProfileInfo): void { this.selfProfile_ = info; } + setSelfProfile(info: UserProfileInfo): void { + this.assertOpen('self profile'); + this.selfProfile_ = { ...info }; + } // ─── Domain object reads ─── @@ -212,10 +308,15 @@ export class IdentityService { } updateGroupMember(groupId: number, member: GroupMemberInfo): void { + this.assertOpen('group member update'); const g = this.groups_.get(groupId); if (!g) return; - g.members.set(member.uin, member); - this.rememberUidUin(member.uid, member.uin); + this.assertPersistenceCapacity('group member update'); + const observed = { ...member }; + const persisted: MemberInput = { groupId, ...observed, active: true }; + g.members.set(observed.uin, observed); + this.rememberUidUin(observed.uid, observed.uin); + this.runWrite('group member update', () => this.transaction(() => this.upsertGroupMember(persisted))); } // ─── ID translation ─── @@ -268,13 +369,14 @@ export class IdentityService { LIMIT 1`, ).get(groupId, normalized) as { uin: number | null } | undefined; const uin = normalizeUin(row?.uin); - if (uin !== null) return uin; + if (uin !== null && this.isDatabaseMappingCurrent(normalized, uin)) return uin; } const row = this.pstmt( 'SELECT uin FROM users WHERE uid = ? AND uin IS NOT NULL LIMIT 1', ).get(normalized) as { uin: number | null } | undefined; - return normalizeUin(row?.uin); + const uin = normalizeUin(row?.uin); + return uin !== null && this.isDatabaseMappingCurrent(normalized, uin) ? uin : null; } findUidByUin(uin: number, groupId?: number): string | null { @@ -297,52 +399,60 @@ export class IdentityService { LIMIT 1`, ).get(groupId, normalized) as { uid: string | null } | undefined; const uid = normalizeUid(row?.uid); - if (uid) return uid; + if (uid && this.isDatabaseMappingCurrent(uid, normalized)) return uid; } const row = this.pstmt( 'SELECT uid FROM users WHERE uin = ? AND uid IS NOT NULL LIMIT 1', ).get(normalized) as { uid: string | null } | undefined; - return normalizeUid(row?.uid) || null; + const uid = normalizeUid(row?.uid); + return uid && this.isDatabaseMappingCurrent(uid, normalized) ? uid : null; } // ─── Observation (write side) ─── rememberFriends(friends: FriendInfo[]): void { - this.friends_ = friends; - for (const friend of friends) this.rememberUidUin(friend.uid, friend.uin); + this.beginObservation('friends'); + const observed = friends.map((friend) => ({ ...friend })); + const persisted = observed.map((friend): UserInput => ({ + uid: friend.uid, + uin: friend.uin, + nickname: friend.nickname, + remark: friend.remark, + isFriend: true, + source: 'friend', + })); + this.friends_ = observed; + for (const friend of observed) this.rememberUidUin(friend.uid, friend.uin); this.runWrite('friends', () => this.transaction(() => { this.pstmt('UPDATE users SET is_friend = 0, updated_at = ? WHERE is_friend = 1') .run(nowSeconds()); - for (const friend of friends) { - this.upsertUser({ - uid: friend.uid, - uin: friend.uin, - nickname: friend.nickname, - remark: friend.remark, - isFriend: true, - source: 'friend', - }); - } + for (const friend of persisted) this.upsertUser(friend); })); } rememberGroups(groups: QQGroupInfo[]): void { - this.setGroupsInMemory(groups); + this.beginObservation('groups'); + const observed = groups.map((group): QQGroupInfo => ({ + ...group, + members: new Map( + [...(group.members ?? new Map())] + .map(([uin, member]) => [uin, { ...member }] as const), + ), + })); + const persisted = observed.map((group): GroupInput => ({ + groupId: group.groupId, + groupName: group.groupName, + remark: group.remark, + memberCount: group.memberCount, + memberMax: group.memberMax, + })); + this.setGroupsInMemory(observed); this.runWrite('groups', () => this.transaction(() => { this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE active = 1') .run(nowSeconds()); - for (const group of groups) { - this.upsertGroup({ - groupId: group.groupId, - groupName: group.groupName, - remark: group.remark, - memberCount: group.memberCount, - memberMax: group.memberMax, - }); - } + for (const group of persisted) this.upsertGroup(group); })); - this.hydrateActiveMembersForGroups(groups.map((group) => group.groupId)); } /** @@ -352,6 +462,7 @@ export class IdentityService { * doesn't resurrect on the next load (the server refetch won't include it). */ forgetGroup(groupId: number): void { + this.beginObservation('forget group'); this.groups_.delete(groupId); this.runWrite('forget group', () => { this.pstmt('UPDATE groups SET active = 0, updated_at = ? WHERE group_id = ?') @@ -360,49 +471,45 @@ export class IdentityService { } rememberGroupMembers(groupId: number, members: GroupMemberInfo[]): void { - this.setGroupMembersInMemory(groupId, members); - for (const member of members) this.rememberUidUin(member.uid, member.uin); + this.beginObservation('group members'); + const observed = members.map((member) => ({ ...member })); + const persisted = observed.map((member): MemberInput => ({ + groupId, + ...member, + active: true, + })); + this.setGroupMembersInMemory(groupId, observed); + for (const member of observed) this.rememberUidUin(member.uid, member.uin); this.runWrite('group members', () => this.transaction(() => { - this.upsertGroup({ groupId, memberCount: members.length }); + this.upsertGroup({ groupId, memberCount: persisted.length }); this.pstmt('UPDATE group_members SET active = 0, updated_at = ? WHERE group_id = ?') .run(nowSeconds(), groupId); - for (const member of members) { - this.upsertGroupMember({ - groupId, - uid: member.uid, - uin: member.uin, - nickname: member.nickname, - card: member.card, - role: member.role, - level: member.level, - title: member.title, - joinTime: member.joinTime, - lastSentTime: member.lastSentTime, - shutUpTime: member.shutUpTime, - active: true, - }); - } + for (const member of persisted) this.upsertGroupMember(member); })); } rememberUserProfile(info: UserProfileInfo): void { - this.userProfiles_.set(info.uin, info); - const selfUin = parseInt(this.uin_, 10) || 0; - if (info.uin === selfUin) this.selfProfile_ = info; - this.rememberUidUin(info.uid, info.uin); - this.runWrite('user profile', () => this.transaction(() => this.upsertUser({ - uid: info.uid, - uin: info.uin, - nickname: info.nickname, - remark: info.remark, + this.beginObservation('user profile'); + const observed = { ...info }; + const persisted: UserInput = { + uid: observed.uid, + uin: observed.uin, + nickname: observed.nickname, + remark: observed.remark, source: 'profile', - }))); + }; + this.userProfiles_.set(observed.uin, observed); + const selfUin = parseInt(this.uin_, 10) || 0; + if (observed.uin === selfUin) this.selfProfile_ = { ...observed }; + this.rememberUidUin(observed.uid, observed.uin); + this.runWrite('user profile', () => this.transaction(() => this.upsertUser(persisted))); } /** Remember the approval msgseq carried by a private "qun.invite" card's * jumpUrl, keyed by group. `set_group_add_request` reads it back to approve * a bot self-invite via 0x10c8 (eventType=2). See issue #125. */ rememberGroupInviteCardSequence(groupUin: number, sequence: number): void { + this.assertOpen('group invite sequence'); if (groupUin > 0 && sequence > 0) this.groupInviteCardSeqs_.set(groupUin, sequence); } @@ -410,14 +517,24 @@ export class IdentityService { return this.groupInviteCardSeqs_.get(groupUin); } + /** Reverse lookup used for NapCat-compatible numeric request flags. */ + findGroupInviteCardGroupBySequence(sequence: number): number | undefined { + for (const [groupUin, rememberedSequence] of this.groupInviteCardSeqs_) { + if (rememberedSequence === sequence) return groupUin; + } + return undefined; + } + rememberGroupRequests(requests: GroupRequestInfo[]): void { - for (const request of requests) { + this.beginObservation('group requests'); + const observed = requests.map((request) => ({ ...request })); + for (const request of observed) { this.rememberUidUin(request.targetUid, request.targetUin); this.rememberUidUin(request.invitorUid, request.invitorUin); this.rememberUidUin(request.operatorUid, request.operatorUin); } this.runWrite('group requests', () => this.transaction(() => { - for (const request of requests) { + for (const request of observed) { this.upsertGroup({ groupId: request.groupId, groupName: request.groupName }); this.upsertUser({ uid: request.targetUid, @@ -444,14 +561,16 @@ export class IdentityService { rememberRequestIdentity( identity: { groupId?: number; uid?: string; uin?: number; nickname?: string; source?: string }, ): void { - this.rememberUidUin(identity.uid, identity.uin); + this.beginObservation('request identity'); + const observed = { ...identity }; + this.rememberUidUin(observed.uid, observed.uin); this.runWrite('request identity', () => this.transaction(() => { - if (identity.groupId !== undefined) this.upsertGroup({ groupId: identity.groupId }); + if (observed.groupId !== undefined) this.upsertGroup({ groupId: observed.groupId }); this.upsertUser({ - uid: identity.uid, - uin: identity.uin, - nickname: identity.nickname, - source: identity.source || 'request', + uid: observed.uid, + uin: observed.uin, + nickname: observed.nickname, + source: observed.source || 'request', }); })); } @@ -460,21 +579,25 @@ export class IdentityService { groupId: number, identity: { uid?: string; uin?: number; nickname?: string; card?: string }, ): void { - this.rememberUidUin(identity.uid, identity.uin); + this.beginObservation('group member identity'); + const observed = { ...identity }; + this.rememberUidUin(observed.uid, observed.uin); this.runWrite('group member identity', () => this.transaction(() => this.upsertGroupMember({ groupId, - uid: identity.uid, - uin: identity.uin, - nickname: identity.nickname, - card: identity.card, + uid: observed.uid, + uin: observed.uin, + nickname: observed.nickname, + card: observed.card, active: true, }))); } markGroupMemberInactive(groupId: number, identity: { uid?: string; uin?: number }): void { + this.beginObservation('group member inactive'); + const observed = { ...identity }; this.runWrite('group member inactive', () => { - const uid = normalizeUid(identity.uid); - const uin = normalizeUin(identity.uin); + const uid = normalizeUid(observed.uid); + const uin = normalizeUin(observed.uin); if (!uid && uin === null) return; const rows = this.findMemberRows(groupId, uid, uin); const updatedAt = nowSeconds(); @@ -504,6 +627,20 @@ export class IdentityService { this.uidByUin.set(normalizedUin, normalizedUid); } + private isDatabaseMappingCurrent(uid: string, uin: number): boolean { + const currentUin = this.uinByUid.get(uid); + const currentUid = this.uidByUin.get(uin); + const current = (currentUin === undefined || currentUin === uin) + && (currentUid === undefined || currentUid === uid); + if (!current) { + this.log.warn( + 'identity stale database mapping rejected: uin=%s candidateUid=%s candidateUin=%d currentUid=%s currentUin=%s', + this.uin_, uid, uin, currentUid ?? '', currentUin ?? '', + ); + } + return current; + } + private setGroupsInMemory(groups: QQGroupInfo[]): void { // Preserve existing member maps where possible so a roster refresh // doesn't blow away cached members for groups we already track. @@ -665,10 +802,10 @@ export class IdentityService { const merged = { uid: uid || primary?.uid || null, uin: uin ?? primary?.uin ?? null, - nickname: normalizeText(input.nickname) || primary?.nickname || '', - remark: normalizeText(input.remark) || primary?.remark || '', + nickname: mergeOptionalText(input.nickname, primary?.nickname ?? ''), + remark: mergeOptionalText(input.remark, primary?.remark ?? ''), isFriend: input.isFriend === true ? 1 : (primary?.is_friend ?? 0), - source: normalizeText(input.source) || primary?.source || '', + source: mergeOptionalText(input.source, primary?.source ?? ''), updatedAt: nowSeconds(), }; @@ -731,8 +868,8 @@ export class IdentityService { updated_at = excluded.updated_at`, ).run( input.groupId, - normalizeText(input.groupName) || existing?.group_name || '', - normalizeText(input.remark) || existing?.remark || '', + mergeOptionalText(input.groupName, existing?.group_name ?? ''), + mergeOptionalText(input.remark, existing?.remark ?? ''), normalizeNonNegative(input.memberCount, existing?.member_count ?? 0), normalizeNonNegative(input.memberMax, existing?.member_max ?? 0), nowSeconds(), @@ -759,11 +896,11 @@ export class IdentityService { const merged = { uid: uid || primary?.uid || null, uin: uin ?? primary?.uin ?? null, - nickname: normalizeText(input.nickname) || primary?.nickname || '', - card: normalizeText(input.card) || primary?.card || '', - role: normalizeText(input.role) || primary?.role || 'member', + nickname: mergeOptionalText(input.nickname, primary?.nickname ?? ''), + card: mergeOptionalText(input.card, primary?.card ?? ''), + role: mergeOptionalText(input.role, primary?.role ?? 'member'), level: normalizeNonNegative(input.level, primary?.level ?? 0), - title: normalizeText(input.title) || primary?.title || '', + title: mergeOptionalText(input.title, primary?.title ?? ''), joinTime: normalizeNonNegative(input.joinTime, primary?.join_time ?? 0), lastSentTime: normalizeNonNegative(input.lastSentTime, primary?.last_sent_time ?? 0), shutUpTime: normalizeNonNegative(input.shutUpTime, primary?.shut_up_time ?? 0), @@ -875,13 +1012,22 @@ export class IdentityService { private transaction(fn: () => T): T { if (!this.db || this.inTransaction) return fn(); this.inTransaction = true; - this.db.exec('BEGIN'); try { + this.db.exec('BEGIN'); const result = fn(); this.db.exec('COMMIT'); return result; } catch (err) { - try { this.db.exec('ROLLBACK'); } catch { /* ignore */ } + try { + this.db.exec('ROLLBACK'); + } catch (rollbackErr) { + const transactionMessage = err instanceof Error ? err.message : String(err); + const rollbackMessage = rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr); + throw new AggregateError( + [err, rollbackErr], + `identity transaction failed: ${transactionMessage}; rollback failed: ${rollbackMessage}`, + ); + } throw err; } finally { this.inTransaction = false; @@ -890,12 +1036,144 @@ export class IdentityService { private runWrite(label: string, fn: () => void): void { if (!this.db) return; + if (this.persistenceSuspended_) { + this.recordSkippedWrite(label); + return; + } + if (this.pendingWrites_.length > 0) { + this.assertPersistenceCapacity(label); + this.pendingWrites_.push({ label, write: fn }); + return; + } try { fn(); } catch (err) { - this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err)); + this.pendingWrites_.push({ label, write: fn }); + this.recordPersistenceFailure(label, err); + this.schedulePersistenceRetry(); } } + + private assertOpen(label: string): void { + if (!this.closed_) return; + throw new Error(`IdentityService is closed; cannot observe ${label}`); + } + + private beginObservation(label: string): void { + this.assertOpen(label); + this.assertPersistenceCapacity(label); + } + + private assertPersistenceCapacity(label: string): void { + if ( + !this.db + || this.persistenceSuspended_ + || this.pendingWrites_.length < PERSISTENCE_QUEUE_CAPACITY + ) return; + const message = `identity persistence retry queue full: ${this.pendingWrites_.length}/${PERSISTENCE_QUEUE_CAPACITY}`; + this.lastFailedLabel_ = label; + this.lastError_ = message; + this.lastFailureAt_ = Date.now(); + this.log.error( + 'identity persistence queue full: uin=%s label=%s pending=%d retry=%d capacity=%d', + this.uin_, label, this.pendingWrites_.length, this.retryAttempt_, PERSISTENCE_QUEUE_CAPACITY, + ); + throw new Error(message); + } + + private recordPersistenceFailure(label: string, err: unknown): void { + this.lastFailedLabel_ = label; + this.lastError_ = err instanceof Error ? (err.stack ?? err.message) : String(err); + this.lastFailureAt_ = Date.now(); + this.retryAttempt_ += 1; + this.log.error( + 'identity persistence write failed: uin=%s label=%s pending=%d retry=%d err=%s', + this.uin_, label, this.pendingWrites_.length, this.retryAttempt_, this.lastError_, + ); + } + + private schedulePersistenceRetry(): void { + if ( + this.closed_ + || this.persistenceSuspended_ + || !this.db + || this.pendingWrites_.length === 0 + || this.retryTimer_ + ) return; + if (this.retryAttempt_ > PERSISTENCE_RETRY_DELAYS_MS.length) { + this.suspendPersistence(); + return; + } + const delay = PERSISTENCE_RETRY_DELAYS_MS[ + Math.min(Math.max(this.retryAttempt_ - 1, 0), PERSISTENCE_RETRY_DELAYS_MS.length - 1) + ]; + this.nextRetryAt_ = Date.now() + delay; + this.log.warn( + 'identity persistence degraded: uin=%s label=%s pending=%d retry=%d nextRetryMs=%d', + this.uin_, this.lastFailedLabel_, this.pendingWrites_.length, this.retryAttempt_, delay, + ); + this.retryTimer_ = setTimeout(() => { + this.retryTimer_ = null; + this.nextRetryAt_ = null; + this.flushPendingWrites(); + }, delay); + this.retryTimer_.unref?.(); + } + + private flushPendingWrites(scheduleRetry = true): void { + if ( + this.closed_ + || this.persistenceSuspended_ + || !this.db + || this.pendingWrites_.length === 0 + ) return; + const pendingAtStart = this.pendingWrites_.length; + while (this.pendingWrites_.length > 0) { + const next = this.pendingWrites_[0]; + try { + next.write(); + this.pendingWrites_.shift(); + } catch (err) { + this.recordPersistenceFailure(next.label, err); + if (scheduleRetry) this.schedulePersistenceRetry(); + return; + } + } + + const attempts = this.retryAttempt_; + this.retryAttempt_ = 0; + this.nextRetryAt_ = null; + this.log.info( + 'identity persistence recovered: uin=%s flushed=%d pending=0 retries=%d', + this.uin_, pendingAtStart, attempts, + ); + } + + private suspendPersistence(): void { + if (this.persistenceSuspended_) return; + if (this.retryTimer_) { + clearTimeout(this.retryTimer_); + this.retryTimer_ = null; + } + this.nextRetryAt_ = null; + const abandoned = this.pendingWrites_.length; + this.persistenceSuspended_ = true; + this.abandonedWrites_ += abandoned; + this.log.error( + 'identity persistence suspended: uin=%s label=%s pending=%d retry=%d abandoned=%d err=%s', + this.uin_, this.lastFailedLabel_, abandoned, this.retryAttempt_, abandoned, this.lastError_, + ); + this.pendingWrites_.length = 0; + } + + private recordSkippedWrite(label: string): void { + this.skippedWrites_ += 1; + this.abandonedWrites_ += 1; + this.log.warn( + 'identity persistence write skipped: uin=%s label=%s pending=0 retry=%d skipped=%d abandoned=%d', + this.uin_, label, this.retryAttempt_, this.skippedWrites_, this.abandonedWrites_, + ); + } } function rowToMemberInfo(row: { @@ -947,6 +1225,10 @@ function normalizeText(value: unknown): string { return typeof value === 'string' ? value.trim() : ''; } +function mergeOptionalText(value: unknown, fallback: string): string { + return value === undefined ? fallback : normalizeText(value); +} + function normalizeNonNegative(value: unknown, fallback: number): number { if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value)); return fallback; diff --git a/packages/protocol/src/msg-push/decoders/group-message.ts b/packages/protocol/src/msg-push/decoders/group-message.ts index a47c2bfe..8e4f3aec 100644 --- a/packages/protocol/src/msg-push/decoders/group-message.ts +++ b/packages/protocol/src/msg-push/decoders/group-message.ts @@ -12,6 +12,7 @@ export const decodeGroupMessage: MsgPushDecoder = (ctx) => { msgId: ctx.head.msgId & 0x7FFFFFFF, elements: decodeRichBody(ctx.body, true), groupId: 0, + groupName: '', senderNick: '', senderCard: '', senderRole: '', @@ -43,5 +44,9 @@ export const decodeGroupMessage: MsgPushDecoder = (ctx) => { } else if (!ev.senderNick && grp?.memberCard) { ev.senderNick = grp.memberCard; } + // Group name: prefer the message's own wire field (ResponseGrp field 7 — + // fresh even right after a rename), fall back to the cached group list, else + // leave it empty. `ev.groupId` is set above from grp.groupUin. + ev.groupName = grp?.groupName || ctx.identity.findGroup?.(ev.groupId)?.groupName || ''; return [ev]; }; diff --git a/packages/protocol/src/msg-push/decoders/temp-message.ts b/packages/protocol/src/msg-push/decoders/temp-message.ts index a61046ed..22b75962 100644 --- a/packages/protocol/src/msg-push/decoders/temp-message.ts +++ b/packages/protocol/src/msg-push/decoders/temp-message.ts @@ -17,6 +17,10 @@ export const decodeTempMessage: MsgPushDecoder = (ctx) => { ev.groupId = ctx.responseHead.grp.groupUin ?? 0; ev.senderNick = ctx.responseHead.grp.memberName ?? ''; } + // A group temp session carries its source group in responseHead.forward. + if (ctx.responseHead?.forward?.tempGroupUin) { + ev.groupId = ctx.responseHead.forward.tempGroupUin; + } if (!ev.senderNick) { const friend = ctx.identity.findFriend(ctx.fromUin); if (friend) ev.senderNick = friend.nickname; diff --git a/packages/protocol/src/msg-push/helpers.ts b/packages/protocol/src/msg-push/helpers.ts index 200d1abe..f14df2d4 100644 --- a/packages/protocol/src/msg-push/helpers.ts +++ b/packages/protocol/src/msg-push/helpers.ts @@ -3,24 +3,62 @@ import { inflateSync } from 'zlib'; import type { IdentityService } from '../identity-service'; import type { OperatorInfo } from '@snowluma/proto-defs/notify'; +export const MAX_RICH_CARD_OUTPUT_BYTES = 4 * 1024 * 1024; +export const MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES = 8 * 1024 * 1024; + +export type DecompressDataResult = + | { ok: true; text: string; outputBytes: number } + | { ok: false; reason: string }; + export function makeImageUrl(origUrl: string): string { if (!origUrl) return ''; if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl; return 'http://gchat.qpic.cn' + origUrl; } -export function decompressData(data: Uint8Array): string { - if (!data || data.length === 0) return ''; - if (data[0] === 0x01 && data.length > 1) { +export function decompressData( + data: Uint8Array, + maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES, +): DecompressDataResult { + if (!data || data.length === 0) return { ok: false, reason: 'empty_payload' }; + if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) { + throw new Error(`invalid decompression output limit: ${maxOutputBytes}`); + } + if ((data[0] === 0x00 || data[0] === 0x01) && data.length === 1) { + return { ok: false, reason: 'marker_without_payload' }; + } + if (data[0] === 0x01) { try { - const inflated = inflateSync(Buffer.from(data.subarray(1))); - return inflated.toString('utf8'); - } catch { return ''; } + const inflated = inflateSync(Buffer.from(data.subarray(1)), { + maxOutputLength: maxOutputBytes, + }); + return inflated.length > 0 + ? { ok: true, text: inflated.toString('utf8'), outputBytes: inflated.length } + : { ok: false, reason: 'empty_output' }; + } catch (error) { + const code = typeof error === 'object' && error !== null && 'code' in error + ? String(error.code) + : ''; + return { + ok: false, + reason: code === 'ERR_BUFFER_TOO_LARGE' + ? 'output_limit_exceeded' + : code + ? `inflate_failed:${code}` + : 'inflate_failed', + }; + } } - if (data[0] === 0x00 && data.length > 1) { - return Buffer.from(data.subarray(1)).toString('utf8'); + if (data[0] === 0x00) { + if (data.length - 1 > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' }; + return { + ok: true, + text: Buffer.from(data.subarray(1)).toString('utf8'), + outputBytes: data.length - 1, + }; } - return Buffer.from(data).toString('utf8'); + if (data.length > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' }; + return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length }; } export function isNumericUin(value: string): boolean { diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 16174b94..11416ace 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -1,6 +1,7 @@ -import { protobuf_decode } from '@snowluma/proton'; +import { protobuf_decode, protobuf_getUnknownFieldMetadata } from '@snowluma/proton'; import { toHex, toHexUpper } from '@snowluma/common/hex'; -import type { MessageElement } from '../events'; +import { createLogger } from '@snowluma/common/logger'; +import type { MessageElement, MessageElementOf } from '../events'; import type { Elem, FileInfo, @@ -14,12 +15,291 @@ import type { } from '@snowluma/proto-defs/element'; import type { MarkdownData } from '@snowluma/proto-defs/action'; import type { FileExtra, MessageBody, PushMsgBody as PushMsgBodyFull, RichText } from '@snowluma/proto-defs/message'; -import { decompressData, makeImageUrl } from './helpers'; +import { + decompressData, + makeImageUrl, + MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES, + MAX_RICH_CARD_OUTPUT_BYTES, +} from './helpers'; type ElemDecoded = Elem; type RichTextDecoded = RichText; export type PushMsgBody = MessageBody; +const unknownElementLog = createLogger('MsgPush.UnknownElement'); + +// extraInfo/generalFlags are metadata attached to a real element, not message +// content by themselves. Every other listed key has an explicit decoder below. +// Anything outside this set is fail-open, but logged with its field name so a +// QQ wire change leaves a breadcrumb instead of becoming a silent data loss. +const DECODED_WIRE_FIELDS: ReadonlySet = new Set([ + 'text', 'face', 'notOnlineImage', 'transElem', 'marketFace', 'customFace', + 'richMsg', 'groupFile', 'videoFile', 'srcMsg', 'lightApp', 'commonElem', + 'extraInfo', 'generalFlags', +]); +const METADATA_WIRE_FIELDS: ReadonlySet = new Set(['extraInfo', 'generalFlags']); + +interface DecodedCardPayload { + element: MessageElement | null; + error: string | null; + inputBytes: number; + budgetBytes: number; +} + +interface DecodedCards { + rich?: DecodedCardPayload; + light?: DecodedCardPayload; +} + +function invalidCard(inputBytes: number, error: string, budgetBytes = 0): DecodedCardPayload { + return { element: null, error, inputBytes, budgetBytes }; +} + +function decodeCardData(data: Uint8Array, remainingOutputBytes: number) { + if (remainingOutputBytes <= 0) { + return { ok: false as const, reason: 'message_output_budget_exceeded', budgetBytes: 0 }; + } + const limit = Math.min(MAX_RICH_CARD_OUTPUT_BYTES, remainingOutputBytes); + const decoded = decompressData(data, limit); + if (!decoded.ok && decoded.reason === 'output_limit_exceeded' && limit < MAX_RICH_CARD_OUTPUT_BYTES) { + return { ok: false as const, reason: 'message_output_budget_exceeded', budgetBytes: limit }; + } + if (!decoded.ok) { + return { + ...decoded, + budgetBytes: decoded.reason === 'output_limit_exceeded' ? limit : 0, + }; + } + return { ...decoded, budgetBytes: decoded.outputBytes }; +} + +function isXmlCardContent(content: string): boolean { + const trimmed = content.trim(); + return trimmed.startsWith('<') && trimmed.endsWith('>'); +} + +function decodeRichMsgCard( + elem: ElemDecoded, + remainingOutputBytes: number, +): DecodedCardPayload | undefined { + const rm = elem.richMsg; + const data = rm?.template1; + if (!data || data.length === 0) return undefined; + const decoded = decodeCardData(data, remainingOutputBytes); + if (!decoded.ok) return invalidCard(data.length, decoded.reason, decoded.budgetBytes); + + const content = decoded.text; + const svcId = rm?.serviceId ?? 0; + if (svcId !== 1 && !isXmlCardContent(content)) { + return invalidCard(data.length, 'invalid_xml', decoded.budgetBytes); + } + if (svcId === 35) { + const match = /\bm_resid="([^"]+)"/.exec(content); + return { + element: match + ? { type: 'forward', resId: match[1] } + : { type: 'xml', text: content, subType: svcId }, + error: null, + inputBytes: data.length, + budgetBytes: decoded.budgetBytes, + }; + } + + if (svcId === 1) { + try { + const parsed: unknown = JSON.parse(content); + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return invalidCard(data.length, 'invalid_json_object', decoded.budgetBytes); + } + } catch { + return invalidCard(data.length, 'invalid_json', decoded.budgetBytes); + } + return { + element: { type: 'json', text: content }, + error: null, + inputBytes: data.length, + budgetBytes: decoded.budgetBytes, + }; + } + + return { + element: { type: 'xml', text: content, subType: svcId }, + error: null, + inputBytes: data.length, + budgetBytes: decoded.budgetBytes, + }; +} + +function decodeLightAppCard( + elem: ElemDecoded, + remainingOutputBytes: number, +): DecodedCardPayload | undefined { + const data = elem.lightApp?.data; + if (!data || data.length === 0) return undefined; + const decoded = decodeCardData(data, remainingOutputBytes); + if (!decoded.ok) return invalidCard(data.length, decoded.reason, decoded.budgetBytes); + + let parsed: unknown; + try { + parsed = JSON.parse(decoded.text); + } catch { + return invalidCard(data.length, 'invalid_json', decoded.budgetBytes); + } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) { + return invalidCard(data.length, 'invalid_json_object', decoded.budgetBytes); + } + + const card = parsed as { + app?: unknown; + meta?: { detail?: { resid?: unknown; uniseq?: unknown } }; + }; + if (card.app === 'com.tencent.multimsg') { + const detail = card.meta?.detail ?? {}; + const resId = typeof detail.resid === 'string' ? detail.resid : ''; + const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : ''; + if (resId) { + return { + element: { type: 'forward', resId, forwardUuid: uniseq || undefined }, + error: null, + inputBytes: data.length, + budgetBytes: decoded.budgetBytes, + }; + } + } + + return { + element: { type: 'json', text: decoded.text }, + error: null, + inputBytes: data.length, + budgetBytes: decoded.budgetBytes, + }; +} + +function decodeCardsOnce(elems: ElemDecoded[]): Map { + const decoded = new Map(); + let remainingOutputBytes = MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES; + for (const elem of elems) { + const cards: DecodedCards = {}; + const rich = decodeRichMsgCard(elem, remainingOutputBytes); + if (rich) remainingOutputBytes = Math.max(0, remainingOutputBytes - rich.budgetBytes); + const light = decodeLightAppCard(elem, remainingOutputBytes); + if (light) remainingOutputBytes = Math.max(0, remainingOutputBytes - light.budgetBytes); + if (rich) cards.rich = rich; + if (light) cards.light = light; + if (!rich && !light) continue; + decoded.set(elem, cards); + for (const [source, card] of Object.entries(cards)) { + if (card?.error) { + unknownElementLog.debug( + 'wire %s card ignored inputBytes=%d reason=%s', + source, + card.inputBytes, + card.error, + ); + } + } + } + return decoded; +} + +function logUnknownWireMetadata( + value: unknown, + path: string, + depth = 0, + seen = new WeakSet(), +): void { + if (depth > 16 || value === null || typeof value !== 'object' || ArrayBuffer.isView(value)) return; + if (seen.has(value)) return; + seen.add(value); + + logUnknownWireFields(value, path); + + if (Array.isArray(value)) { + value.forEach((entry, index) => logUnknownWireMetadata(entry, `${path}[${index}]`, depth + 1, seen)); + return; + } + for (const [key, entry] of Object.entries(value)) { + logUnknownWireMetadata(entry, `${path}.${key}`, depth + 1, seen); + } +} + +function logUnknownWireFields(value: unknown, path: string): void { + const metadata = protobuf_getUnknownFieldMetadata(value); + for (const unknown of metadata.fields) { + unknownElementLog.debug( + 'wire element ignored unknownTag=%d wireType=%d count=%d bytes=%d reason=no schema decoder path=%s', + unknown.fieldNumber, + unknown.wireType, + unknown.count, + unknown.totalByteLength, + path, + ); + } + if (metadata.omittedOccurrences > 0) { + unknownElementLog.debug( + 'wire unknown metadata truncated totalOccurrences=%d retainedKinds=%d omittedOccurrences=%d omittedBytes=%d path=%s', + metadata.totalOccurrences, + metadata.fields.length, + metadata.omittedOccurrences, + metadata.omittedByteLength, + path, + ); + } +} + +function classifyProtobufDecodeError(error: unknown): string { + const message = error instanceof Error ? error.message.toLowerCase() : ''; + if (message.includes('truncated')) return 'protobuf_truncated'; + if (message.includes('overflow')) return 'protobuf_varint_overflow'; + if (message.includes('bounds') || message.includes('invalid progress')) return 'protobuf_bounds'; + if (message.includes('wire type')) return 'protobuf_invalid_wire_type'; + if (message.includes('field number')) return 'protobuf_invalid_field_number'; + if (message.includes('group')) return 'protobuf_invalid_group'; + return 'protobuf_decode_failed'; +} + +function decodeProtobufPayload( + source: string, + data: Uint8Array, + decode: () => T, +): T | null { + try { + const decoded = decode(); + logUnknownWireMetadata(decoded, source); + return decoded; + } catch (error) { + unknownElementLog.debug( + 'wire protobuf payload ignored source=%s bytes=%d reason=%s', + source, + data.length, + classifyProtobufDecodeError(error), + ); + return null; + } +} + +type FingerprintElement = + | MessageElementOf<'image'> + | MessageElementOf<'record'> + | MessageElementOf<'video'> + | MessageElementOf<'file'>; + +function assignValidFingerprints( + element: FingerprintElement, + md5Hex: string | undefined, + sha1Hex: string | undefined, + source: string, +): void { + if (md5Hex) { + if (/^[0-9a-fA-F]{32}$/.test(md5Hex)) element.md5Hex = md5Hex; + else unknownElementLog.debug('wire %s ignored invalid md5 fingerprint length=%d', source, md5Hex.length); + } + if (sha1Hex) { + if (/^[0-9a-fA-F]{40}$/.test(sha1Hex)) element.sha1Hex = sha1Hex; + else unknownElementLog.debug('wire %s ignored invalid sha1 fingerprint length=%d', source, sha1Hex.length); + } +} + /** * Build the `mediaNode` re-upload descriptor from an NTV2 IndexNode + FileInfo. * Record and video decode to the byte-identical `{ fileUuid, storeId, @@ -54,8 +334,10 @@ function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] { const elements: MessageElement[] = []; + logUnknownWireFields(body, 'body'); if (body?.richText) { const rt = body.richText; + logUnknownWireFields(rt, 'body.richText'); if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[])); extractRichtextExtras(rt, elements, isGroup); } @@ -67,7 +349,6 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): function convertElements(elems: ElemDecoded[]): MessageElement[] { const result: MessageElement[] = []; - let skipNext = false; // [#146] A QQ mini-program / ark share (B站 video, QQ 小程序, …) arrives as a // `lightApp`/`richMsg` card element plus a plain `text` element carrying QQ's // graceful-degradation compat string ("当前QQ版本不支持此应用,请升级") — the text @@ -81,7 +362,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // rule: when a card is present, drop sibling plain `text`. `@`/reply/face etc. // are not plain text and survive. `richMsg` covers json (svc=1) and xml (svc=35) // cards alike. - const hasCard = elems.some((e) => e.lightApp || e.richMsg); + // Only a card that can actually decode is allowed to suppress QQ's sibling + // compatibility text. Field presence alone is insufficient: a malformed + // card must fail open and preserve its otherwise-valid text sibling. + const decodedCards = decodeCardsOnce(elems); + const hasCard = [...decodedCards.values()].some((cards) => ( + Boolean(cards.rich?.element || cards.light?.element) + )); // [#127] A QQ NT reply carries the replied sender as a structural auto-mention // (MentionExtra.type=2, uin=0) right after srcMsg, followed by a blank // separator text. Both are part of the reply wire shape, not user content — @@ -91,7 +378,22 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { let dropNextBlankText = false; for (const elem of elems) { - if (skipNext) { skipNext = false; continue; } + const resultCountBeforeElement = result.length; + logUnknownWireMetadata(elem, 'elem'); + + // Proton materializes every schema key with a null/default value, so key + // presence alone is not evidence that the wire carried that element. + // Report only unsupported fields with an actual decoded value. + const unsupportedFields = Object.entries(elem) + .filter(([, value]) => value !== null && value !== undefined) + .map(([key]) => key) + .filter((key) => !DECODED_WIRE_FIELDS.has(key)); + if (unsupportedFields.length > 0) { + unknownElementLog.debug( + 'wire element ignored fields=%s reason=no MessageElement decoder', + unsupportedFields.join(','), + ); + } // Reply / quote. For a c2c (friend) reply the canonical replied-to sequence // is the srcMsg reserve's `friendSequence`, NOT `origSeqs[0]` — origSeqs @@ -119,8 +421,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // backfill can reconstruct it locally if it isn't in the store / server. if (src.elemsRaw?.length) { const decoded: ElemDecoded[] = []; - for (const raw of src.elemsRaw) { - try { decoded.push(protobuf_decode(raw)); } catch { /* skip corrupt elem */ } + for (const [index, raw] of src.elemsRaw.entries()) { + const nested = decodeProtobufPayload( + `srcMsg.elemsRaw[${index}]`, + raw, + () => protobuf_decode(raw), + ); + if (nested) decoded.push(nested); } if (decoded.length) reply.replyElements = convertElements(decoded); } @@ -128,18 +435,20 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // in elems[] — recover it from sourceMsg (field 9) when elems carried no // file, so a quoted file's content survives into get_msg (#124). if (src.sourceMsg?.length && !reply.replyElements?.some((e) => e.type === 'file')) { - try { - const pmsg = protobuf_decode(src.sourceMsg); - const nof = pmsg?.body?.richText?.notOnlineFile; - if (nof?.fileName) { - (reply.replyElements ??= []).push({ - type: 'file', - fileName: nof.fileName, - fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0, - fileId: nof.fileUuid ?? '', - }); - } - } catch { /* sourceMsg decode is best-effort */ } + const pmsg = decodeProtobufPayload( + 'srcMsg.sourceMsg', + src.sourceMsg, + () => protobuf_decode(src.sourceMsg!), + ); + const nof = pmsg?.body?.richText?.notOnlineFile; + if (nof?.fileName) { + (reply.replyElements ??= []).push({ + type: 'file', + fileName: nof.fileName, + fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0, + fileId: nof.fileUuid ?? '', + }); + } } result.push(reply); } @@ -151,7 +460,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { const t = elem.text; let mention: MentionExtra | null = null; if (t.pbReserve && t.pbReserve.length > 0) { - mention = protobuf_decode(t.pbReserve); + mention = decodeProtobufPayload( + 'text.pbReserve', + t.pbReserve, + () => protobuf_decode(t.pbReserve!), + ); } const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11; const hasMention = mention && (mention.type === 1 || mention.type === 2); @@ -168,7 +481,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { } if (hasAttr6 || hasMention) { - const me: MessageElement = { type: 'at', text: t.str ?? '' }; + const me: MessageElement = { type: 'at', targetUin: 0, text: t.str ?? '' }; if (hasAttr6) { const buf = t.attr6Buf!; me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0; @@ -189,7 +502,8 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // Face if (elem.face) { - result.push({ type: 'face', faceId: elem.face.index ?? 0 }); + const faceId = elem.face.index ?? 0; + if (Number.isSafeInteger(faceId) && faceId >= 0) result.push({ type: 'face', faceId }); } // MarketFace (商城表情). Keep the wire identity (`emojiId`/`tabId`/`key`) @@ -199,19 +513,21 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // `faceId` GUID bytes — it also forms the gxh gif URL on the segment side. if (elem.marketFace) { const mf = elem.marketFace; - result.push({ - type: 'mface', - text: mf.faceName ?? '', - emojiId: mf.faceId && mf.faceId.length > 0 ? toHex(mf.faceId) : '', - emojiPackageId: mf.tabId ?? 0, - emojiKey: mf.key ?? '', - }); + if (mf.faceId?.length === 16) { + result.push({ + type: 'mface', + text: mf.faceName ?? '', + emojiId: toHex(mf.faceId), + emojiPackageId: mf.tabId ?? 0, + emojiKey: mf.key ?? '', + }); + } } // NotOnlineImage (C2C image) if (elem.notOnlineImage) { const img = elem.notOnlineImage; - if (img.picMd5 && img.picMd5.length > 0) { + if (img.picMd5?.length === 16) { const urlPath = img.origUrl || img.bigUrl || ''; result.push({ type: 'image', @@ -234,7 +550,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // CustomFace (group image) if (elem.customFace) { const img = elem.customFace; - if (img.md5 && img.md5.length > 0) { + if (img.md5?.length === 16) { result.push({ type: 'image', imageUrl: makeImageUrl(img.origUrl ?? ''), @@ -291,11 +607,17 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { // TransElem type=24 (group file via transport) if (elem.transElem) { const te = elem.transElem; + const resultCountBeforeTrans = result.length; if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) { const val = te.elemValue; const len = (val[1] << 8) | val[2]; if (val.length >= 3 + len) { - const extra = protobuf_decode(val.subarray(3, 3 + len)); + const payload = val.subarray(3, 3 + len); + const extra = decodeProtobufPayload( + 'transElem.groupFile', + payload, + () => protobuf_decode(payload), + ); if (extra?.inner?.info) { const info = extra.inner.info; result.push({ @@ -307,75 +629,27 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { } } } + if (result.length === resultCountBeforeTrans) { + unknownElementLog.debug( + 'wire transElem ignored elemType=%d reason=no recognized MessageElement payload', + te.elemType ?? 0, + ); + } } // RichMsg - if (elem.richMsg) { - const rm = elem.richMsg; - if (rm.template1 && rm.template1.length > 0) { - const content = decompressData(rm.template1); - if (content) { - const svcId = rm.serviceId ?? 0; - if (svcId === 35) { - const pos = content.indexOf('m_resid="'); - if (pos !== -1) { - const start = pos + 9; - const end = content.indexOf('"', start); - if (end !== -1) { - result.push({ type: 'forward', resId: content.substring(start, end) }); - continue; - } - } - result.push({ type: 'xml', text: content, subType: svcId }); - } else if (svcId === 1) { - result.push({ type: 'json', text: content }); - } else { - result.push({ type: 'xml', text: content, subType: svcId }); - } - } - } - } + const cards = decodedCards.get(elem); + if (cards?.rich?.element) result.push(cards.rich.element); // LightApp - if (elem.lightApp) { - const la = elem.lightApp; - if (la.data && la.data.length > 0) { - const content = decompressData(la.data); - if (content) { - // `com.tencent.multimsg` is the multi-msg / forward preview - // LightApp (the modern replacement for the XML serviceID=35 - // shape). Parse out resid + uniseq so downstream callers can - // both render a `[聊天记录]` placeholder and walk into the - // forward chain via `fetch(resId)` — the uniseq is what links - // the inner layer to its piggybacked actions on the outer's - // LongMsgResult. Other LightApp messages fall through to the - // generic `{type: 'json'}` path. - try { - const parsed = JSON.parse(content); - if (parsed && parsed.app === 'com.tencent.multimsg') { - const detail = parsed.meta?.detail ?? {}; - const resId = typeof detail.resid === 'string' ? detail.resid : ''; - const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : ''; - if (resId) { - result.push({ - type: 'forward', - resId, - forwardUuid: uniseq || undefined, - }); - continue; - } - } - } catch { /* fall through to generic json element */ } - result.push({ type: 'json', text: content }); - } - } - } + if (cards?.light?.element) result.push(cards.light.element); // CommonElem if (elem.commonElem) { const ce = elem.commonElem; const svcType = ce.serviceType ?? 0; const bizType = ce.businessType ?? 0; + const resultCountBeforeCommon = result.length; if (svcType === 2) { // Poke @@ -392,7 +666,12 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { if ((b & 0x80) === 0) break; } if (pos + length <= pb.length) { - const img = protobuf_decode(pb.subarray(pos, pos + length)); + const payload = pb.subarray(pos, pos + length); + const img = decodeProtobufPayload( + 'commonElem.flashImage', + payload, + () => protobuf_decode(payload), + ); if (img) { const me: MessageElement = { type: 'image', fileId: img.filePath ?? '', @@ -406,10 +685,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { result.push(me); } } - skipNext = true; } else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) { // NTQQ new protocol image/record/video - const info = protobuf_decode(ce.pbElem); + const info = decodeProtobufPayload( + 'commonElem.msgInfo', + ce.pbElem, + () => protobuf_decode(ce.pbElem!), + ); if (info?.msgInfoBody && info.msgInfoBody.length > 0) { const body = info.msgInfoBody[0]; if (body.index?.info) { @@ -434,8 +716,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { fileSize: fi.fileSize ?? 0, width: fi.width ?? 0, height: fi.height ?? 0, imageUrl: url, }; - if (fi.fileHash) me.md5Hex = fi.fileHash; - if (fi.fileSha1) me.sha1Hex = fi.fileSha1; + assignValidFingerprints(me, fi.fileHash, fi.fileSha1, 'commonElem image'); if (fi.type?.picFormat) me.picFormat = fi.type.picFormat; if (info.extBizInfo?.pic) { me.subType = info.extBizInfo.pic.bizType ?? 0; @@ -445,42 +726,52 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { result.push(me); } else if (bizType === 12 || bizType === 22) { // Record - result.push({ + const record: MessageElementOf<'record'> = { type: 'record', fileName: fi.fileName ?? '', fileId: idx.fileUuid ?? '', duration: fi.time ?? 0, fileHash: fi.fileHash ?? '', fileSize: fi.fileSize ?? 0, - md5Hex: fi.fileHash ?? '', - sha1Hex: fi.fileSha1 ?? '', voiceFormat: fi.type?.voiceFormat ?? 0, mediaNode: buildMediaNode(idx, fi), - }); + }; + assignValidFingerprints(record, fi.fileHash, fi.fileSha1, 'commonElem record'); + result.push(record); } else if (bizType === 11 || bizType === 21) { // Video - result.push({ + const video: MessageElementOf<'video'> = { type: 'video', fileName: fi.fileName ?? '', fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0, duration: fi.time ?? 0, fileHash: fi.fileHash ?? '', width: fi.width ?? 0, height: fi.height ?? 0, - md5Hex: fi.fileHash ?? '', - sha1Hex: fi.fileSha1 ?? '', videoFormat: fi.type?.videoFormat ?? 0, mediaNode: buildMediaNode(idx, fi), - }); + }; + assignValidFingerprints(video, fi.fileHash, fi.fileSha1, 'commonElem video'); + result.push(video); } } } } else if (svcType === 33 && ce.pbElem) { // Small face - const extra = protobuf_decode(ce.pbElem); - if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 }); + const extra = decodeProtobufPayload( + 'commonElem.smallFace', + ce.pbElem, + () => protobuf_decode(ce.pbElem!), + ); + const faceId = extra?.faceId ?? 0; + if (Number.isSafeInteger(faceId) && faceId >= 0) result.push({ type: 'face', faceId }); } else if (svcType === 37 && ce.pbElem) { // Big face - const extra = protobuf_decode(ce.pbElem); - if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid }); - skipNext = true; + const extra = decodeProtobufPayload( + 'commonElem.bigFace', + ce.pbElem, + () => protobuf_decode(ce.pbElem!), + ); + if (extra?.qsid !== undefined && Number.isSafeInteger(extra.qsid) && extra.qsid >= 0) { + result.push({ type: 'face', faceId: extra.qsid }); + } } else if (svcType === 45 && ce.pbElem && ce.pbElem.length > 0) { // Markdown commonElem. Older QQ clients (≤9.9.30) deliver a 闪传 (flash // transfer) file as a richui markdown card (busId=FlashTransfer); newer @@ -489,6 +780,38 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] { const flash = decodeFlashTransferCard(ce.pbElem); if (flash) result.push(flash); } + + // Route predicates alone are not proof that a payload decoded. Log any + // CommonElem that produced no MessageElement, including known service + // types with a new businessType or a malformed/unrecognized payload. + if (result.length === resultCountBeforeCommon) { + unknownElementLog.debug( + 'wire commonElem ignored serviceType=%d businessType=%d reason=no recognized MessageElement payload', + svcType, + bizType, + ); + } + } + + // Known content fields can also drift or arrive malformed. Preserve the + // rest of the message, but make every standalone decode miss observable. + // transElem/CommonElem emit richer diagnostics in their own branches. + if (result.length === resultCountBeforeElement) { + const ignoredKnownFields = Object.entries(elem) + .filter(([, value]) => value !== null && value !== undefined) + .map(([key]) => key) + .filter((key) => ( + DECODED_WIRE_FIELDS.has(key) + && !METADATA_WIRE_FIELDS.has(key) + && key !== 'transElem' + && key !== 'commonElem' + )); + if (ignoredKnownFields.length > 0) { + unknownElementLog.debug( + 'wire element ignored fields=%s reason=no recognized MessageElement payload', + ignoredKnownFields.join(','), + ); + } } } @@ -520,7 +843,11 @@ function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknow } function decodeFlashTransferCard(pbElem: Uint8Array): MessageElement | null { - const md = protobuf_decode(pbElem); + const md = decodeProtobufPayload( + 'commonElem.flashTransfer', + pbElem, + () => protobuf_decode(pbElem), + ); const content = md?.content ?? ''; if (!content.includes('FlashTransfer')) return null; const m = content.match(/[?&]json=([^)\s]+)/); @@ -535,11 +862,15 @@ function decodeFlashTransferCard(pbElem: Uint8Array): MessageElement | null { const filesetId = deepFindValue(obj, ['fileSetId', 'filesetId', 'fileset_id', 'file_set_id']); const title = deepFindValue(obj, ['title', 'fileName', 'name']); const sceneType = deepFindValue(obj, ['sceneType', 'scene_type']); + const normalizedFilesetId = filesetId != null ? String(filesetId).trim() : ''; + if (!normalizedFilesetId) return null; + const normalizedSceneType = sceneType == null ? 0 : Number(sceneType); + if (!Number.isSafeInteger(normalizedSceneType) || normalizedSceneType < 0) return null; return { type: 'flash_file', - filesetId: filesetId != null ? String(filesetId) : '', + filesetId: normalizedFilesetId, fileName: title != null ? String(title) : '', - sceneType: sceneType != null ? Number(sceneType) : 0, + sceneType: normalizedSceneType, }; } @@ -551,14 +882,14 @@ function extractRichtextExtras( // Ptt (voice) if (rt.ptt) { const p = rt.ptt; - const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : ''; - const me: MessageElement = { + const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : undefined; + const me: MessageElementOf<'record'> = { type: 'record', fileName: p.fileName ?? '', fileSize: p.fileSize ?? 0, duration: p.time ?? 0, - fileHash: md5Hex, - md5Hex, + fileHash: md5Hex ?? '', voiceFormat: p.format ?? 0, }; + assignValidFingerprints(me, md5Hex, undefined, 'ptt'); if (isGroup && (p.fileId ?? 0n) !== 0n) { me.fileId = p.groupFileKey ?? ''; } else { @@ -604,7 +935,11 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]): // "incomplete metadata". After consolidating FileExtra to wrap // `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`), // this reads the right tags. - const extra = protobuf_decode(msgContent); + const extra = decodeProtobufPayload( + 'messageBody.msgContent', + msgContent, + () => protobuf_decode(msgContent), + ); if (!extra?.file) return; const f = extra.file; if (!f.fileUuid) return; diff --git a/packages/protocol/src/packet-pipeline.ts b/packages/protocol/src/packet-pipeline.ts index 6f27b5d1..45deee06 100644 --- a/packages/protocol/src/packet-pipeline.ts +++ b/packages/protocol/src/packet-pipeline.ts @@ -4,6 +4,7 @@ import { createLogger, type Logger } from '@snowluma/common/logger'; import type { BridgeEventBus } from './event-bus'; import type { QQEventVariant } from './events'; import type { IdentityService } from './identity-service'; +import { formatGroupRequestFlag, type GroupRequestInfo } from './qq-info'; const moduleLog = createLogger('Bridge'); const moduleEventLog = createLogger('Event'); @@ -56,7 +57,10 @@ export interface PacketPipelineDeps { */ resolveGroupJoinRequest( groupId: number, uid: string, subType: 'add' | 'invite', - ): Promise<{ comment: string; sequence: number } | null>; + ): Promise; + /** Resolve a private invite-card msgseq. Implementations may briefly wait + * for the paired C2C Ark card, as the PkgType 87 push omits this value. */ + resolveGroupInviteCardSequence?(groupId: number): Promise; } export class IncomingPacketPipeline { @@ -251,6 +255,32 @@ export class IncomingPacketPipeline { // `notify.postscript`. Without this the OneBot `comment` field is // empty — bug #98. event.message = requestR.value.comment; + + const request = requestR.value; + const hasApprovalTuple = Number.isSafeInteger(request.sequence) && request.sequence > 0 + && Number.isSafeInteger(request.groupId) && request.groupId > 0 + && Number.isSafeInteger(request.eventType) && request.eventType > 0; + if (hasApprovalTuple) { + if (subType === 'invite' && request.eventType === 2) { + // A bot self-invite must use the private Ark card's msgseq (#125), + // not the sequence returned by 0x10C0. Keep the legacy flag when + // correlation times out so the action can retry the cache later. + const cardSequence = await this.deps.resolveGroupInviteCardSequence?.(event.groupId) ?? null; + if (cardSequence) { + event.flag = formatGroupRequestFlag({ + groupId: event.groupId, + sequence: cardSequence, + eventType: 2, + filtered: false, + }); + } else { + this.log.warn('invite-card msgseq unavailable before dispatch: groupId=%d uid=%s', + event.groupId, uid); + } + } else { + event.flag = formatGroupRequestFlag(request); + } + } } else if (requestR.status === 'rejected') { this.log.warn('failed to resolve group join request: groupId=%d uid=%s err=%s', event.groupId, uid, diff --git a/packages/protocol/src/qq-info.ts b/packages/protocol/src/qq-info.ts index f62148fe..b1c6c20f 100644 --- a/packages/protocol/src/qq-info.ts +++ b/packages/protocol/src/qq-info.ts @@ -67,3 +67,22 @@ export interface GroupRequestInfo { comment: string; filtered: boolean; } + +/** Approval tuple required by OIDB 0x10C8. The OneBot flag is opaque to + * clients, but carrying the complete tuple makes delayed handling stateless. */ +export type GroupRequestHandle = Pick< + GroupRequestInfo, + 'sequence' | 'groupId' | 'eventType' | 'filtered' +>; + +/** Canonical SnowLuma group-request flag (version 1). */ +export function formatGroupRequestFlag(handle: GroupRequestHandle): string { + return [ + 'slreq', + '1', + handle.sequence, + handle.groupId, + handle.eventType, + handle.filtered ? 1 : 0, + ].join(':'); +} diff --git a/packages/protocol/tests/element-manifest.test.ts b/packages/protocol/tests/element-manifest.test.ts index 4fbd7742..07c4be1b 100644 --- a/packages/protocol/tests/element-manifest.test.ts +++ b/packages/protocol/tests/element-manifest.test.ts @@ -1,7 +1,12 @@ import { describe, it, expect } from 'vitest'; import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; -import { typesForDirection } from '../src/element-manifest'; +import { + ELEMENT_MANIFEST, + MessageElementValidationError, + assertValidMessageElement, + typesForDirection, +} from '../src/element-manifest'; // 对账测试(protocol 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的 // 两个 protocol 方向: @@ -47,4 +52,76 @@ describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包) expect(handled).not.toContain('poke'); expect(handled).toEqual(sorted(typesForDirection('W'))); }); + + it('fields 是可执行封闭契约:每个声明字段都有 validator,越界字段会拒绝', () => { + const sampleValue = (field: string): unknown => { + if (field === 'replyElements') return []; + if (field === 'forwardNews') return [{ text: 'preview' }]; + if (field === 'mediaNode') return {}; + if (field === 'emojiId' || field === 'md5Hex') return 'ab'.repeat(16); + if (field === 'sha1Hex') return 'cd'.repeat(20); + if (field === 'flash' || field === 'noByteFallback') return true; + if (field === 'targetUin' || field === 'faceId' || field === 'fileSize' + || field.startsWith('reply') || field === 'subType' || field === 'duration' + || field === 'width' || field === 'height' || field === 'emojiPackageId' + || field === 'sceneType' || field === 'forwardTSum' || field.endsWith('Format')) return 1; + return 'value'; + }; + + for (const [type, spec] of Object.entries(ELEMENT_MANIFEST)) { + expect(new Set(spec.fields).size, `${type} has duplicate fields`).toBe(spec.fields.length); + for (const required of spec.requiredFields) expect(spec.fields).toContain(required); + const element: Record = { type }; + for (const field of spec.fields) element[field] = sampleValue(field); + expect(() => assertValidMessageElement(element), type).not.toThrow(); + } + + expect(() => assertValidMessageElement({ type: 'poke', subType: 1, faceId: 1 })) + .toThrowError(expect.objectContaining({ + name: 'MessageElementValidationError', + code: 'UNEXPECTED_FIELD', + elementType: 'poke', + field: 'faceId', + })); + expect(() => assertValidMessageElement({ type: 'reply' })) + .toThrowError(expect.objectContaining({ code: 'MISSING_FIELD', field: 'replySeq' })); + expect(() => assertValidMessageElement({ type: 'toString' })) + .toThrowError(expect.objectContaining({ code: 'UNKNOWN_TYPE', elementType: 'toString' })); + expect(() => assertValidMessageElement({ type: 'mface', emojiId: 'zz' }, 'W')) + .toThrowError(expect.objectContaining({ code: 'INVALID_FIELD', field: 'emojiId' })); + expect(() => assertValidMessageElement({ + type: 'image', + url: 'https://example.com/a.png', + md5Hex: 'not-md5', + }, 'W')).toThrowError(expect.objectContaining({ code: 'INVALID_FIELD', field: 'md5Hex' })); + }); + + it('returns a stable typed validation error for BAD_REQUEST mapping', () => { + try { + assertValidMessageElement({ type: 'unknown-segment' }, 'W'); + expect.unreachable('validation should throw'); + } catch (error) { + expect(error).toBeInstanceOf(MessageElementValidationError); + expect(error).toMatchObject({ code: 'UNKNOWN_TYPE', elementType: 'unknown-segment' }); + } + }); + + it('rejects invalid wire ranges and incomplete fast-upload fingerprints', () => { + expect(() => assertValidMessageElement({ + type: 'file', + fileId: 'fid', + fileSize: -1, + }, 'P')).toThrowError(expect.objectContaining({ + code: 'INVALID_FIELD', + field: 'fileSize', + })); + expect(() => assertValidMessageElement({ + type: 'image', + url: 'https://example.com/fallback-must-not-be-used.png', + noByteFallback: true, + }, 'W')).toThrowError(expect.objectContaining({ + code: 'MISSING_FIELD', + field: 'md5Hex', + })); + }); }); diff --git a/packages/protocol/tests/msg-push/fetch-group-history.test.ts b/packages/protocol/tests/msg-push/fetch-group-history.test.ts index c8815f9f..48ed6512 100644 --- a/packages/protocol/tests/msg-push/fetch-group-history.test.ts +++ b/packages/protocol/tests/msg-push/fetch-group-history.test.ts @@ -9,7 +9,7 @@ import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-def import type { IdentityService } from '../../src/identity-service'; import { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from '../../src/msg-push'; -const identity = { findGroupMember: () => undefined } as unknown as IdentityService; +const identity = { findGroupMember: () => undefined, findGroup: () => null } as unknown as IdentityService; function okResult(data: Uint8Array): SendPacketResult { return { success: true, gotResponse: true, responseData: data } as SendPacketResult; @@ -69,7 +69,7 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => { it('[#1] prefers the fresher group card in grp.memberCard (field 4) over a stale cache card', async () => { const stale = { uin: 222, uid: '', nickname: 'BaseNick', card: 'StaleCard', role: 'member', level: 0, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0 }; - const idWithMember = { findGroupMember: (_g: number, u: number) => (u === 222 ? stale : undefined) } as unknown as IdentityService; + const idWithMember = { findGroupMember: (_g: number, u: number) => (u === 222 ? stale : undefined), findGroup: () => null } as unknown as IdentityService; const resp = protobuf_encode({ body: { groupUin: 9999, messages: [ { responseHead: { fromUin: 222, grp: { groupUin: 9999, memberCard: 'FreshCard' } }, // field2 empty, field4 = fresh card @@ -84,7 +84,7 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => { it('[#1] keeps the cache card when field 4 equals the base nickname (no active group card)', async () => { const m = { uin: 222, uid: '', nickname: 'BaseNick', card: 'CachedCard', role: 'member', level: 0, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0 }; - const id = { findGroupMember: () => m } as unknown as IdentityService; + const id = { findGroupMember: () => m, findGroup: () => null } as unknown as IdentityService; const resp = protobuf_encode({ body: { groupUin: 9999, messages: [ { responseHead: { fromUin: 222, grp: { groupUin: 9999, memberCard: 'BaseNick' } }, // field4 == base nick → not a card diff --git a/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts b/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts index 2d274ed1..712de609 100644 --- a/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts +++ b/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts @@ -35,9 +35,9 @@ describe('decodeRichBody / 闪传 flash_file (#199/#200)', () => { expect(out).toEqual([{ type: 'flash_file', filesetId: 'fs-deep', fileName: 'a.zip', sceneType: 0 }]); }); - it('defaults missing fields (still emits a non-empty element)', () => { + it('drops a malformed card that has no fileset identity', () => { const out = decodeRichBody(flashBody({ busId: 'FlashTransfer', templateId: 'flash' }), true); - expect(out).toEqual([{ type: 'flash_file', filesetId: '', fileName: '', sceneType: 0 }]); + expect(out).toEqual([]); }); it('ignores a non-FlashTransfer markdown card (no flash_file element)', () => { diff --git a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts index c78768d5..c8c5c584 100644 --- a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -11,11 +11,14 @@ import { describe, expect, it } from 'vitest'; import { deflateSync } from 'zlib'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { decodeRichBody } from '../../src/msg-push/rich-body-decoder'; +import { MAX_RICH_CARD_OUTPUT_BYTES } from '../../src/msg-push/helpers'; import { buildSendElems } from '../../src/element-builder'; +import { assertValidMessageElement } from '../../src/element-manifest'; import type { MessageElement } from '../../src/events'; import type { MessageBody } from '@snowluma/proto-defs/message'; -import type { SrcMsgPbReserve } from '@snowluma/proto-defs/element'; +import type { Elem, MsgInfo, QFaceExtra, SrcMsgPbReserve } from '@snowluma/proto-defs/element'; function lightAppBytes(json: unknown): Uint8Array { const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8')); @@ -25,6 +28,26 @@ function lightAppBytes(json: unknown): Uint8Array { return out; } +function varint(value: number): number[] { + const out: number[] = []; + let current = value >>> 0; + do { + let byte = current & 0x7f; + current >>>= 7; + if (current !== 0) byte |= 0x80; + out.push(byte); + } while (current !== 0); + return out; +} + +function lengthDelimited(fieldNumber: number, payload: Uint8Array): Uint8Array { + return Uint8Array.from([ + ...varint((fieldNumber << 3) | 2), + ...varint(payload.length), + ...payload, + ]); +} + describe('decodeRichBody / forward LightApp', () => { it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => { const body: MessageBody = { @@ -228,6 +251,25 @@ describe('decodeRichBody / market face', () => { }); }); +describe('decodeRichBody / decoded element contract', () => { + it('omits an absent PTT fingerprint instead of emitting an invalid empty hash', () => { + const body: MessageBody = { + richText: { + ptt: { + fileName: 'voice.silk', + fileSize: 12, + time: 1, + fileMd5: new Uint8Array(), + }, + }, + } as any; + const out = decodeRichBody(body, true); + expect(out).toHaveLength(1); + expect(out[0]).not.toHaveProperty('md5Hex'); + expect(() => assertValidMessageElement(out[0], 'D')).not.toThrow(); + }); +}); + // Reply identity for c2c: the replied-to sequence is srcMsg.origSeqs[0] for BOTH // group and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals the // quoted message's head.sequence — i.e. the seq its message_id is hashed from — @@ -269,3 +311,475 @@ describe('decodeRichBody / reply uses origSeqs[0] for c2c', () => { expect(decodeRichBody(body, false)).toContainEqual({ type: 'reply', replySeq: CLIENT_SEQ }); }); }); + +describe('decodeRichBody / unknown wire element observability', () => { + it('does not report Proton materialized null fields as wire elements', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const encoded = protobuf_encode({ + richText: { elems: [{ text: { str: 'known text' } }] }, + }); + const decodedBody = protobuf_decode(encoded); + expect(decodeRichBody(decodedBody, true)).toEqual([{ type: 'text', text: 'known text' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured.filter((entry) => entry.scope === 'MsgPush.UnknownElement')).toEqual([]); + }); + + it('records a service-48 CommonElem with an unknown business type', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [{ + commonElem: { + serviceType: 48, + businessType: 99, + pbElem: protobuf_encode({}), + }, + }], + }, + }; + expect(decodeRichBody(body, true)).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'serviceType=48 businessType=99 reason=no recognized MessageElement payload', + ), + })); + }); + + it('fails open and records the unsupported wire field plus reason', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [{ onlineImage: { filePath: '/unknown-wire-shape' } } as any], + }, + }; + let decoded: ReturnType | undefined; + expect(() => { decoded = decodeRichBody(body, true); }).not.toThrow(); + expect(decoded).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('fields=onlineImage reason=no MessageElement decoder'), + })); + }); + + it('retains and records a schema-unknown protobuf tag beside known text', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const knownElem = protobuf_encode({ + text: { str: 'known text' }, + }); + const unknownElem = lengthDelimited(60, Uint8Array.of(1, 2, 3)); + const richText = Uint8Array.from([ + ...lengthDelimited(2, knownElem), + ...lengthDelimited(2, unknownElem), + ]); + const rawBody = lengthDelimited(1, richText); + const decodedBody = protobuf_decode(rawBody); + + expect(decodeRichBody(decodedBody, true)).toEqual([{ type: 'text', text: 'known text' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'unknownTag=60 wireType=2 count=1 bytes=4 reason=no schema decoder path=elem', + ), + })); + }); + + it('logs repeated unknown tags once with an occurrence count', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const elemBytes: number[] = [...protobuf_encode({ text: { str: 'known' } })]; + const unknown = lengthDelimited(60, Uint8Array.of(7)); + for (let index = 0; index < 1_000; index++) elemBytes.push(...unknown); + const richText = lengthDelimited(2, Uint8Array.from(elemBytes)); + const decodedBody = protobuf_decode(lengthDelimited(1, richText)); + + expect(decodeRichBody(decodedBody, true)).toEqual([{ type: 'text', text: 'known' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + const logs = captured.filter((entry) => entry.message.includes('unknownTag=60')); + expect(logs).toHaveLength(1); + expect(logs[0]?.message).toContain('count=1000 bytes=2000'); + }); + + it('preserves sibling text and records a malformed known card field', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [ + { richMsg: { serviceId: 35, template1: Uint8Array.of(1, 1, 2, 3) } } as any, + { text: { str: 'keep me' } } as any, + ], + }, + }; + expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep me' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('fields=richMsg reason=no recognized MessageElement payload'), + })); + }); + + it('does not consume the next element when a structural CommonElem is malformed', () => { + const body: MessageBody = { + richText: { + elems: [ + { commonElem: { serviceType: 3, businessType: 0, pbElem: Uint8Array.of(0, 5) } } as any, + { text: { str: 'keep next' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep next' }]); + }); + + it('does not consume sibling text after a decoded big face', () => { + const body: MessageBody = { + richText: { + elems: [ + { + commonElem: { + serviceType: 37, + businessType: 0, + pbElem: protobuf_encode({ qsid: 321 }), + }, + } as any, + { text: { str: 'keep after face' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([ + { type: 'face', faceId: 321 }, + { type: 'text', text: 'keep after face' }, + ]); + }); + + it('records unknown tags inside bytes-embedded protobuf payloads', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const known = protobuf_encode({ qsid: 654 }); + const pbElem = Uint8Array.from([ + ...known, + ...lengthDelimited(60, Uint8Array.of(1, 2)), + ]); + const body: MessageBody = { + richText: { + elems: [{ + commonElem: { serviceType: 37, businessType: 0, pbElem }, + } as any], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([{ type: 'face', faceId: 654 }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + message: expect.stringContaining( + 'unknownTag=60 wireType=2 count=1 bytes=3 reason=no schema decoder path=commonElem.bigFace', + ), + })); + }); + + it('fails open when an embedded face protobuf is truncated', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [ + { + commonElem: { + serviceType: 37, + businessType: 0, + pbElem: Uint8Array.of(0x18, 0x80), + }, + } as any, + { text: { str: 'keep after malformed face' } } as any, + ], + }, + }; + + let decoded: ReturnType | undefined; + expect(() => { decoded = decodeRichBody(body, true); }).not.toThrow(); + expect(decoded).toEqual([ + { type: 'text', text: 'keep after malformed face' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'source=commonElem.bigFace bytes=2 reason=protobuf_truncated', + ), + })); + }); + + it('retains and records schema-unknown tags inside nested element messages', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const textPayload = Uint8Array.from([ + ...lengthDelimited(1, new TextEncoder().encode('nested known text')), + ...lengthDelimited(60, Uint8Array.of(9, 8, 7)), + ]); + const elemPayload = lengthDelimited(1, textPayload); + const richTextPayload = lengthDelimited(2, elemPayload); + const decodedBody = protobuf_decode(lengthDelimited(1, richTextPayload)); + + expect(decodeRichBody(decodedBody, true)).toEqual([ + { type: 'text', text: 'nested known text' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'unknownTag=60 wireType=2 count=1 bytes=4 reason=no schema decoder path=elem.text', + ), + })); + }); + + it('preserves sibling text when a LightApp is not a JSON object', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [ + { + lightApp: { + data: Uint8Array.from([0, ...Buffer.from('not-json', 'utf8')]), + }, + } as any, + { text: { str: 'keep me' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep me' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('wire light card ignored inputBytes=9 reason=invalid_json'), + })); + expect(captured.some((entry) => entry.message.includes('not-json'))).toBe(false); + }); + + it('records unknown tags on MessageBody and RichText roots', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const knownElem = protobuf_encode({ text: { str: 'root known text' } }); + const richTextPayload = Uint8Array.from([ + ...lengthDelimited(2, knownElem), + ...lengthDelimited(61, Uint8Array.of(4, 5)), + ]); + const rawBody = Uint8Array.from([ + ...lengthDelimited(1, richTextPayload), + ...lengthDelimited(60, Uint8Array.of(6)), + ]); + const decodedBody = protobuf_decode(rawBody); + + expect(decodeRichBody(decodedBody, true)).toEqual([ + { type: 'text', text: 'root known text' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + message: expect.stringContaining('unknownTag=60 wireType=2 count=1 bytes=2 reason=no schema decoder path=body'), + })); + expect(captured).toContainEqual(expect.objectContaining({ + message: expect.stringContaining('unknownTag=61 wireType=2 count=1 bytes=3 reason=no schema decoder path=body.richText'), + })); + }); + + it('does not treat marker-only or non-XML RichMsg data as a card', () => { + const body: MessageBody = { + richText: { + elems: [ + { richMsg: { serviceId: 35, template1: Uint8Array.of(0) } } as any, + { + richMsg: { + serviceId: 35, + template1: Uint8Array.from([0, ...Buffer.from('not xml', 'utf8')]), + }, + } as any, + { text: { str: 'keep malformed card fallback' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([ + { type: 'text', text: 'keep malformed card fallback' }, + ]); + }); + + it('bounds compressed card output and preserves sibling text on overflow', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const compressed = deflateSync(Buffer.alloc(MAX_RICH_CARD_OUTPUT_BYTES + 1, 0x61)); + const data = new Uint8Array(compressed.length + 1); + data[0] = 1; + data.set(compressed, 1); + const body: MessageBody = { + richText: { + elems: [ + { lightApp: { data } } as any, + { text: { str: 'bounded fallback' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([ + { type: 'text', text: 'bounded fallback' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('reason=output_limit_exceeded'), + })); + }); + + it('bounds retained card output across the entire message', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const payload = { app: 'budget-test', data: 'x'.repeat(3 * 1024 * 1024) }; + const body: MessageBody = { + richText: { + elems: [ + { lightApp: { data: lightAppBytes(payload) } } as any, + { lightApp: { data: lightAppBytes(payload) } } as any, + { lightApp: { data: lightAppBytes(payload) } } as any, + ], + }, + }; + + const decoded = decodeRichBody(body, true); + expect(decoded).toHaveLength(2); + expect(decoded.every((element) => element.type === 'json')).toBe(true); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('reason=message_output_budget_exceeded'), + })); + }); + + it('charges malformed card inflation against the message budget', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const compressed = deflateSync(Buffer.alloc(3 * 1024 * 1024, 0x78)); + const data = new Uint8Array(compressed.length + 1); + data[0] = 1; + data.set(compressed, 1); + const body: MessageBody = { + richText: { + elems: Array.from({ length: 4 }, () => ({ lightApp: { data } } as any)), + }, + }; + + expect(decodeRichBody(body, true)).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + const exhausted = captured.filter((entry) => ( + entry.scope === 'MsgPush.UnknownElement' + && entry.message.includes('reason=message_output_budget_exceeded') + )); + expect(exhausted).toHaveLength(2); + }); +}); diff --git a/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts b/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts index c82139fc..8264ec8b 100644 --- a/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts +++ b/packages/protocol/tests/oidb-services/group-admin/set-special-title.test.ts @@ -32,7 +32,7 @@ describe('SetSpecialTitle namespace', () => { expect(env.body?.body?.specialTitle).toBe('crown'); // uinName (tag 7) must mirror specialTitle or the server silently no-ops. expect(env.body?.body?.uinName).toBe('crown'); - // -1 (int_32) round-trips as 0xFFFFFFFF after the proton decoder reinterprets. - expect(env.body?.body?.expireTime).toBe(0xFFFFFFFF); + // int_32 preserves the signed -1 sentinel after the wire round-trip. + expect(env.body?.body?.expireTime).toBe(-1); }); }); diff --git a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts index db799d0c..2c0db50d 100644 --- a/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts +++ b/packages/protocol/tests/packet-pipeline-stranger-resolve.test.ts @@ -19,23 +19,29 @@ import type { PacketInfo } from '@snowluma/common/protocol-types'; function makePipeline(opts: { resolveStrangerProfile?: vi.Mock; resolveGroupJoinRequest?: vi.Mock; + resolveGroupInviteCardSequence?: vi.Mock; } = {}) { const identity = IdentityService.memory('10001'); const events = new BridgeEventBus(); const resolveStrangerProfile = opts.resolveStrangerProfile ?? vi.fn(async () => null); const resolveGroupJoinRequest = opts.resolveGroupJoinRequest ?? vi.fn(async () => null); + const resolveGroupInviteCardSequence = opts.resolveGroupInviteCardSequence ?? vi.fn(async () => null); const pipeline = new IncomingPacketPipeline({ identity, events, refreshMemberCache: vi.fn(async () => false), resolveStrangerProfile, resolveGroupJoinRequest, + resolveGroupInviteCardSequence, }); const captured: QQEventVariant[] = []; events.onAny((event) => { captured.push(event as QQEventVariant); }); - return { pipeline, events, captured, resolveStrangerProfile, resolveGroupJoinRequest }; + return { + pipeline, events, captured, + resolveStrangerProfile, resolveGroupJoinRequest, resolveGroupInviteCardSequence, + }; } describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { @@ -185,6 +191,73 @@ describe('IncomingPacketPipeline / stranger resolve on group_invite', () => { expect(ev.fromUin).toBe(1957003260); }); + it('replaces the legacy identity flag with a canonical approval tuple', async () => { + const resolveGroupJoinRequest = vi.fn(async () => ({ + groupId: 950929451, + groupName: 'group', + targetUid: 'u_target', + targetUin: 1957003260, + targetName: 'target', + invitorUid: 'u_inviter', + invitorUin: 0, + invitorName: '', + operatorUid: '', + operatorUin: 0, + operatorName: '', + sequence: 1779543612823906, + state: 1, + eventType: 1, + comment: '你们好', + filtered: true, + })); + const { pipeline, captured } = makePipeline({ resolveGroupJoinRequest }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', + time: 1, selfUin: 10001, + groupId: 950929451, fromUin: 1957003260, + fromUid: 'u_target', subType: 'add', message: '', + flag: 'add:950929451:u_target', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(captured).toHaveLength(1); + expect(captured[0]).toMatchObject({ + message: '你们好', + flag: 'slreq:1:1779543612823906:950929451:1:1', + }); + }); + + it('uses the private invite-card msgseq for a self-invite approval tuple', async () => { + const resolveGroupJoinRequest = vi.fn(async () => ({ + groupId: 999, groupName: 'group', + targetUid: 'self', targetUin: 10001, targetName: 'self', + invitorUid: 'u_inviter', invitorUin: 456, invitorName: 'inviter', + operatorUid: '', operatorUin: 0, operatorName: '', + sequence: 111, state: 1, eventType: 2, + comment: '', filtered: false, + })); + const resolveGroupInviteCardSequence = vi.fn(async () => 778899); + const { pipeline, captured } = makePipeline({ + resolveGroupJoinRequest, + resolveGroupInviteCardSequence, + }); + + pipeline.registerCmd('test.cmd', () => [{ + kind: 'group_invite', time: 1, selfUin: 10001, + groupId: 999, fromUin: 456, fromUid: 'u_inviter', + subType: 'invite', message: '', flag: 'invite:999:u_inviter', + } as QQEventVariant]); + + pipeline.process({ serviceCmd: 'test.cmd' } as PacketInfo); + await new Promise(r => setTimeout(r, 10)); + + expect(resolveGroupInviteCardSequence).toHaveBeenCalledWith(999); + expect(captured[0]).toMatchObject({ flag: 'slreq:1:778899:999:2:0' }); + }); + it('runs the profile + request lookups in parallel (independent failures)', async () => { // Profile lookup succeeds, request lookup fails — event should // still carry the resolved uin but no comment. The dispatch @@ -309,7 +382,7 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => { } const groupMsg = (senderCard: string): QQEventVariant => ({ - kind: 'group_message', time: 1, selfUin: 10001, groupId: 9999, senderUin: 222, + kind: 'group_message', groupName: '', time: 1, selfUin: 10001, groupId: 9999, senderUin: 222, senderNick: 'BaseNick', senderCard, senderRole: 'member', msgSeq: 1, msgId: 1, elements: [{ type: 'text', text: 'hi' }], } as QQEventVariant); @@ -378,7 +451,7 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () = function groupMsg(card: string): QQEventVariant { return { - kind: 'group_message', time: 1700000000, selfUin: 10001, groupId: GROUP, + kind: 'group_message', groupName: '', time: 1700000000, selfUin: 10001, groupId: GROUP, senderUin: 22222, senderNick: 'nick', senderCard: card, senderRole: 'member', msgSeq: 1, msgId: 1, elements: [], } as QQEventVariant; diff --git a/packages/proton/package.json b/packages/proton/package.json index bc773523..bf19cff2 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.12.0", + "version": "1.12.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/proton/protobuf.d.ts b/packages/proton/protobuf.d.ts index b6f52593..4c8cbccb 100644 --- a/packages/proton/protobuf.d.ts +++ b/packages/proton/protobuf.d.ts @@ -32,6 +32,22 @@ export type bytes = Uint8Array; export function protobuf_encode(params: T): Uint8Array; export function protobuf_decode(data: Uint8Array): T; +/** Non-enumerable metadata retained for protobuf tags unknown to the schema. */ +export interface ProtobufUnknownField { + fieldNumber: number; + wireType: number; + count: number; + totalByteLength: number; +} +export interface ProtobufUnknownFieldMetadata { + fields: readonly ProtobufUnknownField[]; + totalOccurrences: number; + omittedOccurrences: number; + omittedByteLength: number; +} +export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[]; +export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata; + // ── Optional runtime map fallback (disabled by default) ─────────────── export interface ProtobufRuntimeField { name: string; diff --git a/packages/proton/src/codegen/decoder.ts b/packages/proton/src/codegen/decoder.ts index 9b8477d2..3a7f349d 100644 --- a/packages/proton/src/codegen/decoder.ts +++ b/packages/proton/src/codegen/decoder.ts @@ -10,19 +10,15 @@ function tagValue(field: ProtobufField): number { /** Emit inline varint decode, storing result in `varName`. */ function varintDec(varName: string, ind: string): string { return [ - `${ind}let ${varName} = data[offset++];`, - `${ind}if (${varName} & 0x80) {`, - `${ind} let _s = 7, _b;`, - `${ind} ${varName} &= 0x7f;`, - `${ind} do { _b = data[offset++]; ${varName} |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80);`, - `${ind}}`, + `${ind}const [${varName}, ${varName}_offset] = __readVarint32(data, offset, end);`, + `${ind}offset = ${varName}_offset;`, ].join('\n'); } function varintDec64(varName: string, ind: string): string { return [ - `${ind}let ${varName} = 0n, _s = 0n, _b;`, - `${ind}do { _b = data[offset++]; ${varName} |= BigInt(_b & 0x7f) << _s; _s += 7n; } while (_b & 0x80);`, + `${ind}const [${varName}, ${varName}_offset] = __readVarint64(data, offset, end);`, + `${ind}offset = ${varName}_offset;`, ].join('\n'); } @@ -34,13 +30,7 @@ function isFixed64BigInt(typeName: string): boolean { return typeName === 'fixed_64' || typeName === 'sfixed_64'; } -const INLINE_SKIP = [ - ` const wireType = _tag & 0x7;`, - ` if (wireType === 0) { while (data[offset] & 0x80) offset++; offset++; }`, - ` else if (wireType === 1) offset += 8;`, - ` else if (wireType === 2) { let _l = data[offset++]; if (_l & 0x80) { let _s = 7, _b; _l &= 0x7f; do { _b = data[offset++]; _l |= (_b & 0x7f) << _s; _s += 7; } while (_b & 0x80); } offset += _l; }`, - ` else if (wireType === 5) offset += 4;`, -].join('\n'); +const INLINE_SKIP = ` offset = __skipUnknownField(data, offset, end, wireType, _tag >>> 3);`; export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry): string { const locals = msg.fields.map((field, index) => { @@ -51,14 +41,20 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry const L = [ `function protobuf_decode_${msg.name}(data, offset = 0, end = data.length) {`, + ` if (!Number.isSafeInteger(offset) || !Number.isSafeInteger(end) || offset < 0 || end < offset || end > data.length) {`, + ` throw new Error('protobuf decoder bounds are invalid');`, + ` }`, ...locals, + ` let _unknownFields = null;`, + ` let _unknownFieldsByKey = null;`, + ` let _unknownTotalOccurrences = 0;`, + ` let _unknownOmittedOccurrences = 0;`, + ` let _unknownOmittedByteLength = 0;`, ` while (offset < end) {`, - ` let _tag = data[offset++];`, - ` if (_tag & 0x80) {`, - ` let _ts = 7, _tb;`, - ` _tag &= 0x7f;`, - ` do { _tb = data[offset++]; _tag |= (_tb & 0x7f) << _ts; _ts += 7; } while (_tb & 0x80);`, - ` }`, + ` const _fieldStart = offset;`, + ` const [_tag, _tagOffset] = __readVarint32(data, offset, end);`, + ` offset = _tagOffset;`, + ` if ((_tag >>> 3) === 0) throw new Error('protobuf field number 0 is invalid');`, ` switch (_tag) {`, ]; @@ -68,12 +64,50 @@ export function generateDecoder(msg: ProtobufMessage, _registry: MessageRegistry L.push( ` default: {`, + ` const _unknownStart = offset;`, + ` const wireType = _tag & 0x7;`, INLINE_SKIP, + ` const _unknownFieldNumber = _tag >>> 3;`, + ` const _unknownByteLength = offset - _unknownStart;`, + ` const _unknownKey = (_unknownFieldNumber * 8) + wireType;`, + ` _unknownTotalOccurrences++;`, + ` const _knownUnknown = _unknownFieldsByKey?.get(_unknownKey);`, + ` if (_knownUnknown) {`, + ` _knownUnknown.count++;`, + ` _knownUnknown.totalByteLength += _unknownByteLength;`, + ` } else if ((_unknownFields?.length ?? 0) < 64) {`, + ` const _unknown = {`, + ` fieldNumber: _unknownFieldNumber,`, + ` wireType,`, + ` count: 1,`, + ` totalByteLength: _unknownByteLength,`, + ` };`, + ` (_unknownFields ??= []).push(_unknown);`, + ` (_unknownFieldsByKey ??= new Map()).set(_unknownKey, _unknown);`, + ` } else {`, + ` _unknownOmittedOccurrences++;`, + ` _unknownOmittedByteLength += _unknownByteLength;`, + ` }`, ` break;`, ` }`, ` }`, + ` if (offset <= _fieldStart || offset > end) throw new Error('protobuf decoder made invalid progress');`, ` }`, - ` return { ${result} };`, + ` const _result = { ${result} };`, + ` if (_unknownTotalOccurrences > 0) Object.defineProperty(`, + ` _result,`, + ` Symbol.for('snowluma.proton.unknownFields'),`, + ` {`, + ` value: {`, + ` fields: _unknownFields ?? [],`, + ` totalOccurrences: _unknownTotalOccurrences,`, + ` omittedOccurrences: _unknownOmittedOccurrences,`, + ` omittedByteLength: _unknownOmittedByteLength,`, + ` },`, + ` enumerable: false,`, + ` },`, + ` );`, + ` return _result;`, `}`, ); return L.join('\n'); @@ -91,16 +125,17 @@ function decodeField(field: ProtobufField, index: number): string { if (isMessage) { L.push(varintDec('_len', I)); - L.push(assign(`protobuf_decode_${typeName}(data, offset, offset + _len)`)); - L.push(`${I}offset += _len;`); + L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); + L.push(assign(`protobuf_decode_${typeName}(data, offset, _end)`)); + L.push(`${I}offset = _end;`); } else if (typeName === 'string') { L.push(varintDec('_len', I)); - L.push(`${I}const _end = offset + _len;`); + L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); L.push(assign(`__td.decode(data.subarray(offset, _end))`)); L.push(`${I}offset = _end;`); } else if (typeName === 'bytes') { L.push(varintDec('_len', I)); - L.push(`${I}const _end = offset + _len;`); + L.push(`${I}const _end = __checkedEnd(offset, _len, end);`); L.push(assign(`data.slice(offset, _end)`)); L.push(`${I}offset = _end;`); } else if (typeName === 'bool') { @@ -115,6 +150,13 @@ function decodeField(field: ProtobufField, index: number): string { } else { L.push(assign(`__zigZagDecode64(_val)`)); } + } else if (typeName === 'int_32') { + // Protobuf encodes negative int32 values as a sign-extended 10-byte + // varint. Read the full uint64 representation, then keep its signed low + // 32 bits. uint32/sint32/tag/length values must remain on the stricter + // five-byte reader. + L.push(varintDec64('_val', I)); + L.push(assign(`Number(BigInt.asIntN(32, _val))`)); } else if (typeName === 'sint_32') { L.push(varintDec('_val', I)); L.push(assign(`(_val >>> 1) ^ -(_val & 1)`)); @@ -122,15 +164,19 @@ function decodeField(field: ProtobufField, index: number): string { L.push(varintDec('_val', I)); L.push(assign(`_val >>> 0`)); } else if (typeName === 'float') { + L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated float field');`); L.push(assign(`__readFloat32(data, offset)`)); L.push(`${I}offset += 4;`); } else if (wireType === WireType.Bit32) { + L.push(`${I}if (end - offset < 4) throw new Error('protobuf truncated fixed32 field');`); L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); L.push(`${I}offset += 4;`); } else if (typeName === 'double') { + L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated double field');`); L.push(assign(`__readFloat64(data, offset)`)); L.push(`${I}offset += 8;`); } else if (isFixed64BigInt(typeName)) { + L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`); if (typeName === 'fixed_64') { L.push(assign(`__readFixed64(data, offset)`)); } else { @@ -138,6 +184,7 @@ function decodeField(field: ProtobufField, index: number): string { } L.push(`${I}offset += 8;`); } else if (wireType === WireType.Bit64) { + L.push(`${I}if (end - offset < 8) throw new Error('protobuf truncated fixed64 field');`); L.push(assign(`data[offset] | (data[offset + 1] << 8) | (data[offset + 2] << 16) | (data[offset + 3] << 24)`)); L.push(`${I}offset += 8;`); } diff --git a/packages/proton/src/codegen/generator.ts b/packages/proton/src/codegen/generator.ts index ee4ee9ca..466226cc 100644 --- a/packages/proton/src/codegen/generator.ts +++ b/packages/proton/src/codegen/generator.ts @@ -95,6 +95,74 @@ function __zigZagEncode64(value) { function __zigZagDecode64(value) { return BigInt.asIntN(64, (value >> 1n) ^ -(value & 1n)); } +function __readVarint32(data, offset, end) { + let value = 0; + for (let i = 0; i < 5; i++) { + if (offset >= end) throw new Error('protobuf truncated uint32 varint'); + const byte = data[offset++]; + if (i === 4 && (byte & 0xf0) !== 0) throw new Error('protobuf uint32 varint overflow'); + value += (byte & 0x7f) * (2 ** (i * 7)); + if ((byte & 0x80) === 0) return [value >>> 0, offset]; + } + throw new Error('protobuf uint32 varint overflow'); +} +function __readVarint64(data, offset, end) { + let value = 0n; + for (let i = 0; i < 10; i++) { + if (offset >= end) throw new Error('protobuf truncated uint64 varint'); + const byte = data[offset++]; + if (i === 9 && byte > 1) throw new Error('protobuf uint64 varint overflow'); + value |= BigInt(byte & 0x7f) << BigInt(i * 7); + if ((byte & 0x80) === 0) return [value, offset]; + } + throw new Error('protobuf uint64 varint overflow'); +} +function __skipVarint(data, offset, end) { + for (let i = 0; i < 10; i++) { + if (offset >= end) throw new Error('protobuf truncated varint'); + const byte = data[offset++]; + if (i === 9 && byte > 1) throw new Error('protobuf varint overflow'); + if ((byte & 0x80) === 0) return offset; + } + throw new Error('protobuf varint overflow'); +} +function __checkedEnd(offset, length, end) { + if (length > end - offset) throw new Error('protobuf length-delimited field exceeds parent bounds'); + return offset + length; +} +function __skipUnknownField(data, offset, end, wireType, fieldNumber, depth = 0) { + if (depth > 64) throw new Error('protobuf group nesting exceeds 64'); + if (wireType === 0) return __skipVarint(data, offset, end); + if (wireType === 1) { + if (end - offset < 8) throw new Error('protobuf truncated fixed64 field'); + return offset + 8; + } + if (wireType === 2) { + const [length, next] = __readVarint32(data, offset, end); + return __checkedEnd(next, length, end); + } + if (wireType === 3) { + while (offset < end) { + const [tag, next] = __readVarint32(data, offset, end); + offset = next; + const nestedField = tag >>> 3; + const nestedWire = tag & 0x7; + if (nestedField === 0) throw new Error('protobuf field number 0 is invalid'); + if (nestedWire === 4) { + if (nestedField !== fieldNumber) throw new Error('protobuf mismatched end-group tag'); + return offset; + } + offset = __skipUnknownField(data, offset, end, nestedWire, nestedField, depth + 1); + } + throw new Error('protobuf unterminated group'); + } + if (wireType === 4) throw new Error('protobuf unexpected end-group tag'); + if (wireType === 5) { + if (end - offset < 4) throw new Error('protobuf truncated fixed32 field'); + return offset + 4; + } + throw new Error('protobuf invalid wire type ' + wireType); +} function __writeFloat32(buf, offset, value) { __scratch.setFloat32(0, value, true); buf[offset++] = __scratch.getUint8(0); diff --git a/packages/proton/src/runtime.ts b/packages/proton/src/runtime.ts index c48cc583..7dfbd394 100644 --- a/packages/proton/src/runtime.ts +++ b/packages/proton/src/runtime.ts @@ -12,6 +12,49 @@ import { type DynamicEncode = (params: unknown) => Uint8Array; type DynamicDecode = (data: Uint8Array) => unknown; +export interface ProtobufUnknownField { + fieldNumber: number; + wireType: number; + count: number; + totalByteLength: number; +} + +export interface ProtobufUnknownFieldMetadata { + fields: readonly ProtobufUnknownField[]; + totalOccurrences: number; + omittedOccurrences: number; + omittedByteLength: number; +} + +const PROTOBUF_UNKNOWN_FIELDS = Symbol.for('snowluma.proton.unknownFields'); +const EMPTY_UNKNOWN_FIELD_METADATA: ProtobufUnknownFieldMetadata = Object.freeze({ + fields: Object.freeze([]), + totalOccurrences: 0, + omittedOccurrences: 0, + omittedByteLength: 0, +}); + +/** Unknown wire tags retained by generated decoders. The symbol-backed + * metadata is non-enumerable, so decoded object shapes and re-encoding remain + * unchanged while protocol boundaries can make schema drift observable. */ +export function protobuf_getUnknownFields(value: unknown): readonly ProtobufUnknownField[] { + return protobuf_getUnknownFieldMetadata(value).fields; +} + +export function protobuf_getUnknownFieldMetadata(value: unknown): ProtobufUnknownFieldMetadata { + if (typeof value !== 'object' || value === null) return EMPTY_UNKNOWN_FIELD_METADATA; + const metadata = (value as Record)[PROTOBUF_UNKNOWN_FIELDS]; + if (typeof metadata !== 'object' || metadata === null) return EMPTY_UNKNOWN_FIELD_METADATA; + const candidate = metadata as Partial; + if (!Array.isArray(candidate.fields)) return EMPTY_UNKNOWN_FIELD_METADATA; + return { + fields: candidate.fields, + totalOccurrences: candidate.totalOccurrences ?? candidate.fields.length, + omittedOccurrences: candidate.omittedOccurrences ?? 0, + omittedByteLength: candidate.omittedByteLength ?? 0, + }; +} + interface DynamicTypeFns { encode?: DynamicEncode; decode?: DynamicDecode; diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts index 09fc54f8..f546be6f 100644 --- a/packages/proton/test/__tests__/generator.test.ts +++ b/packages/proton/test/__tests__/generator.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect } from 'vitest'; import { analyzeSource } from '../../src/ast/analyzer'; import { generateCode } from '../../src/codegen/generator'; +import { protobuf_getUnknownFieldMetadata } from '../../src/runtime'; import { loadFixture } from '../helpers'; /** Analyze fixture → generate → eval → return encode/decode pair */ @@ -24,6 +25,18 @@ function makeRoundTripFromSchema(schema: string, msgName: string) { return { enc, dec }; } +function encodeVarint32(value: number): number[] { + const bytes: number[] = []; + let remaining = value >>> 0; + do { + let byte = remaining & 0x7f; + remaining >>>= 7; + if (remaining !== 0) byte |= 0x80; + bytes.push(byte); + } while (remaining !== 0); + return bytes; +} + describe('code generator', () => { it('generates encode/decode for simple uint_32', () => { const gen = generateCode(analyzeSource(loadFixture('simple.ts'), 't.ts')); @@ -36,7 +49,7 @@ describe('code generator', () => { it('generates nested message code', () => { const gen = generateCode(analyzeSource(loadFixture('nested.ts'), 't.ts')); expect(gen).toContain('protobuf_encode_Inner('); - expect(gen).toContain('protobuf_decode_Inner(data, offset, offset + _len)'); + expect(gen).toContain('protobuf_decode_Inner(data, offset, _end)'); }); it('round-trip uint_32', () => { @@ -126,6 +139,99 @@ interface Sint32Msg { expect(dec(enc(input))).toEqual(input); }); + it('preserves legacy outbound int_32 bytes while accepting canonical negative varints', () => { + const schema = ` +interface Int32Msg { + value: pb<1, int_32>; + values: pb_repeated<2, int_32>; + forced: pb_optional<3, int_32>; +}`; + const { enc, dec } = makeRoundTripFromSchema(schema, 'Int32Msg'); + const input = { + value: -1, + values: [-2147483648, -1, 0, 1, 2147483647], + forced: -2147483648, + }; + const encoded = enc(input); + + // Keep SnowLuma's established five-byte negative int32 encoding on the + // outbound path until QQ interoperability is verified on a live account. + // The decoder remains liberal and accepts protobuf's canonical ten-byte + // negative form below. + expect(Array.from(encoded.slice(0, 6))).toEqual([ + 0x08, + 0xff, 0xff, 0xff, 0xff, 0x0f, + ]); + expect(dec(encoded)).toEqual(input); + expect(dec(Uint8Array.from([ + 0x08, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, + ])).value).toBe(-1); + }); + + it('rejects malformed length-delimited fields without leaving parent bounds', () => { + const schema = `interface BytesMsg { data: pb<1, bytes>; }`; + const gen = generateCode(analyzeSource(schema, 'BytesMsg.ts')); + const { dec } = makeRoundTripFromSchema(schema, 'BytesMsg'); + + expect(gen).toContain('const _end = __checkedEnd(offset, _len, end);'); + expect(() => dec(Uint8Array.from([0x0a, 0x80]))).toThrow(/truncated uint32 varint/); + expect(() => dec(Uint8Array.from([0x0a, 0x80, 0x80, 0x80, 0x80, 0x10]))).toThrow(/uint32 varint overflow/); + }); + + it('skips unknown groups without decoding their fields into the parent', () => { + const schema = ` +interface Text { str: pb<1, string>; } +interface Elem { text: pb<1, Text>; } +`; + const { dec } = makeRoundTripFromSchema(schema, 'Elem'); + const decoded = dec(Uint8Array.from([ + 0x7b, + 0x0a, 0x08, 0x0a, 0x06, 0x66, 0x6f, 0x72, 0x67, 0x65, 0x64, + 0x7c, + ])); + + expect(decoded.text).toBeNull(); + expect(protobuf_getUnknownFieldMetadata(decoded).fields).toMatchObject([ + { fieldNumber: 15, wireType: 3 }, + ]); + }); + + it('aggregates repeated unknown fields instead of retaining every occurrence', () => { + const { dec } = makeRoundTripFromSchema( + `interface UnknownMsg { known: pb<1, uint_32>; }`, + 'UnknownMsg', + ); + const wire: number[] = []; + const tag = encodeVarint32((60 << 3) | 0); + for (let index = 0; index < 1_000; index++) wire.push(...tag, 0); + + const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire))); + expect(metadata).toEqual({ + fields: [{ fieldNumber: 60, wireType: 0, count: 1_000, totalByteLength: 1_000 }], + totalOccurrences: 1_000, + omittedOccurrences: 0, + omittedByteLength: 0, + }); + }); + + it('caps retained unknown field kinds and summarizes overflow', () => { + const { dec } = makeRoundTripFromSchema( + `interface UnknownKindsMsg { known: pb<1, uint_32>; }`, + 'UnknownKindsMsg', + ); + const wire: number[] = []; + for (let fieldNumber = 2; fieldNumber <= 66; fieldNumber++) { + wire.push(...encodeVarint32((fieldNumber << 3) | 0), 0); + } + + const metadata = protobuf_getUnknownFieldMetadata(dec(Uint8Array.from(wire))); + expect(metadata.fields).toHaveLength(64); + expect(metadata.totalOccurrences).toBe(65); + expect(metadata.omittedOccurrences).toBe(1); + expect(metadata.omittedByteLength).toBe(1); + }); + it('round-trip double as ieee754 number', () => { const schema = ` interface DoubleMsg { diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 964669a4..01253288 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.12.0", + "version": "1.12.1", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 900901d2..369abf7a 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.12.0", + "version": "1.12.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 191f6a8f..ead321fe 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.12.0", + "version": "1.12.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 0f4301ca..45e00764 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.12.0", + "version": "1.12.1", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/websocket/src/extensions.ts b/packages/websocket/src/extensions.ts index 7da9467d..f349a359 100644 --- a/packages/websocket/src/extensions.ts +++ b/packages/websocket/src/extensions.ts @@ -135,11 +135,35 @@ export function compressRaw(data: Buffer): Buffer { } export function decompressRaw(data: Buffer, maxPayload?: number): Buffer { - const inflated = zlib.inflateRawSync(Buffer.concat([data, TRAILER]), { - finishFlush: zlib.constants.Z_SYNC_FLUSH, - }); + let inflated: Buffer; + try { + inflated = zlib.inflateRawSync(Buffer.concat([data, TRAILER]), { + finishFlush: zlib.constants.Z_SYNC_FLUSH, + // A post-inflate length check is too late for a compression bomb: zlib + // has already allocated the expanded buffer by then. Node enforces this + // limit while producing output. maxOutputLength cannot be zero, so keep + // the allocation ceiling at one byte for the maxPayload=0 edge case and + // let the exact check below reject any non-empty message. + ...(maxPayload === undefined + ? {} + : { maxOutputLength: Math.max(1, maxPayload) }), + }); + } catch (cause) { + const zlibError = cause as Error & { code?: string }; + if (maxPayload !== undefined && zlibError.code === 'ERR_BUFFER_TOO_LARGE') { + const err = new Error( + `Message too large after inflate (maxPayload=${maxPayload})`, + { cause }, + ) as Error & { code?: number }; + err.code = 1009; + throw err; + } + throw cause; + } if (maxPayload !== undefined && inflated.length > maxPayload) { - const err = new Error('Message too large after inflate') as Error & { code?: number }; + const err = new Error( + `Message too large after inflate (maxPayload=${maxPayload})`, + ) as Error & { code?: number }; err.code = 1009; throw err; } diff --git a/packages/websocket/tests/extensions.test.ts b/packages/websocket/tests/extensions.test.ts new file mode 100644 index 00000000..f294e236 --- /dev/null +++ b/packages/websocket/tests/extensions.test.ts @@ -0,0 +1,31 @@ +import { describe, expect, it } from 'vitest'; + +import { compressRaw, decompressRaw } from '../src/extensions'; + +describe('permessage-deflate decompression limits', () => { + it('accepts output exactly at maxPayload', () => { + const source = Buffer.alloc(4096, 0x61); + const compressed = compressRaw(source); + + expect(decompressRaw(compressed, source.byteLength)).toEqual(source); + }); + + it('stops a compression bomb during inflate and maps it to WebSocket 1009', () => { + const maxPayload = 4096; + const compressed = compressRaw(Buffer.alloc(1024 * 1024, 0x61)); + expect(compressed.byteLength).toBeLessThan(maxPayload); + + let thrown: unknown; + try { + decompressRaw(compressed, maxPayload); + } catch (error) { + thrown = error; + } + + expect(thrown).toMatchObject({ + code: 1009, + message: `Message too large after inflate (maxPayload=${maxPayload})`, + cause: { code: 'ERR_BUFFER_TOO_LARGE' }, + }); + }); +}); diff --git a/packages/webui/package.json b/packages/webui/package.json index 7430ce2a..1d90ec59 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.12.0", + "version": "1.12.1", "type": "module", "scripts": { "dev": "vite", diff --git a/packages/webui/src/components/config/node-summary-card.tsx b/packages/webui/src/components/config/node-summary-card.tsx index fd45e4bb..d8ee0bb8 100644 --- a/packages/webui/src/components/config/node-summary-card.tsx +++ b/packages/webui/src/components/config/node-summary-card.tsx @@ -17,12 +17,14 @@ const LIVE_STYLE: Record = { ok: 'bg-success/10 text-success', warn: 'bg-warning/10 text-warning', down: 'bg-destructive/10 text-destructive', + degraded: 'bg-destructive/10 text-destructive', disabled: 'bg-muted text-muted-foreground', }; const LIVE_LABEL: Record = { ok: '正常', warn: '注意', down: '异常', + degraded: '应用失败', disabled: '未启用', }; @@ -74,7 +76,9 @@ export function NodeSummaryCard({ {liveStatus && ( {LIVE_LABEL[liveStatus.status]} · {liveStatus.detail} @@ -118,4 +122,3 @@ export function NodeSummaryCard({ ); } - diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index 113b880a..e24bf1e1 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -51,6 +51,7 @@ export function ConfigPage() { cancelSwitch, save, saveStatus, + saveStatusTone, } = useOneBotInstanceConfig(qqList, { selectedUin, onSelectedUinChange: setSelectedUin, @@ -187,6 +188,7 @@ export function ConfigPage() { selectedUin={selectedUin} dirty={dirty} saveStatus={saveStatus} + saveStatusTone={saveStatusTone} onSave={immediateSave} activeTab={activeTab} onCreate={ @@ -262,12 +264,13 @@ interface HeaderBarProps { selectedUin: string; dirty: boolean; saveStatus: string; + saveStatusTone: 'idle' | 'saving' | 'success' | 'warning' | 'error'; onSave: () => void; activeTab: TabKey; onCreate?: () => void; } -function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate }: HeaderBarProps) { +function HeaderBar({ selectedUin, dirty, saveStatus, saveStatusTone, onSave, activeTab, onCreate }: HeaderBarProps) { return (
@@ -279,11 +282,13 @@ function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate
{(saveStatus || dirty) && ( - {saveStatus === '保存中...' ? ( + {saveStatusTone === 'saving' ? ( <>保存中 - ) : saveStatus === '保存成功' ? ( - <>已保存 - ) : saveStatus ? ( + ) : saveStatusTone === 'success' ? ( + <>{saveStatus} + ) : saveStatusTone === 'warning' ? ( + <>{saveStatus} + ) : saveStatusTone === 'error' ? ( <>{saveStatus} ) : ( <>未保存 diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index ccdb1c84..4a46efdb 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -28,6 +28,9 @@ const levelClass: Record = { }; const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error']; +// More than this many new lines in one flush ⇒ firehose: suppress the per-row +// entrance so a 100 line/s stream never strobes (scroll flow + edge fade carry it). +const BURST_MAX = 4; // View presets bundle the display prefs (levels/maxLines/autoScroll/wrap). The // server stores only the id; 'custom' (any hand-tuned state) has no bundle. @@ -92,7 +95,7 @@ function ToolButton({ label, onClick, children, active, danger, disabled }: Tool export function LogsPage() { const api = useApi(); - const { formatClock } = useTheme(); + const { formatClock, appearance } = useTheme(); const { pages, setPages } = useLayout(); const prefs = pages.logs; @@ -106,6 +109,12 @@ export function LogsPage() { const [newKeyword, setNewKeyword] = useState(''); const [newColor, setNewColor] = useState(HIGHLIGHT_COLORS[0].id); const scrollRef = useRef(null); + // Ids currently playing the entrance animation. Populated in the flush (from + // real arrivals, so it's immune to filter/idle churn) and pruned by a 260ms + // timer so a later scroll-into-view never replays. Render reads it directly. + const animatingRef = useRef>(new Set()); + const animTimersRef = useRef>(new Set()); + const motionOnRef = useRef(true); // live motion pref for the async flush closure // maxLines is read through a ref so changing it doesn't re-subscribe the SSE. const maxLines = prefs.maxLines; @@ -152,11 +161,30 @@ export function LogsPage() { // maxLines cap are preserved (a reconnect can replay recent ids). let pending: LogEntry[] = []; let flushTimer: number | null = null; + // Stable Set instances — captured so cleanup clears the very sets the flush + // mutates (satisfies the ref-in-cleanup lint without changing behaviour). + const animating = animatingRef.current; + const animTimers = animTimersRef.current; const flush = () => { flushTimer = null; if (pending.length === 0) return; const batchMap = new Map(pending.map((e) => [e.id, e] as const)); pending = []; + // Mark just-arrived lines for the entrance animation — but suppress a + // firehose batch (> BURST_MAX) so 100 lines/s never strobes; the scroll + // flow + edge fade carry it instead. Populating here (before setLogs) + // means the very first paint of the row already has the class, and the + // 260ms timer bounds it so a later scroll-into-view can't replay it. + if (motionOnRef.current && batchMap.size > 0 && batchMap.size <= BURST_MAX) { + for (const id of batchMap.keys()) { + animatingRef.current.add(id); + const t = window.setTimeout(() => { + animatingRef.current.delete(id); + animTimersRef.current.delete(t); + }, 260); + animTimersRef.current.add(t); + } + } setLogs((prev) => { const kept = prev.length ? prev.filter((it) => !batchMap.has(it.id)) : prev; const merged = kept.length ? [...kept, ...batchMap.values()] : [...batchMap.values()]; @@ -177,6 +205,9 @@ export function LogsPage() { return () => { dispose(); if (flushTimer != null) clearTimeout(flushTimer); + for (const t of animTimers) clearTimeout(t); + animTimers.clear(); + animating.clear(); }; }, [api]); @@ -229,6 +260,44 @@ export function LogsPage() { // eslint-disable-next-line react-hooks/exhaustive-deps }, [logs, filtered.length, prefs.autoScroll, prefs.wrap]); + // Entrance detection lives in the flush (real arrivals only). Here we just keep + // the flush's motion read live, since it was captured once in the [api] effect. + const motionOn = !appearance.reduceMotion && !appearance.disableMotion; + useEffect(() => { motionOnRef.current = motionOn; }, [motionOn]); + + // Scroll-position-aware edge fade: fade a boundary only when hidden content + // actually exists past it, so a fully-scrolled top/bottom row is never dimmed. + const [edges, setEdges] = useState({ top: false, bottom: false }); + const recomputeEdges = useCallback(() => { + const el = scrollRef.current; + if (!el) return; + const top = el.scrollTop > 4; // small hysteresis so a 1px nudge can't flicker the fade + const bottom = el.scrollTop + el.clientHeight < el.scrollHeight - 1; + setEdges((p) => (p.top === top && p.bottom === bottom ? p : { top, bottom })); + }, []); + useEffect(() => { + const el = scrollRef.current; + if (!el) return; + recomputeEdges(); + el.addEventListener('scroll', recomputeEdges, { passive: true }); + // A ResizeObserver on the viewport catches height changes the scroll/content + // effects miss — e.g. the options panel expanding above the list, or a window + // resize — in one listener. + const ro = new ResizeObserver(() => recomputeEdges()); + ro.observe(el); + return () => { + el.removeEventListener('scroll', recomputeEdges); + ro.disconnect(); + }; + }, [recomputeEdges]); + // New lines / wrap changes shift the overflow, so recheck the edges then too. + useEffect(() => { recomputeEdges(); }, [filtered.length, prefs.wrap, recomputeEdges]); + const maskCls = appearance.disableMotion ? undefined + : edges.top && edges.bottom ? 'log-fade-both' + : edges.top ? 'log-fade-top' + : edges.bottom ? 'log-fade-bottom' + : undefined; + // Any hand edit to the bundled prefs drops the active preset to 'custom'. const toggleLevel = (lv: LogLevel) => { const next = new Set(enabled); @@ -537,7 +606,7 @@ export function LogsPage() { 消息
)} - + div]:!block', maskCls)}>
{filtered.length === 0 ? (
@@ -560,34 +629,46 @@ export function LogsPage() { const log = filtered[vRow.index]; if (!log) return null; // guard a transient count/measurement skew const hl = matchHighlight(log.message, prefs.highlightRules); + // Entrance is decided entirely by animatingRef (populated in + // the flush from real arrivals, pruned at 260ms), so it fires + // on the first paint, never replays on scroll-into-view, and + // is immune to filter/idle churn. Outer = positioning + + // measurement (its translateY); inner = visual row + the + // transform-based entrance, kept separate so they never collide. + const entering = animatingRef.current.has(log.id); return (
-
- {formatClock(log.time)} - - - {log.level.toUpperCase()} - - [{log.scope}] -
- - {log.req !== undefined && ( - #{log.req} +
+ style={hl ? { boxShadow: `inset 3px 0 0 ${hl}`, backgroundColor: `color-mix(in oklab, ${hl} 8%, transparent)` } : undefined} + > +
+ {formatClock(log.time)} + + + {log.level.toUpperCase()} + + [{log.scope}] +
+ + {log.req !== undefined && ( + #{log.req} + )} + {log.message} + +
); })} diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index 3719f8a1..008df0ef 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -731,17 +731,24 @@ const CONN_STATUS_STYLE: Record = { ok: 'bg-success/10 text-success', warn: 'bg-warning/10 text-warning', down: 'bg-destructive/10 text-destructive', + degraded: 'bg-destructive/10 text-destructive', disabled: 'bg-muted text-muted-foreground', }; const CONN_STATUS_LABEL: Record = { - ok: '正常', warn: '注意', down: '异常', disabled: '未启用', + ok: '正常', warn: '注意', down: '异常', degraded: '应用失败', disabled: '未启用', }; const ADAPTER_KIND_LABEL: Record = { httpServer: 'HTTP 服务端', httpClient: 'HTTP 上报', wsServer: 'WS 服务端', wsClient: 'WS 客户端', }; // Worst-status-first ordering (down → warn → disabled → ok). -const CONN_STATUS_RANK: Record = { down: 0, warn: 1, disabled: 2, ok: 3 }; +const CONN_STATUS_RANK: Record = { + degraded: 0, + down: 1, + warn: 2, + disabled: 3, + ok: 4, +}; function ConnectionsBlock({ config }: { config: ConnectionsConfig }) { const { connections } = useAppState(); @@ -804,6 +811,11 @@ function ConnectionsBlock({ config }: { config: ConnectionsConfig }) { {ADAPTER_KIND_LABEL[adp.kind]}
{adp.detail}
+ {adp.lastError && adp.lastErrorAt && ( +
+ {new Date(adp.lastErrorAt).toLocaleString()} · {adp.lastError} +
+ )}
))} diff --git a/packages/webui/src/hooks/use-onebot-instance-config.ts b/packages/webui/src/hooks/use-onebot-instance-config.ts index b3d61031..202b9a15 100644 --- a/packages/webui/src/hooks/use-onebot-instance-config.ts +++ b/packages/webui/src/hooks/use-onebot-instance-config.ts @@ -33,6 +33,7 @@ export interface UseOneBotInstanceConfig { */ save: (override?: OneBotConfig) => Promise; saveStatus: string; + saveStatusTone: 'idle' | 'saving' | 'success' | 'warning' | 'error'; } const CLEAR_SAVE_STATUS_MS = 3000; @@ -53,8 +54,13 @@ export function useOneBotInstanceConfig( const [config, setConfigState] = useState(null); const [savedSnapshot, setSavedSnapshot] = useState(null); const [saveStatus, setSaveStatus] = useState(''); + const [saveStatusTone, setSaveStatusTone] = useState('idle'); const [pendingSwitchUin, setPendingSwitchUin] = useState(null); const clearTimerRef = useRef(null); + const editRevisionRef = useRef(0); + const saveGenerationRef = useRef(0); + const selectedUinRef = useRef(selectedUin); + selectedUinRef.current = selectedUin; // Auto-select first account when none is selected yet. useEffect(() => { @@ -63,6 +69,14 @@ export function useOneBotInstanceConfig( // Load on UIN change. The api client already runs normalizeOneBotConfig. useEffect(() => { + editRevisionRef.current += 1; + saveGenerationRef.current += 1; + if (clearTimerRef.current != null) { + window.clearTimeout(clearTimerRef.current); + clearTimerRef.current = null; + } + setSaveStatus(''); + setSaveStatusTone('idle'); if (!selectedUin) { setConfigState(null); setSavedSnapshot(null); @@ -73,6 +87,7 @@ export function useOneBotInstanceConfig( try { const loaded = await api.config.get(selectedUin); if (cancelled) return; + editRevisionRef.current += 1; setConfigState(loaded); setSavedSnapshot(JSON.stringify(loaded)); } catch (e) { @@ -96,7 +111,10 @@ export function useOneBotInstanceConfig( return JSON.stringify(config) !== savedSnapshot; }, [config, savedSnapshot]); - const setConfig = useCallback((next: OneBotConfig) => setConfigState(next), []); + const setConfig = useCallback((next: OneBotConfig) => { + editRevisionRef.current += 1; + setConfigState(next); + }, []); const requestSwitchUin = useCallback( (uin: string) => { @@ -115,27 +133,54 @@ export function useOneBotInstanceConfig( const cancelSwitch = useCallback(() => setPendingSwitchUin(null), []); - const scheduleStatusClear = useCallback(() => { + const scheduleStatusClear = useCallback((uin: string, generation: number) => { if (clearTimerRef.current != null) window.clearTimeout(clearTimerRef.current); clearTimerRef.current = window.setTimeout(() => { - setSaveStatus(''); clearTimerRef.current = null; + if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) return; + setSaveStatus(''); + setSaveStatusTone('idle'); }, CLEAR_SAVE_STATUS_MS); }, []); const save = useCallback(async (override?: OneBotConfig) => { const target = override ?? config; if (!selectedUin || !target) return; + const uin = selectedUin; + const editRevision = editRevisionRef.current; + const generation = ++saveGenerationRef.current; setSaveStatus('保存中...'); + setSaveStatusTone('saving'); try { - const serverView = await api.config.save(selectedUin, target); - setConfigState(serverView); - setSavedSnapshot(JSON.stringify(serverView)); - setSaveStatus('保存成功'); + const result = await api.config.save(uin, target); + if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) return; + setSavedSnapshot(JSON.stringify(result.config)); + if (editRevisionRef.current === editRevision) { + setConfigState(result.config); + } else { + setSaveStatus('上一版本已保存,当前修改仍待保存'); + setSaveStatusTone('warning'); + return; + } + if (!result.online) { + setSaveStatus('保存成功;当前离线,将在下次连接时应用'); + setSaveStatusTone('warning'); + } else if (result.applied) { + setSaveStatus('保存成功,热重载完成'); + setSaveStatusTone('success'); + } else { + const first = result.errors[0]?.message; + setSaveStatus(`保存成功,但热重载失败${first ? `:${first}` : ''}`); + setSaveStatusTone('warning'); + } } catch (e) { + if (selectedUinRef.current !== uin || saveGenerationRef.current !== generation) return; setSaveStatus(`保存失败:${e instanceof Error ? e.message : '未知错误'}`); + setSaveStatusTone('error'); } finally { - scheduleStatusClear(); + if (selectedUinRef.current === uin && saveGenerationRef.current === generation) { + scheduleStatusClear(uin, generation); + } } }, [api, selectedUin, config, scheduleStatusClear]); @@ -150,5 +195,6 @@ export function useOneBotInstanceConfig( cancelSwitch, save, saveStatus, + saveStatusTone, }; } diff --git a/packages/webui/src/index.css b/packages/webui/src/index.css index b67b6885..3069a564 100644 --- a/packages/webui/src/index.css +++ b/packages/webui/src/index.css @@ -237,6 +237,38 @@ html[data-kiosk="1"] [data-kiosk-hide] { display: none !important; } +/* Log stream row entrance — a subtle fade + rise for a genuinely new tail line. + transform+opacity only (composited, cheap at high rate); the virtual row's own + translateY positioning lives on the OUTER wrapper, so this INNER animation + never fights it or perturbs measureElement. Applied only to real arrivals and + auto-suppressed in bursts; gated in JS on reduce/disable-motion, and the rules + below also neutralise it. */ +@keyframes log-row-in { + from { opacity: 0; transform: translateY(6px); } + to { opacity: 1; transform: translateY(0); } +} +.log-row-in { + animation: log-row-in 200ms cubic-bezier(0.16, 1, 0.3, 1); +} + +/* Soft edge fade for the log scroll viewport — rows dissolve at a boundary as + they scroll past it (Apple-style). Scroll-position-aware: each edge only fades + when there is actually hidden content in that direction, so a fully-scrolled + top/bottom row is never dimmed (readability). A static mask, not motion: kept + under reduce-motion, dropped only on the hard 关闭全部动效 switch. */ +.log-fade-top { + -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 14px, #000 100%); + mask-image: linear-gradient(to bottom, transparent 0, #000 14px, #000 100%); +} +.log-fade-bottom { + -webkit-mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 18px), transparent 100%); + mask-image: linear-gradient(to bottom, #000 0, #000 calc(100% - 18px), transparent 100%); +} +.log-fade-both { + -webkit-mask-image: linear-gradient(to bottom, transparent 0, #000 14px, #000 calc(100% - 18px), transparent 100%); + mask-image: linear-gradient(to bottom, transparent 0, #000 14px, #000 calc(100% - 18px), transparent 100%); +} + /* Reduce motion: a CSS fallback for non-Framer transitions/animations. Framer Motion itself is handled by . */ html[data-reduce-motion="1"] *, diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 352ad8fb..6d483132 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -86,14 +86,49 @@ class HttpApiClient implements ApiClient { }, save: async (uin, config) => { const url = `/api/config/${encodeURIComponent(uin)}`; - // POST returns { success, reloaded, message } — no config body. To - // honour the "save returns canonical server view" contract, refetch - // after a successful POST. - await this.fetchJson(url, { + const result = await this.fetchJson<{ + success?: boolean; + saved?: boolean; + applied?: boolean; + online?: boolean; + reloaded?: boolean; + errors?: Array<{ + name: string; + kind?: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient'; + phase: string; + message: string; + at: number; + restored?: boolean; + }>; + config?: unknown; + message?: string; + }>(url, { method: 'POST', body: JSON.stringify(config), }); - return this.config.get(uin); + // Refetch the canonical persisted view after the save. Runtime apply + // is a separate fact and is preserved alongside that config. + let canonical = result.config === undefined + ? null + : normalizeOneBotConfig(result.config); + if (canonical === null) { + try { + canonical = await this.config.get(uin); + } catch (error) { + // Legacy servers omit `config`. Their POST still confirmed the + // save, so a follow-up GET failure must not become "保存失败". + console.warn('config saved but canonical refetch failed', error); + canonical = config; + } + } + return { + config: canonical, + saved: result.saved ?? result.success === true, + applied: result.applied ?? result.reloaded === true, + online: result.online ?? result.reloaded === true, + errors: Array.isArray(result.errors) ? result.errors : [], + message: result.message ?? '配置保存成功', + }; }, }; diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index cb80c92e..666a47b4 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -69,6 +69,24 @@ export type ProcessActionResult = { process?: HookProcessInfo & { error?: string }; }; +export interface ConfigApplyError { + name: string; + kind?: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient'; + phase: string; + message: string; + at: number; + restored?: boolean; +} + +export interface ConfigSaveResult { + config: OneBotConfig; + saved: boolean; + applied: boolean; + online: boolean; + errors: ConfigApplyError[]; + message: string; +} + export type StreamStatus = 'open' | 'reconnecting' | 'closed'; export interface LogsStreamOptions { @@ -134,7 +152,7 @@ export interface ApiClient { // ---- OneBotInstance per-UIN config ---- config: { get(uin: string): Promise; - save(uin: string, config: OneBotConfig): Promise; + save(uin: string, config: OneBotConfig): Promise; }; // ---- WebUI listener self-config (port / host / TLS / trust-proxy) ---- diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index e0ee9406..83bbb0a3 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -27,13 +27,15 @@ export interface QQInfo { nickname: string; } -export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled'; +export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled' | 'degraded'; export interface AdapterStatus { name: string; kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient'; status: AdapterStatusLevel; detail: string; + lastError?: string; + lastErrorAt?: number; } export interface AccountConnections {