Merge pull request #214 from SnowLuma/dev
chore: promote dev → main (c04864d)
This commit is contained in:
137 files changed
+11569
-1468
No files matched your search
+1
-1
@@ -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",
|
||||
|
||||
@@ -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).",
|
||||
|
||||
@@ -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).",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<DownloadRKeyInfo[]> {
|
||||
const resp = await FetchDownloadRkeys.invoke(this.ctx);
|
||||
|
||||
|
||||
@@ -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<string, ForwardNodePayload[]>();
|
||||
|
||||
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<string> {
|
||||
// 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<MessageElement> {
|
||||
): Promise<MessageElementOf<'file'>> {
|
||||
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<LongMsgResult>(inflate);
|
||||
const actions = Array.isArray(longMsg?.action) ? longMsg!.action! : [];
|
||||
const mainAction = actions.find(item => item?.actionCommand === 'MultiMsg');
|
||||
|
||||
@@ -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<SendMessageReceipt> {
|
||||
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<SendMessageRequest>({
|
||||
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<SendMessageResponse>(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.
|
||||
*
|
||||
|
||||
@@ -19,10 +19,15 @@ const log = createLogger('Bridge');
|
||||
export class Bridge implements BridgeInterface {
|
||||
readonly identity: IdentityService;
|
||||
private pids_ = new Set<number>();
|
||||
/** 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<number, PacketSender>();
|
||||
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<string, UploadedFileMeta>();
|
||||
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<string> {
|
||||
return this.identity.resolveUid(uin, groupId);
|
||||
}
|
||||
@@ -203,4 +312,3 @@ export interface ClientKeyInfo {
|
||||
}
|
||||
export { AiVoiceChatType };
|
||||
export type { AiVoiceCategory, StrangerStatus };
|
||||
|
||||
@@ -17,7 +17,6 @@ const log = createLogger('Bridge');
|
||||
export class BridgeManager {
|
||||
private sessions_ = new Map<string, QQSession>();
|
||||
private pidToUin_ = new Map<number, string>();
|
||||
private pidPacketClients_ = new Map<number, PacketSender>();
|
||||
|
||||
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 };
|
||||
|
||||
@@ -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'));
|
||||
|
||||
@@ -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: '配置已保存,但热重载失败,请检查服务器日志。',
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -51,7 +51,11 @@ function recvLongMsgResp(bodies: PushMsgBody[]) {
|
||||
action: [{ actionCommand: 'MultiMsg', actionData: { msgBody: bodies } }],
|
||||
};
|
||||
const gz = gzipSync(Buffer.from(protobuf_encode<LongMsgResult>(longMsg)));
|
||||
const resp = protobuf_encode<RecvLongMsgResp>({ result: { payload: new Uint8Array(gz) } });
|
||||
return recvCompressedLongMsgResp(gz);
|
||||
}
|
||||
|
||||
function recvCompressedLongMsgResp(payload: Uint8Array) {
|
||||
const resp = protobuf_encode<RecvLongMsgResp>({ 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
|
||||
|
||||
@@ -143,12 +143,11 @@ describe('apis/group-admin', () => {
|
||||
expect(nameEnv.body).toMatchObject({ groupUin: 1, body: { targetName: 'newName' } });
|
||||
|
||||
const titleEnv = protobuf_decode<OidbBase<OidbSpecialTitle>>(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<OidbBase<Oidb0xf16Req>>(bridge.sendRawPacket.mock.calls[3]![1]);
|
||||
expect(remarkEnv.body?.inner).toMatchObject({ groupId: 1n, remark: 'newRemark' });
|
||||
|
||||
@@ -17,7 +17,7 @@ function makeFriendMessage(): FriendMessage {
|
||||
|
||||
function makeGroupMessage(): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
kind: 'group_message', groupName: '',
|
||||
time: 1700000000,
|
||||
selfUin: 10001,
|
||||
groupId: 99999,
|
||||
|
||||
@@ -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<PacketSender['sendPacket']>(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',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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: '',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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<typeof createConnectionMock>;
|
||||
});
|
||||
// 安装一个 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<typeof createConnectionMock>;
|
||||
});
|
||||
}
|
||||
|
||||
// 顺序读取记录: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<Uint8Array> {
|
||||
this.inFlight += 1;
|
||||
this.reads.push({ offset, length });
|
||||
await Promise.resolve();
|
||||
this.inFlight -= 1;
|
||||
return new Uint8Array(length);
|
||||
}
|
||||
async close(): Promise<void> {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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');
|
||||
|
||||
+66
-8
@@ -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.
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
+743
-8
@@ -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<string, unknown>): Promise<OneBotEnvelope>;
|
||||
/** Execute a Stream Action over the HTTP multi-frame transport. */
|
||||
callStream(action: string, params: Record<string, unknown>, options?: StreamCallOptions): Promise<StreamCallResult>;
|
||||
}
|
||||
|
||||
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<string, Map<string, DownloadReservation>>();
|
||||
|
||||
function reserveDownloadQuota(
|
||||
streamDir: string,
|
||||
partPath: string,
|
||||
finalPath: string,
|
||||
bytes: number,
|
||||
quotaBytes: number,
|
||||
): DownloadReservation {
|
||||
const active = downloadReservations.get(streamDir) ?? new Map<string, DownloadReservation>();
|
||||
const activePaths = new Set<string>();
|
||||
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<string, unknown> | undefined {
|
||||
return value && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: 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<void> {
|
||||
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<string, unknown> | 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<ReturnType<ReadableStreamDefaultReader<Uint8Array>['read']>>;
|
||||
|
||||
async function readWithIdleTimeout(
|
||||
reader: ReadableStreamDefaultReader<Uint8Array>,
|
||||
timeoutMs: number,
|
||||
callerSignal: AbortSignal | undefined,
|
||||
action: string,
|
||||
frameIndex: number,
|
||||
): Promise<ByteStreamReadResult> {
|
||||
if (callerSignal?.aborted) {
|
||||
throw new Error(`action ${action} stream read frame ${frameIndex}: cancelled: ${abortReason(callerSignal)}`);
|
||||
}
|
||||
return new Promise<ByteStreamReadResult>((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<string, unknown>,
|
||||
maxStreamBytes: number,
|
||||
callerSignal: AbortSignal | undefined,
|
||||
post: (params: Record<string, unknown>, signal?: AbortSignal) => Promise<StreamCallResult>,
|
||||
): Promise<UploadStreamResult> {
|
||||
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<string, string> = {
|
||||
'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<void> => {
|
||||
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;
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
+18
-13
@@ -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<string, unknown>;
|
||||
return callTool(req.params.name, args, { mode, client });
|
||||
return callTool(req.params.name, args, { mode, client, signal: extra.signal });
|
||||
});
|
||||
|
||||
server.setRequestHandler(ListResourcesRequestSchema, async () => ({
|
||||
|
||||
@@ -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<string, CatalogAction>();
|
||||
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<string, unknown>, ctx: CallCtx): Promise<ToolResult> {
|
||||
@@ -173,10 +192,36 @@ async function execute(args: Record<string, unknown>, ctx: CallCtx, kind: 'read'
|
||||
args.params && typeof args.params === 'object' && !Array.isArray(args.params)
|
||||
? (args.params as Record<string, unknown>)
|
||||
: {};
|
||||
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<string, unknown>;
|
||||
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)}`);
|
||||
}
|
||||
}
|
||||
@@ -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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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<Record<string, any>> = [];
|
||||
const fakeFetch = (async (_url: unknown, init: RequestInit) => {
|
||||
const request = JSON.parse(String(init.body)) as Record<string, any>;
|
||||
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<Record<string, any>> = [];
|
||||
const fakeFetch = (async (_url: unknown, init: RequestInit) => {
|
||||
const request = JSON.parse(String(init.body)) as Record<string, any>;
|
||||
requests.push(request);
|
||||
let frame: Record<string, unknown>;
|
||||
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<Record<string, any>> = [];
|
||||
const fakeFetch = (async (_url: unknown, init: RequestInit) => {
|
||||
const request = JSON.parse(String(init.body)) as Record<string, any>;
|
||||
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<string, any>;
|
||||
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<Uint8Array>({
|
||||
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<void>((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<Uint8Array>({
|
||||
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<Uint8Array>({
|
||||
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<Record<string, any>> = [];
|
||||
const signals: AbortSignal[] = [];
|
||||
const fakeFetch = (async (_url: unknown, init: RequestInit) => {
|
||||
const request = JSON.parse(String(init.body)) as Record<string, any>;
|
||||
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<Uint8Array>({ 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<void>((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<Response>((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<void>((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<Uint8Array>({
|
||||
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<void>((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']);
|
||||
});
|
||||
});
|
||||
@@ -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<ReturnType<typeof callTool>>;
|
||||
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<string, unknown>) => OneBotEnvelope): ActionClient {
|
||||
function fakeClient(
|
||||
impl?: (action: string, params: Record<string, unknown>) => OneBotEnvelope,
|
||||
streamImpl?: (action: string, params: Record<string, unknown>, 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<string, unknown>; 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);
|
||||
});
|
||||
});
|
||||
@@ -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.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
|
||||
|
||||
@@ -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。`,
|
||||
'',
|
||||
|
||||
@@ -447,12 +447,18 @@ type Handler = (params: JsonObject) => Promise<ApiResponse>;
|
||||
* 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<S extends Spec> 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<InferParams<S>>;
|
||||
@@ -482,7 +488,7 @@ interface ActionDef<S extends Spec> {
|
||||
const wording = (e: Err): string => (e.field ? `${e.field}: ${e.reason}` : e.reason);
|
||||
|
||||
export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
||||
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<InferParams<S>>)
|
||||
: [];
|
||||
@@ -510,6 +516,7 @@ export function defineAction<S extends Spec>(def: ActionDef<S>): ActionSpec<S> {
|
||||
};
|
||||
|
||||
return {
|
||||
kind: 'normal',
|
||||
names,
|
||||
params: def.params,
|
||||
parse,
|
||||
@@ -567,7 +574,8 @@ interface StreamActionDef<S extends Spec> {
|
||||
}
|
||||
|
||||
export interface StreamActionSpec<S extends Spec> extends RegisteredActionSpec {
|
||||
readonly names: string[];
|
||||
readonly kind: 'stream';
|
||||
readonly names: readonly string[];
|
||||
readonly params: S;
|
||||
parse(raw: JsonObject): CoerceResult<InferParams<S>>;
|
||||
}
|
||||
@@ -587,6 +595,7 @@ export function defineStreamAction<S extends Spec>(def: StreamActionDef<S>): Str
|
||||
});
|
||||
|
||||
return {
|
||||
kind: 'stream',
|
||||
names: base.names,
|
||||
params: def.params,
|
||||
parse: base.parse,
|
||||
|
||||
@@ -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<string, CompiledActionName>();
|
||||
|
||||
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);
|
||||
@@ -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 });
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -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 = [
|
||||
},
|
||||
}),
|
||||
];
|
||||
|
||||
@@ -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<MessageSendResult>;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise<MessageSendResult>;
|
||||
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
|
||||
canSendImage: () => boolean;
|
||||
@@ -75,6 +80,12 @@ export interface ApiActionContext {
|
||||
|
||||
type ActionHandler = (params: JsonObject, sink?: StreamSink) => Promise<import('./types').ApiResponse>;
|
||||
|
||||
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<string, ActionHandler>();
|
||||
/** 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<string>();
|
||||
/** 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<string, RegisteredHandler>();
|
||||
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<string, unknown> | 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<string, unknown> | 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<import('./types').ApiResponse> {
|
||||
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<void>,
|
||||
isAlive?: () => boolean,
|
||||
): Promise<void> {
|
||||
const bad = (): void => { void emit(JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'))); };
|
||||
if (!rawRequest.trim()) { bad(); return; }
|
||||
const bad = (): Promise<void> => 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;
|
||||
}
|
||||
|
||||
|
||||
+262
-16
@@ -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<string, keyof OneBotNetworks>();
|
||||
const serverBindings = new Map<string, string>();
|
||||
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<string, keyof OneBotNetworks>,
|
||||
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<string, string>): 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<string>): 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 {
|
||||
|
||||
@@ -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 MessageElementType> = T extends 'image'
|
||||
? MessageElementOf<'image'> | MessageElementOf<'mface'>
|
||||
: MessageElementOf<T>;
|
||||
|
||||
export interface ElementCodec<T extends MessageElementType = MessageElementType> {
|
||||
/** S 收·转:MessageElement → OneBot 段。 */
|
||||
toSegment?: (element: MessageElement, ctx: ToSegmentContext) => Promise<JsonObject>;
|
||||
/** P 发·解:OneBot 段 data → MessageElement(null = 丢弃该段)。 */
|
||||
fromSegment?: (data: Record<string, unknown>, options?: ParseMessageOptions) => Promise<MessageElement | null>;
|
||||
toSegment?: (element: MessageElementOf<T>, ctx: ToSegmentContext) => Promise<JsonObject>;
|
||||
/** P 发·解:OneBot 段 data → MessageElement(null = 无法构造,parser 会 typed reject)。 */
|
||||
fromSegment?: (data: Record<string, unknown>, options?: ParseMessageOptions) => Promise<CodecOutput<T> | null>;
|
||||
}
|
||||
|
||||
type ElementCodecMap = Partial<{
|
||||
readonly [T in MessageElementType]: ElementCodec<T>;
|
||||
}>;
|
||||
|
||||
// ── 共享低层工具(原在 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<string, unknown>): MessageElement {
|
||||
export function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElementOf<'mface'> {
|
||||
return {
|
||||
type: 'mface',
|
||||
text: String(data.summary ?? data.name ?? ''),
|
||||
@@ -95,7 +131,7 @@ export function pickMediaSource(data: Record<string, unknown>): string {
|
||||
|
||||
// ── codec 表:一种元素类型一条,键即 element.type(收·转)/ 段 type(发·解,二者同名)──
|
||||
|
||||
export const ELEMENT_CODECS: Record<string, ElementCodec> = {
|
||||
export const ELEMENT_CODECS = {
|
||||
text: {
|
||||
async toSegment(element) {
|
||||
return { type: 'text', data: { text: element.text ?? '' } };
|
||||
@@ -190,6 +226,7 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
|
||||
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<string, ElementCodec> = {
|
||||
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<string, ElementCodec> = {
|
||||
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<string, ElementCodec> = {
|
||||
};
|
||||
},
|
||||
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<string, ElementCodec> = {
|
||||
};
|
||||
},
|
||||
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<string, ElementCodec> = {
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
} 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<string, ElementCodec>)[type];
|
||||
}
|
||||
@@ -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),
|
||||
|
||||
@@ -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<JsonObject> {
|
||||
// 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: {} };
|
||||
}
|
||||
@@ -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<void>;
|
||||
}
|
||||
|
||||
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<Promise<void>>();
|
||||
let accepting = true;
|
||||
|
||||
const track = (
|
||||
kind: QQEventVariant['kind'],
|
||||
start: () => void | Promise<void>,
|
||||
): Promise<void> => {
|
||||
if (!accepting) return Promise.resolve();
|
||||
let operation: Promise<void>;
|
||||
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<void> {
|
||||
// `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)`]);
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
|
||||
+150
-85
@@ -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<NetworkReconcileResult>;
|
||||
private lifecycleTail: Promise<void>;
|
||||
private readonly rkeyCache: RKeyCache;
|
||||
private readonly ctx: OneBotInstanceContext;
|
||||
/** Process-uptime baseline for the `#sl` status reply. */
|
||||
private readonly startedAt = Date.now();
|
||||
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
|
||||
private readonly statusCommandCooldown = new Map<string, number>();
|
||||
private disposeEventPipeline: (() => void) | null = null;
|
||||
private eventPipeline: EventPipelineHandle | null = null;
|
||||
private eventPipelineDrain: Promise<void> = Promise.resolve();
|
||||
private disposePromise: Promise<NetworkShutdownResult> | null = null;
|
||||
private disposeRequested = false;
|
||||
private acceptingActions = true;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private readonly storeCloseState = {
|
||||
message: false,
|
||||
media: false,
|
||||
reaction: false,
|
||||
};
|
||||
|
||||
private readonly pids = new Set<number>();
|
||||
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<ApiResponse> {
|
||||
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<void>,
|
||||
isAlive?: () => boolean,
|
||||
): Promise<void> {
|
||||
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<NetworkReconcileResult> {
|
||||
return this.networkReady;
|
||||
}
|
||||
|
||||
reloadConfig(config: OneBotConfig): Promise<NetworkReconcileResult> {
|
||||
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<NetworkShutdownResult> {
|
||||
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<void> {
|
||||
const ctx = this.buildNetworkContext();
|
||||
const desired = new Map<string, NetworkBase>();
|
||||
const factories = new Map<string, () => void>();
|
||||
private enqueueLifecycle<T>(operation: () => Promise<T>): Promise<T> {
|
||||
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<T>(label: string, start: () => Promise<T>): Promise<T> {
|
||||
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<T>;
|
||||
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<T>(label: string, error: unknown): Promise<T> {
|
||||
const rejected = Promise.reject<T>(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 {
|
||||
|
||||
+192
-16
@@ -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<string, OneBotInstance>();
|
||||
private readonly pendingLifecycle = new Set<Promise<void>>();
|
||||
private readonly retiringInstances = new Set<OneBotInstance>();
|
||||
private readonly lifecycleFailures: Array<{
|
||||
label: string;
|
||||
error: unknown;
|
||||
instances?: Set<OneBotInstance>;
|
||||
}> = [];
|
||||
private readonly pendingStarts = new Map<string, { bridge: BridgeInterface; cancelled: boolean }>();
|
||||
private disposePromise: Promise<void> | 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<ConfigApplyResult> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<unknown>,
|
||||
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<void> {
|
||||
|
||||
@@ -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<string, string> {
|
||||
const params: Record<string, string> = {};
|
||||
@@ -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<string, unknown>): 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<string, unknown>,
|
||||
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<string, unknown>,
|
||||
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<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
|
||||
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<string, unknow
|
||||
prompt: title,
|
||||
meta: { news: { title, desc: content, jumpUrl: url, preview: image } },
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
return validatedOutboundElement({ type: 'json', text: jsonData });
|
||||
}
|
||||
case 'music': {
|
||||
// Music share — uses external signing service (NapCat-compatible)
|
||||
const musicType = String(data.type ?? '');
|
||||
const musicType = requireNonEmptyStringField(normalizedType, data, 'type');
|
||||
// Non-custom platform names are deliberately open: musicSignUrl is
|
||||
// configurable and private signers may support platforms beyond the
|
||||
// built-in NapCat set. Their executable contract is non-empty type+id.
|
||||
if (musicType === 'custom') {
|
||||
requireNonEmptyStringField(normalizedType, data, 'url');
|
||||
requireNonEmptyStringField(normalizedType, data, 'audio');
|
||||
requireNonEmptyStringField(normalizedType, data, 'title');
|
||||
} else if (data.id === undefined || data.id === null || String(data.id).trim() === '') {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
'message segment "music" requires field "id" for a platform card',
|
||||
normalizedType,
|
||||
'id',
|
||||
);
|
||||
}
|
||||
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
|
||||
try {
|
||||
let postData: Record<string, unknown>;
|
||||
@@ -107,7 +204,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
});
|
||||
if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`);
|
||||
const musicJson = await resp.text();
|
||||
return { type: 'json', text: musicJson };
|
||||
return validatedOutboundElement({ type: 'json', text: musicJson });
|
||||
} catch (e) {
|
||||
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
|
||||
// Fallback: build a basic card locally
|
||||
@@ -126,13 +223,13 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
},
|
||||
},
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
return validatedOutboundElement({ type: 'json', text: jsonData });
|
||||
}
|
||||
}
|
||||
case 'location': {
|
||||
// Location — map to json card
|
||||
const lat = String(data.lat ?? '');
|
||||
const lon = String(data.lon ?? '');
|
||||
const lat = requireCoordinate(data, 'lat');
|
||||
const lon = requireCoordinate(data, 'lon');
|
||||
const title = String(data.title ?? '位置');
|
||||
const content = String(data.content ?? `${lat},${lon}`);
|
||||
const jsonData = JSON.stringify({
|
||||
@@ -141,18 +238,34 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
prompt: `[位置]${title}`,
|
||||
meta: { Location: { lat, lng: lon, title, address: content } },
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
return validatedOutboundElement({ type: 'json', text: jsonData });
|
||||
}
|
||||
case 'contact': {
|
||||
// Contact card — map to json card
|
||||
const contactType = String(data.type ?? 'qq');
|
||||
const contactId = String(data.id ?? '');
|
||||
const contactType = requireNonEmptyStringField(normalizedType, data, 'type');
|
||||
if (contactType !== 'qq' && contactType !== 'group') {
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
'message segment "contact" field "type" must be "qq" or "group"',
|
||||
normalizedType,
|
||||
'type',
|
||||
);
|
||||
}
|
||||
const contactId = String(data.id ?? '').trim();
|
||||
const numericId = intOr(contactId, 0);
|
||||
if (numericId <= 0) {
|
||||
throw new MessageElementValidationError(
|
||||
'INVALID_FIELD',
|
||||
'message segment "contact" field "id" must be a positive integer',
|
||||
normalizedType,
|
||||
'id',
|
||||
);
|
||||
}
|
||||
const normalizedContactType = contactType.trim().toLowerCase();
|
||||
if (numericId > 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<string, unknow
|
||||
prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`,
|
||||
meta: { contact: { type: contactType, id: contactId } },
|
||||
});
|
||||
return { type: 'json', text: jsonData };
|
||||
return validatedOutboundElement({ type: 'json', text: jsonData });
|
||||
}
|
||||
case 'rps': {
|
||||
// Rock-paper-scissors — map to dice-like face
|
||||
return { type: 'face', faceId: 359 };
|
||||
return validatedOutboundElement({ type: 'face', faceId: 359 });
|
||||
}
|
||||
case 'dice': {
|
||||
// Dice — map to dice face
|
||||
return { type: 'face', faceId: 358 };
|
||||
return validatedOutboundElement({ type: 'face', faceId: 358 });
|
||||
}
|
||||
case 'shake': {
|
||||
// Window shake — map to poke
|
||||
return { type: 'poke', faceId: 1 };
|
||||
// Window shake normalizes to poke, then the W-direction guard returns the
|
||||
// same explicit "use the dedicated poke Action" validation error.
|
||||
return validatedOutboundElement({ type: 'poke', subType: 1 });
|
||||
}
|
||||
case 'anonymous': {
|
||||
// Anonymous flag — ignored during send, the protocol handles anonymity
|
||||
return null;
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message segment "anonymous" has no executable send semantics',
|
||||
normalizedType,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// 真实元素(P 发·解,段 type 与 element.type 同名):查 codec 表。
|
||||
// 见 event-converter/element-codecs.ts。
|
||||
const codec = ELEMENT_CODECS[normalizedType];
|
||||
if (codec?.fromSegment) return codec.fromSegment(data, options);
|
||||
const codec = getElementCodec(normalizedType);
|
||||
if (codec?.fromSegment) {
|
||||
const element = await codec.fromSegment(data, options);
|
||||
if (!element) {
|
||||
throw new MessageElementValidationError(
|
||||
'MISSING_FIELD',
|
||||
`message segment "${normalizedType}" is missing required or usable fields`,
|
||||
normalizedType,
|
||||
);
|
||||
}
|
||||
return validatedOutboundElement(element);
|
||||
}
|
||||
|
||||
console.warn(`[MsgParser] unsupported segment type: ${type}`);
|
||||
return null;
|
||||
if (Object.hasOwn(ELEMENT_MANIFEST, normalizedType)) {
|
||||
// Known receive-only/by-design-no type (currently flash_file). Ask the
|
||||
// executable manifest for the stable error + dedicated-Action hint.
|
||||
assertValidMessageElement({ type: normalizedType }, 'P');
|
||||
}
|
||||
throw new MessageElementValidationError(
|
||||
'UNKNOWN_TYPE',
|
||||
`unknown message segment type: ${type}`,
|
||||
normalizedType,
|
||||
);
|
||||
}
|
||||
|
||||
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
@@ -203,31 +338,56 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
|
||||
|
||||
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
|
||||
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',
|
||||
);
|
||||
}
|
||||
@@ -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<J
|
||||
requester_uin: r.targetUin,
|
||||
requester_nick: r.targetName,
|
||||
message: r.comment,
|
||||
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
|
||||
flag: formatGroupRequestFlag(r),
|
||||
}));
|
||||
} catch {
|
||||
return [];
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
|
||||
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, MessageElementOf, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload';
|
||||
import type { MessageSendResult } from '../api-handler';
|
||||
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
|
||||
import { segmentsToRawMessage } from '../helper/cq';
|
||||
import type { OneBotInstanceContext } from '../instance-context';
|
||||
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
|
||||
import { parseMessage } from '../message-parser';
|
||||
import { MessageElementValidationError, parseMessage } from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types';
|
||||
|
||||
@@ -41,14 +41,35 @@ export function videoNeedsFileFallback(element: MessageElement, isSizeErr: boole
|
||||
* else is returned for a normal re-send.
|
||||
*/
|
||||
export function splitVideoFileFallback(
|
||||
elements: MessageElement[],
|
||||
elements: Array<Exclude<MessageElement, { type: 'file' }>>,
|
||||
isSizeErr: boolean,
|
||||
): { fileEls: MessageElement[]; remaining: MessageElement[] } {
|
||||
const fileEls: MessageElement[] = [];
|
||||
const remaining: MessageElement[] = [];
|
||||
): {
|
||||
fileEls: Array<MessageElementOf<'file'>>;
|
||||
remaining: Array<Exclude<MessageElement, { type: 'file' }>>;
|
||||
} {
|
||||
const fileEls: Array<MessageElementOf<'file'>> = [];
|
||||
const remaining: Array<Exclude<MessageElement, { type: 'file' }>> = [];
|
||||
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<MessageSendResult> {
|
||||
// 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<string> => {
|
||||
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<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | 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<ForwardNodePayload[]> {
|
||||
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',
|
||||
);
|
||||
}
|
||||
@@ -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<GroupRequestInfo[]> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
// 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);
|
||||
}
|
||||
@@ -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<C extends NetworkBase> {
|
||||
@@ -36,6 +41,7 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
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<C extends NetworkBase> {
|
||||
|
||||
get currentConfig(): Readonly<C> { return this.config; }
|
||||
|
||||
get hasApplyFailure(): boolean { return this.applyFailure !== null; }
|
||||
|
||||
abstract open(): void | Promise<void>;
|
||||
abstract close(): void | Promise<void>;
|
||||
|
||||
@@ -58,6 +66,35 @@ export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
|
||||
/** 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<C extends NetworkBase> {
|
||||
// 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<C extends NetworkBase> {
|
||||
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);
|
||||
}
|
||||
@@ -52,16 +52,22 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
this.options = resolveReportOptions(next);
|
||||
}
|
||||
|
||||
onEvent(event: JsonObject, payload: DispatchPayload): void {
|
||||
async onEvent(event: JsonObject, payload: DispatchPayload): Promise<void> {
|
||||
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<void> {
|
||||
private async postEvent(
|
||||
payload: string,
|
||||
event: JsonObject,
|
||||
config: HttpClientNetwork,
|
||||
): Promise<void> {
|
||||
if (!this.isEnabled) return;
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
@@ -69,13 +75,13 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
|
||||
'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<HttpClientNetwork> {
|
||||
}
|
||||
} 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));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,24 +17,56 @@ const moduleLog = createLogger('OneBot.HTTP');
|
||||
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
|
||||
private server: Server | null = null;
|
||||
private listening = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
|
||||
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
|
||||
super(name, config, ctx, moduleLog);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
async open(): Promise<void> {
|
||||
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<void> {
|
||||
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<void>((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<HttpServerNetwork>
|
||||
|
||||
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<void> {
|
||||
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<void> {
|
||||
@@ -200,6 +261,33 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
|
||||
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<void>;
|
||||
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<string> {
|
||||
@@ -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));
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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<NetworkBase>;
|
||||
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<string, AnyAdapter>();
|
||||
private readonly adapters = new Map<string, ManagedAdapter>();
|
||||
private readonly factory: NetworkAdapterFactory | null;
|
||||
private operationTail: Promise<void> = Promise.resolve();
|
||||
private acceptingReconciles = true;
|
||||
private acceptingEvents = true;
|
||||
private readonly inFlightEmits = new Set<Promise<void>>();
|
||||
private shutdownPromise: Promise<NetworkShutdownResult> | 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<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): 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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<NetworkReconcileResult> {
|
||||
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<void> {
|
||||
/** Compatibility seam for tests/pre-built adapters. Opens sequentially and
|
||||
* reports each failure instead of hiding it in a detached Promise. */
|
||||
openAll(): Promise<NetworkReconcileResult> {
|
||||
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<void> {
|
||||
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<NetworkShutdownResult> {
|
||||
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<NetworkShutdownResult> {
|
||||
return this.shutdown();
|
||||
}
|
||||
|
||||
emitEvent(event: JsonObject): Promise<void> {
|
||||
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<void> {
|
||||
// Notify debug taps first — before the adapter check — so the debug stream
|
||||
// sees every event even when no adapter is connected. Never let a tap throw
|
||||
// into the dispatch path.
|
||||
// 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<unknown>[] = [];
|
||||
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<NetworkReconcileResult> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<T>(operation: () => Promise<T>): Promise<T> {
|
||||
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);
|
||||
}
|
||||
@@ -27,6 +27,8 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
private options: EventReportOptions;
|
||||
private role: WsRole;
|
||||
private explicitlyClosed = false;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
// 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<WsClientNetwork> {
|
||||
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<void> {
|
||||
this.explicitlyClosed = true;
|
||||
this.acceptingActions = false;
|
||||
this.isEnabled = false;
|
||||
this.connected = false;
|
||||
this.cancelReconnect();
|
||||
@@ -59,6 +72,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
safeClose(this.socket);
|
||||
this.socket = null;
|
||||
}
|
||||
await Promise.all(this.inFlightActions);
|
||||
}
|
||||
|
||||
override describeStatus(): AdapterStatus {
|
||||
@@ -131,9 +145,11 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
|
||||
});
|
||||
|
||||
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<WsClientNetwork> {
|
||||
);
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): 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<void>;
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +30,9 @@ interface ForwardConn {
|
||||
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
private wss: WebSocketServer | null = null;
|
||||
private listening = false;
|
||||
private closePromise: Promise<void> | null = null;
|
||||
private acceptingActions = false;
|
||||
private readonly inFlightActions = new Set<Promise<void>>();
|
||||
private connections = new Map<WebSocket, ForwardConn>();
|
||||
private options: EventReportOptions;
|
||||
|
||||
@@ -38,15 +41,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
|
||||
this.options = resolveReportOptions(config);
|
||||
}
|
||||
|
||||
open(): void {
|
||||
if (this.isEnabled) return;
|
||||
async open(): Promise<void> {
|
||||
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<void> {
|
||||
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<WsServerNetwork> {
|
||||
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<WsServerNetwork> {
|
||||
}
|
||||
}
|
||||
|
||||
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<void> {
|
||||
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<WsServerNetwork> {
|
||||
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<WsServerNetwork> {
|
||||
);
|
||||
}
|
||||
|
||||
private trackInboundAction(start: () => Promise<void>): 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<void>;
|
||||
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';
|
||||
|
||||
@@ -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<string, number>();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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/);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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', {});
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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'] });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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> = {}): 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',
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -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' });
|
||||
});
|
||||
|
||||
@@ -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 } });
|
||||
});
|
||||
});
|
||||
@@ -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) } });
|
||||
|
||||
@@ -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<typeof import('../src/modules/message-actions')>('../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<OneBotInstanceContext> = {}): {
|
||||
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<void>((resolve) => { markStarted = resolve; });
|
||||
let releaseConversion!: () => void;
|
||||
const conversionGate = new Promise<void>((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<void>((resolve) => { markStarted = resolve; });
|
||||
let releaseConversion!: () => void;
|
||||
const conversionGate = new Promise<void>((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);
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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> | 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);
|
||||
}
|
||||
@@ -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<void>((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<string, string>)['X-Signature']).toBe(
|
||||
`sha1=${createHmac('sha1', oldConfig.accessToken!).update(body).digest('hex')}`,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -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<void>((resolve) => { releaseAction = resolve; });
|
||||
let actionStarted!: () => void;
|
||||
const started = new Promise<void>((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<void>((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;
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>, {
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -53,8 +53,8 @@ async function waitForListen(adapter: HttpServerAdapter): Promise<number> {
|
||||
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<void>((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<void>((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<void>((resolve, reject) => {
|
||||
rebound.once('error', reject);
|
||||
rebound.listen(port.port, '127.0.0.1', resolve);
|
||||
});
|
||||
} finally {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
rebound.close((error) => error ? reject(error) : resolve());
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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<void>((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<string, unknown>, {
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown>, {
|
||||
uin: '10001',
|
||||
online: true,
|
||||
heartbeatTimer: null,
|
||||
eventPipeline: null,
|
||||
eventPipelineDrain: Promise.resolve(),
|
||||
disposePromise: null,
|
||||
disposeRequested: false,
|
||||
acceptingActions: true,
|
||||
inFlightActions: new Set<Promise<void>>(),
|
||||
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<NetworkShutdownResult>((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<void>((resolve) => { finishAction = resolve; });
|
||||
const action = (f.instance as unknown as {
|
||||
trackAction<T>(label: string, start: () => Promise<T>): Promise<T>;
|
||||
}).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<void>((resolve) => { finishEvent = resolve; });
|
||||
const stop = vi.fn();
|
||||
const drain = vi.fn(() => eventGate);
|
||||
Object.assign(f.instance as unknown as Record<string, unknown>, {
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -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<string, unknown> }).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);
|
||||
});
|
||||
});
|
||||
@@ -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<unknown>,
|
||||
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<void>((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<string, OneBotInstance>;
|
||||
trackLifecycle(label: string, operation: Promise<unknown>): 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<unknown>): 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<OneBotInstance> }).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<string, unknown> }).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<void>((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<OneBotInstance>;
|
||||
onSessionStarted(uin: string, bridge: never): void;
|
||||
onSessionClosed(uin: string): void;
|
||||
pendingStarts: Map<string, unknown>;
|
||||
};
|
||||
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<OneBotInstance>;
|
||||
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<OneBotInstance>;
|
||||
trackLifecycle(label: string, operation: Promise<unknown>, 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/);
|
||||
});
|
||||
});
|
||||
@@ -34,7 +34,7 @@ function recordElement(overrides: Partial<MessageElement> = {}): MessageElement
|
||||
|
||||
function makeGroupMessage(elements: MessageElement[]): GroupMessage {
|
||||
return {
|
||||
kind: 'group_message',
|
||||
kind: 'group_message', groupName: '',
|
||||
time: 1700000000,
|
||||
selfUin: SELF_ID,
|
||||
groupId: GROUP_ID,
|
||||
|
||||
@@ -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<typeof vi.fn>): 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();
|
||||
});
|
||||
});
|
||||
@@ -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: '<msg/>', resid: '35' } }] as any,
|
||||
false,
|
||||
);
|
||||
expect(xml).toEqual([{ type: 'xml', text: '<msg/>', 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),
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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' });
|
||||
|
||||
@@ -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<FakeNetworkConfig> {
|
||||
reloads = 0;
|
||||
// Last dispatch payload object identity, to assert it was reused per emit.
|
||||
lastPayloads: DispatchPayload[] = [];
|
||||
waitForEvent: Promise<void> | undefined;
|
||||
|
||||
open(): void {
|
||||
this.opens++;
|
||||
@@ -43,10 +44,19 @@ class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
|
||||
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<void> {
|
||||
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<void>((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);
|
||||
});
|
||||
});
|
||||
@@ -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<void>;
|
||||
release(): void;
|
||||
}
|
||||
|
||||
function gate(): Gate {
|
||||
let release!: () => void;
|
||||
return {
|
||||
promise: new Promise<void>((resolve) => { release = resolve; }),
|
||||
release: () => release(),
|
||||
};
|
||||
}
|
||||
|
||||
class ProbeAdapter extends IOneBotNetworkAdapter<NetworkBase> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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' }),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -8,7 +8,7 @@ const APIS_ROUTING: Record<string, string> = {
|
||||
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
|
||||
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
|
||||
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
|
||||
getGroupInviteCardSequence: 'contacts',
|
||||
getGroupInviteCardSequence: 'contacts', findGroupInviteCardGroupBySequence: 'contacts',
|
||||
};
|
||||
|
||||
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
|
||||
@@ -52,6 +52,63 @@ function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): 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/);
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
});
|
||||
|
||||
@@ -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) =>
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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<string, unknown>);
|
||||
|
||||
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<void>((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);
|
||||
});
|
||||
});
|
||||
@@ -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<typeof vi.fn> }).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<typeof vi.fn> }).sendGroupTempMessage)
|
||||
.not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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<void>((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 {
|
||||
|
||||
@@ -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>): 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<void>((resolve) => { finishAction = resolve; });
|
||||
(adapter as unknown as { trackInboundAction(start: () => Promise<void>): 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);
|
||||
});
|
||||
});
|
||||
@@ -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<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
|
||||
|
||||
@@ -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<ProtoElem[]> {
|
||||
// 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}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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<T extends MessageElementType> = Exclude<keyof MessageElementOf<T>, 'type'> & string;
|
||||
|
||||
export interface ElementSpec<T extends MessageElementType> {
|
||||
/** 每个方向的支持状态。 */
|
||||
readonly directions: Readonly<Record<ElementDirection, DirectionSupport>>;
|
||||
/**
|
||||
* 该元素类型在 `MessageElement` 上「属于自己」的字段 —— 字段契约的文档基准,
|
||||
* 供各方向读写时对齐(例如 poke 统一用 `subType`,不再收侧 `subType` / 发侧
|
||||
* `faceId` 打架)。当前为文档性声明,字段级强制留待后续阶段。
|
||||
* 该元素类型允许的全部字段。`fieldsFor` 在编译期要求它与判别联合完全一致,
|
||||
* `validateMessageElement` 在运行时据此拒绝越界字段。
|
||||
*/
|
||||
readonly fields: readonly string[];
|
||||
readonly fields: readonly ElementField<T>[];
|
||||
/** 运行时必须存在(不能为 undefined/null)的字段。 */
|
||||
readonly requiredFields: readonly ElementField<T>[];
|
||||
/** 备注:媒体上传、三角映射、协议限制等需要跨方向知道的事。 */
|
||||
readonly note?: string;
|
||||
}
|
||||
|
||||
type ManifestShape = { readonly [T in MessageElementType]: ElementSpec<T> };
|
||||
|
||||
/**
|
||||
* 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<T extends MessageElementType>() {
|
||||
return <const F extends readonly ElementField<T>[]>(
|
||||
fields: F & (Exclude<ElementField<T>, F[number]> extends never
|
||||
? unknown
|
||||
: { readonly __missingFields: Exclude<ElementField<T>, 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<string, ElementSpec>;
|
||||
} 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<string> = 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<string> = new Set([
|
||||
'faceId', 'targetUin', 'fileSize', 'replySeq', 'replyMessageId',
|
||||
'replySenderUin', 'replyTime', 'replyRandom', 'subType', 'duration',
|
||||
'width', 'height', 'emojiPackageId', 'sceneType', 'forwardTSum',
|
||||
'picFormat', 'videoFormat', 'voiceFormat',
|
||||
]);
|
||||
const BOOLEAN_FIELDS: ReadonlySet<string> = 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<string, unknown>, 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<string, unknown>;
|
||||
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<string, unknown>, element.type, 'text');
|
||||
return;
|
||||
case 'json': {
|
||||
requireNonEmptyString(element as unknown as Record<string, unknown>, 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<string, unknown>, 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<string, unknown>;
|
||||
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<string>(['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<string> {
|
||||
}
|
||||
|
||||
/**
|
||||
* 发·解(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<string> = new Set([
|
||||
'node', 'share', 'music', 'location', 'contact', 'rps', 'dice', 'shake', 'anonymous',
|
||||
|
||||
+189
-80
@@ -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> = T extends T ? keyof T : never;
|
||||
type StrictUnionMember<T, All> = T extends T
|
||||
? T & Partial<Record<Exclude<UnionKeys<All>, 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<MessageElementVariant, MessageElementVariant>;
|
||||
export type MessageElementType = MessageElementVariant['type'];
|
||||
export type MessageElementOf<T extends MessageElementType> = Extract<MessageElementVariant, { type: T }>;
|
||||
|
||||
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;
|
||||
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user