From 4ba2b2739879dc549abecf8ed282c08edf564300 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 20 Jul 2026 15:33:28 +0800 Subject: [PATCH] fix(onebot): keep synthetic sequences out of history Distinguish QQ-authoritative message sequences from local message IDs so group files and reply placeholders cannot become history anchors or be reused by protocol actions. Filter QQ null roam records and migrate previously stored synthetic rows. Fixes #254 --- packages/onebot/src/actions/extended.ts | 9 +- .../src/event-converter/element-codecs.ts | 23 ++- packages/onebot/src/event-pipeline.ts | 2 + packages/onebot/src/instance-context.ts | 4 +- packages/onebot/src/message-parser.ts | 7 +- packages/onebot/src/message-store.ts | 153 +++++++++++++++-- .../onebot/src/modules/message-actions.ts | 138 ++++++++++++--- packages/onebot/src/types.ts | 12 +- .../tests/backfill-reply-target.test.ts | 2 + packages/onebot/tests/event-pipeline.test.ts | 1 + .../onebot/tests/extended-actions.test.ts | 34 ++++ .../onebot/tests/history-direction.test.ts | 37 ++++ .../tests/message-action-validation.test.ts | 33 +++- packages/onebot/tests/message-store.test.ts | 159 ++++++++++++++++++ packages/onebot/tests/send-group-file.test.ts | 139 ++++++++++++++- .../src/msg-push/fetch-group-history.ts | 19 +++ .../msg-push/fetch-group-history.test.ts | 31 ++++ 17 files changed, 758 insertions(+), 45 deletions(-) diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index 1379340e..52f40157 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises'; import type { ApiActionContext } from '../api-handler'; import { asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; -import { JsonObject, RETCODE, failedResponse, okResponse } from '../types'; +import { hasAuthoritativeSequence, RETCODE, failedResponse, okResponse, type JsonObject } from '../types'; import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; @@ -111,6 +111,9 @@ async function groupTodoRun( if (!meta.isGroup || meta.targetId !== p.group_id) { return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); } + if (!hasAuthoritativeSequence(meta)) { + return failedResponse(RETCODE.ACTION_FAILED, 'message has no authoritative QQ sequence'); + } await op(p.group_id, BigInt(meta.sequence)); return okResponse(); } @@ -245,6 +248,10 @@ export const actions = [ return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); } + if (!hasAuthoritativeSequence(meta)) { + return failedResponse(RETCODE.ACTION_FAILED, 'message has no authoritative QQ sequence'); + } + await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, p.code, p.is_set); return okResponse(); }, diff --git a/packages/onebot/src/event-converter/element-codecs.ts b/packages/onebot/src/event-converter/element-codecs.ts index ce3dde85..851c4100 100644 --- a/packages/onebot/src/event-converter/element-codecs.ts +++ b/packages/onebot/src/event-converter/element-codecs.ts @@ -188,6 +188,7 @@ export const ELEMENT_CODECS = { async fromSegment(data, options) { const id = intOr(data.id, 0); if (id === 0) return null; + const meta = options?.resolveReplyMeta?.(id) ?? null; if (options?.resolveReplySequence) { const resolved = options.resolveReplySequence(id); @@ -199,19 +200,27 @@ export const ELEMENT_CODECS = { }; // Try to get additional meta info for better reply display - if (options?.resolveReplyMeta) { - const meta = options.resolveReplyMeta(id); - if (meta) { - element.replySenderUin = meta.senderUin; - element.replyTime = meta.time; - element.replyRandom = meta.random; - } + if (meta) { + element.replySenderUin = meta.senderUin; + element.replyTime = meta.time; + element.replyRandom = meta.random; } return element; } } + // The id is known locally, but it came from an OIDB-only/synthetic + // message and therefore has no QQ server sequence. Treating the opaque + // OneBot id as a direct sequence would publish a malformed reply. + if (meta?.sequenceAuthoritative === false) { + throw new MessageElementValidationError( + 'INVALID_FIELD', + `reply target ${id} has no authoritative QQ sequence`, + 'reply', + ); + } + // Backward-compatible path: allow direct seq reply IDs. return id > 0 ? { type: 'reply', replySeq: id } : null; }, diff --git a/packages/onebot/src/event-pipeline.ts b/packages/onebot/src/event-pipeline.ts index 316a68d2..d912d934 100644 --- a/packages/onebot/src/event-pipeline.ts +++ b/packages/onebot/src/event-pipeline.ts @@ -190,6 +190,7 @@ function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract { const meta = messageStore.findMeta(messageId); if (!meta) throw new Error('message not found'); if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages'); + if (!hasAuthoritativeSequence(meta)) throw new Error('message has no authoritative QQ sequence'); const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset); const users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt })); const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId); diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index 6c2be457..7425dcad 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -15,7 +15,12 @@ export { MessageElementValidationError } from '@snowluma/protocol/element-manife export interface ParseMessageOptions { resolveReplySequence?: (replyMessageId: number) => number | null; - resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null; + resolveReplyMeta?: (replyMessageId: number) => { + senderUin: number; + time: number; + random: number; + sequenceAuthoritative?: boolean; + } | null; resolveMentionUid?: (targetUin: number) => string | null | Promise; resolveContactArk?: (contactType: string, contactId: number) => string | null | Promise; musicSignUrl?: string; diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index 38f85ce1..36e664ee 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -1,12 +1,20 @@ import { DatabaseSync, type StatementSync } from 'node:sqlite'; +import { createLogger } from '@snowluma/common/logger'; import type { JsonObject, MessageMeta } from './types'; import { openSqliteDb } from './sqlite-open'; +const log = createLogger('OneBot.MessageStore'); + export interface ReadSessionTargets { groupIds: number[]; privateUserIds: number[]; } +export interface StoreEventOptions { + /** False for locally reconstructed events whose sequence QQ never confirmed. */ + sequenceAuthoritative?: boolean; +} + export class MessageStore { private readonly db: DatabaseSync; private readonly stmtStoreEvent: StatementSync; @@ -18,6 +26,7 @@ export class MessageStore { private readonly stmtListEventsAnchored: StatementSync; private readonly stmtListEventsAnchoredForward: StatementSync; private readonly stmtListEventsLatest: StatementSync; + private readonly stmtFindLatestAuthoritativeSequence: StatementSync; private readonly stmtListIncomingC2CSessions: StatementSync; constructor(dbPath: string) { @@ -30,12 +39,13 @@ export class MessageStore { // Database instance — `close()` finalizes them automatically. this.stmtStoreEvent = this.db.prepare( `INSERT INTO messages - (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) - VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?) + (message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp, data) + VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?) ON CONFLICT(message_hash) DO UPDATE SET is_group = excluded.is_group, session_id = excluded.session_id, sequence = excluded.sequence, + sequence_authoritative = excluded.sequence_authoritative, event_name = excluded.event_name, timestamp = excluded.timestamp, data = excluded.data`, @@ -43,12 +53,13 @@ export class MessageStore { this.stmtStoreMeta = this.db.prepare( `INSERT INTO messages - (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp) - VALUES (?, ?, ?, ?, ?, ?, ?, ?) + (message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) ON CONFLICT(message_hash) DO UPDATE SET is_group = excluded.is_group, session_id = excluded.session_id, sequence = excluded.sequence, + sequence_authoritative = excluded.sequence_authoritative, event_name = excluded.event_name, client_sequence = excluded.client_sequence, random = excluded.random, @@ -60,27 +71,28 @@ export class MessageStore { ); this.stmtFindMeta = this.db.prepare( - 'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?', + 'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?', ); this.stmtResolveReplyGroup = this.db.prepare( `SELECT sequence FROM messages - WHERE is_group = 1 AND session_id = ? AND message_hash = ? + WHERE is_group = 1 AND session_id = ? AND message_hash = ? AND sequence_authoritative = 1 LIMIT 1`, ); this.stmtResolveReplyPrivate = this.db.prepare( `SELECT sequence FROM messages - WHERE is_group = 0 AND message_hash = ? + WHERE is_group = 0 AND message_hash = ? AND sequence_authoritative = 1 LIMIT 1`, ); this.stmtListEventsAnchored = this.db.prepare( `SELECT data FROM messages - WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ? + WHERE is_group = ? AND session_id = ? AND data IS NOT NULL + AND sequence_authoritative = 1 AND sequence > 0 AND sequence <= ? ORDER BY sequence DESC LIMIT ?`, ); @@ -88,7 +100,8 @@ export class MessageStore { this.stmtListEventsAnchoredForward = this.db.prepare( `SELECT data FROM messages - WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence >= ? + WHERE is_group = ? AND session_id = ? AND data IS NOT NULL + AND sequence_authoritative = 1 AND sequence > 0 AND sequence >= ? ORDER BY sequence ASC LIMIT ?`, ); @@ -97,10 +110,19 @@ export class MessageStore { `SELECT data FROM messages WHERE is_group = ? AND session_id = ? AND data IS NOT NULL + AND sequence_authoritative = 1 AND sequence > 0 ORDER BY sequence DESC LIMIT ?`, ); + this.stmtFindLatestAuthoritativeSequence = this.db.prepare( + `SELECT sequence + FROM messages + WHERE is_group = ? AND session_id = ? AND sequence_authoritative = 1 AND sequence > 0 + ORDER BY sequence DESC + LIMIT 1`, + ); + this.stmtListIncomingC2CSessions = this.db.prepare( `SELECT session_id FROM messages @@ -124,13 +146,23 @@ export class MessageStore { sessionId: number, sequence: number, eventName: string, - event: JsonObject + event: JsonObject, + options: StoreEventOptions = {}, ): void { if (!isValidMessageId(messageId)) return; const json = JSON.stringify(event); const timestamp = toInt(event.time); - this.stmtStoreEvent.run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json); + this.stmtStoreEvent.run( + messageId, + isGroup ? 1 : 0, + sessionId, + sequence, + options.sequenceAuthoritative === false ? 0 : 1, + eventName, + timestamp, + json, + ); } storeMeta(messageId: number, meta: MessageMeta): void { @@ -140,6 +172,7 @@ export class MessageStore { meta.isGroup ? 1 : 0, meta.targetId, meta.sequence, + meta.sequenceAuthoritative === false ? 0 : 1, meta.eventName, meta.clientSequence, meta.random, @@ -166,6 +199,7 @@ export class MessageStore { is_group: number; session_id: number; sequence: number; + sequence_authoritative: number; event_name: string; client_sequence: number; random: number; @@ -178,6 +212,7 @@ export class MessageStore { isGroup: row.is_group === 1, targetId: row.session_id, sequence: row.sequence, + sequenceAuthoritative: row.sequence_authoritative === 1, eventName: row.event_name, clientSequence: row.client_sequence, random: row.random, @@ -240,6 +275,16 @@ export class MessageStore { return result; } + findLatestAuthoritativeSequence(isGroup: boolean, sessionId: number): number | null { + if (!Number.isInteger(sessionId) || sessionId <= 0) return null; + const row = this.stmtFindLatestAuthoritativeSequence.get( + isGroup ? 1 : 0, + sessionId, + ) as { sequence: number } | undefined; + if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null; + return row.sequence; + } + /** * Build read-report targets from current groups plus genuine incoming C2C * sessions. `is_group = 0` alone is insufficient: group temp sessions use @@ -277,6 +322,7 @@ export class MessageStore { is_group INTEGER NOT NULL, session_id INTEGER NOT NULL, sequence INTEGER NOT NULL, + sequence_authoritative INTEGER NOT NULL DEFAULT 1, event_name TEXT NOT NULL, client_sequence INTEGER NOT NULL DEFAULT 0, random INTEGER NOT NULL DEFAULT 0, @@ -284,7 +330,92 @@ export class MessageStore { data TEXT ) `); + this.migrateSequenceAuthority(); this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)'); + this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)'); + } + + private migrateSequenceAuthority(): void { + const columns = this.db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>; + if (columns.some((column) => column.name === 'sequence_authoritative')) return; + + this.db.exec('BEGIN IMMEDIATE'); + try { + this.db.exec( + 'ALTER TABLE messages ADD COLUMN sequence_authoritative INTEGER NOT NULL DEFAULT 1', + ); + const result = this.db.prepare(` + UPDATE messages + SET sequence_authoritative = 0 + WHERE sequence > 0 + AND data IS NOT NULL + AND CASE WHEN json_valid(data) THEN ( + ( + is_group = 1 + AND ( + ( + json_extract(data, '$.post_type') = 'message_sent' + AND json_extract(data, '$.message_type') = 'group' + AND random = sequence + AND json_extract(data, '$.message[0].type') IN ('file', 'video') + ) + OR + ( + json_extract(data, '$.post_type') = 'message' + AND json_extract(data, '$.message_type') = 'group' + AND json_type(data, '$.group_name') IS NULL + AND json_type(data, '$.sender') = 'object' + AND json_extract(data, '$.sender.user_id') = json_extract(data, '$.user_id') + AND json_extract(data, '$.sender.nickname') = '' + AND json_extract(data, '$.sender.card') = '' + AND json_extract(data, '$.sender.role') = 'member' + AND json_extract(data, '$.sender.sex') = 'unknown' + AND json_extract(data, '$.sender.age') = 0 + ) + OR + ( + json_extract(data, '$.post_type') = 'message' + AND json_extract(data, '$.message_type') = 'group' + AND json_extract(data, '$.user_id') = 0 + AND json_extract(data, '$.time') = 0 + ) + OR + ( + json_extract(data, '$.post_type') = 'message' + AND json_extract(data, '$.message_type') = 'group' + AND json_extract(data, '$.user_id') = 0 + AND json_array_length(json_extract(data, '$.message')) = 1 + AND json_extract(data, '$.message[0].type') = 'text' + AND json_extract(data, '$.message[0].data.text') = '[引用消息]' + ) + ) + ) + OR + ( + is_group = 0 + AND random = 0 + AND client_sequence = 0 + AND json_extract(data, '$.post_type') = 'message' + AND json_extract(data, '$.message_type') = 'private' + AND json_extract(data, '$.sub_type') = 'friend' + AND json_type(data, '$.target_id') IS NULL + AND json_type(data, '$.sender') = 'object' + AND json_extract(data, '$.sender.user_id') = json_extract(data, '$.user_id') + AND json_extract(data, '$.sender.nickname') = '' + AND json_extract(data, '$.sender.sex') = 'unknown' + AND json_extract(data, '$.sender.age') = 0 + ) + ) ELSE 0 END + `).run(); + this.db.exec('COMMIT'); + log.info( + 'message-store schema migrated: sequence authority added, synthetic rows marked=%d', + Number(result.changes), + ); + } catch (error) { + this.db.exec('ROLLBACK'); + throw error; + } } } diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index efb203ed..7bdc7ab8 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -10,7 +10,7 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from ' import { MessageElementValidationError, parseMessage } from '../message-parser'; import type { MessageStore } from '../message-store'; import { sameSelfSentMessage } from '../self-sent-event'; -import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types'; +import { hasAuthoritativeSequence, type JsonArray, type JsonObject, type JsonValue, type MessageMeta } from '../types'; const log = createLogger('OneBot'); @@ -92,7 +92,7 @@ export async function getGroupMsgHistory( let anchorSequence: number | undefined; if (hasAnchor) { const meta = messageStore.findMeta(messageId as number); - if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return []; + if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) return []; anchorSequence = meta.sequence; } @@ -120,7 +120,7 @@ export async function getFriendMsgHistory( let anchorSequence: number | undefined; if (hasAnchor) { const meta = messageStore.findMeta(messageId as number); - if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return []; + if (!hasAuthoritativeSequence(meta) || meta.isGroup || meta.targetId !== userId) return []; anchorSequence = meta.sequence; } @@ -164,15 +164,20 @@ export async function getGroupHistory( let anchorSeq = 0; if (hasAnchor) { const meta = ref.messageStore.findMeta(messageId as number); - if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) { + if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) { // Anchor we don't know — best effort from the local store. return getGroupMsgHistory(ref.messageStore, groupId, messageId, count, reverseOrder); } anchorSeq = meta.sequence; } else { - const latest = ref.messageStore.listSessionEvents(true, groupId, 1); - anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0; + anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0; } + log.debug( + 'group history anchor selected: group=%d source=%s anchorSeq=%d', + groupId, + hasAnchor ? 'message_id' : 'latest_authoritative', + anchorSeq, + ); if (anchorSeq > 0) { try { @@ -191,6 +196,12 @@ export async function getGroupHistory( out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path) } if (out.length > 0) return out; + log.debug( + 'group history server fetch returned no usable messages: group=%d anchorSeq=%d count=%d; using local store', + groupId, + anchorSeq, + want, + ); } catch (err) { log.warn( 'group history server fetch failed: group=%d anchorSeq=%d count=%d reverseOrder=%s error=%s; using local store', @@ -238,7 +249,7 @@ export async function getFriendHistory( : null; const belongsToPeer = meta?.targetId === userId || (meta?.targetId === ref.selfId && toHistInt(storedEvent?.target_id) === userId); - if (!meta || meta.isGroup || meta.sequence <= 0 || !belongsToPeer) { + if (!hasAuthoritativeSequence(meta) || meta.isGroup || !belongsToPeer) { return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder); } anchorSeq = meta.sequence; @@ -246,9 +257,14 @@ export async function getFriendHistory( // Current rows are keyed by conversation peer, so the latest local anchor // covers both incoming and self-sent messages. Legacy sender-keyed rows are // repaired when they are fetched through an explicit anchor. - const latest = ref.messageStore.listSessionEvents(false, userId, 1); - anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0; + anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(false, userId) ?? 0; } + log.debug( + 'friend history anchor selected: user=%d source=%s anchorSeq=%d', + userId, + hasAnchor ? 'message_id' : 'latest_authoritative', + anchorSeq, + ); if (anchorSeq > 0) { try { @@ -279,6 +295,12 @@ export async function getFriendHistory( out.push(sanitizeMessageEventForApi(json)); } if (out.length > 0) return out; + log.debug( + 'friend history server fetch returned no usable messages: user=%d anchorSeq=%d count=%d; using local store', + userId, + anchorSeq, + want, + ); } } catch (err) { log.warn( @@ -369,7 +391,18 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant ) as JsonArray; const fallback = buildBackfillEvent(targetId, replySeq, quotedSender, reply.replyTime ?? 0, segments, ref.selfId, isGroup, session); - ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback); + // Inline quote metadata proves what was displayed, but not that replySeq + // still names a server-backed roam message. Keep it queryable via + // get_msg without letting it become a history/recall/reply anchor. + ref.messageStore.storeEvent( + targetId, + isGroup, + session, + replySeq, + eventName, + fallback, + { sequenceAuthoritative: false }, + ); return; } catch (err) { log.warn('reply-target backfill tier-2 failed (%s)', err instanceof Error ? err.message : String(err)); @@ -382,7 +415,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender, reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }], ref.selfId, isGroup, session); - ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder); + ref.messageStore.storeEvent( + targetId, + isGroup, + session, + replySeq, + eventName, + placeholder, + { sequenceAuthoritative: false }, + ); } // Build a stored-message event for a backfilled reply target (Tier 2/3). @@ -452,6 +493,9 @@ function toHistInt(value: unknown): number { } export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise { + if (!hasAuthoritativeSequence(meta)) { + throw new Error('message has no authoritative QQ sequence and cannot be recalled'); + } if (meta.isGroup) { await bridge.apis.message.recallGroup(meta.targetId, meta.sequence); } else { @@ -473,6 +517,9 @@ export async function setEssenceMessage( ): Promise { const meta = messageStore.findMeta(messageId); if (!meta || !meta.isGroup) throw new Error('message not found or not a group message'); + if (!hasAuthoritativeSequence(meta)) { + throw new Error('message has no authoritative QQ sequence and cannot be marked as essence'); + } await bridge.apis.interaction.setEssence(meta.targetId, meta.sequence, meta.random, enable); } @@ -506,16 +553,33 @@ async function finalizeSend( ref: OneBotInstanceContext, isGroup: boolean, targetId: number, - receipt: { sequence: number; clientSequence: number; random: number; timestamp: number }, + receipt: { + messageId?: number; + sequence: number; + clientSequence: number; + random: number; + timestamp: number; + }, elements: MessageElement[], reportEcho = false, ): Promise { const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; - const messageId = hashMessageIdInt32(receipt.sequence, targetId, eventName); + const sequenceAuthoritative = Number.isInteger(receipt.sequence) && receipt.sequence > 0; + const opaqueMessageId = receipt.messageId ?? 0; + // Ordinary sends use QQ's real sequence so receive/send paths derive the same + // OneBot id. OIDB-only sends (notably group files) have no QQ sequence: keep + // their opaque local id separate instead of feeding a file hash into protocol + // operations as if it were a server sequence (#254). + const messageId = sequenceAuthoritative + ? hashMessageIdInt32(receipt.sequence, targetId, eventName) + : Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0 + ? opaqueMessageId + : hashMessageIdInt32(0, targetId, eventName); ref.cacheMessageMeta(messageId, { isGroup, targetId, sequence: receipt.sequence, + sequenceAuthoritative, eventName, clientSequence: receipt.clientSequence, random: receipt.random, @@ -526,10 +590,11 @@ async function finalizeSend( sessionId: targetId, messageId, sequence: receipt.sequence, + sequenceAuthoritative, timestamp: receipt.timestamp, elements, }); - return reportEcho && echoEvent && receipt.sequence > 0 && receipt.timestamp > 0 + return reportEcho && echoEvent && sequenceAuthoritative && receipt.timestamp > 0 ? { messageId, echoEvent } : { messageId }; } @@ -541,11 +606,20 @@ async function cacheSelfSentMessage( sessionId: number; // groupId or peer userId messageId: number; sequence: number; + sequenceAuthoritative: boolean; timestamp: number; elements: MessageElement[]; }, ): Promise { - const { isGroup, sessionId, messageId, sequence, timestamp, elements } = options; + const { + isGroup, + sessionId, + messageId, + sequence, + sequenceAuthoritative, + timestamp, + elements, + } = options; if (!Number.isInteger(messageId) || messageId === 0) return null; // Defensive: tests may mock `ref.messageStore` without the full MessageStore @@ -608,7 +682,16 @@ async function cacheSelfSentMessage( // Persist before dispatch so `/get_msg` is immediately consistent for a // client reacting to the synthetic message_sent notification. - storeEvent.call(ref.messageStore, messageId, isGroup, sessionId, sequence, eventName, event); + storeEvent.call( + ref.messageStore, + messageId, + isGroup, + sessionId, + sequence, + eventName, + event, + { sequenceAuthoritative }, + ); return event; } catch (err) { // Never turn a successful QQ send into a failed Action after the fact. @@ -665,6 +748,7 @@ export async function sendPrivateMessage( senderUin, time, random: meta?.random ?? 0, + sequenceAuthoritative: meta?.sequenceAuthoritative, }; } const meta = ref.messageStore.findMeta(replyMessageId); @@ -673,6 +757,7 @@ export async function sendPrivateMessage( senderUin: ref.selfId, time: meta.timestamp, random: meta.random, + sequenceAuthoritative: meta.sequenceAuthoritative, }; } return null; @@ -838,6 +923,8 @@ export async function sendGroupMessage( return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId); }, resolveReplyMeta: (replyMessageId) => { + const meta = ref.messageStore.findMeta(replyMessageId); + if (!meta || !meta.isGroup || meta.targetId !== groupId) return null; const event = ref.messageStore.findEvent(replyMessageId); if (event) { return { @@ -847,10 +934,16 @@ export async function sendGroupMessage( time: typeof event.time === 'number' ? event.time : parseInt(String(event.time || '0'), 10), - random: 0, + random: meta?.random ?? 0, + sequenceAuthoritative: meta?.sequenceAuthoritative, }; } - return null; + return { + senderUin: ref.selfId, + time: meta.timestamp, + random: meta.random, + sequenceAuthoritative: meta.sequenceAuthoritative, + }; }, resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId), resolveContactArk: (contactType, contactId) => resolveContactArk(ref, contactType, contactId), @@ -918,7 +1011,14 @@ export async function sendGroupMessage( if (!lastReceipt) { let h = 0; for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 0; - lastReceipt = { messageId: 0, sequence: h & 0x7FFFFFFF, clientSequence: 0, random: h & 0x7FFFFFFF, timestamp: Math.floor(Date.now() / 1000) }; + const localSeed = h & 0x7FFFFFFF; + lastReceipt = { + messageId: hashMessageIdInt32(localSeed, groupId, GROUP_MESSAGE_EVENT), + sequence: 0, + clientSequence: 0, + random: localSeed, + timestamp: Math.floor(Date.now() / 1000), + }; } } if (!lastReceipt) throw new Error('message is empty'); diff --git a/packages/onebot/src/types.ts b/packages/onebot/src/types.ts index 57e99feb..9284b1a7 100644 --- a/packages/onebot/src/types.ts +++ b/packages/onebot/src/types.ts @@ -122,12 +122,23 @@ export interface MessageMeta { isGroup: boolean; targetId: number; sequence: number; + /** Whether `sequence` was confirmed by QQ and is safe for protocol actions. */ + sequenceAuthoritative: boolean; eventName: string; clientSequence: number; random: number; timestamp: number; } +/** True only when a stored sequence can safely be sent back to QQ. */ +export function hasAuthoritativeSequence( + meta: MessageMeta | null | undefined, +): meta is MessageMeta { + return meta?.sequenceAuthoritative === true + && Number.isInteger(meta.sequence) + && meta.sequence > 0; +} + export const RETCODE = { ACTION_FAILED: 100, INTERNAL_ERROR: 1200, @@ -152,4 +163,3 @@ export function failedResponse(retcode: number, wording: string): ApiResponse { }; } export type { JsonArray, JsonObject, JsonPrimitive, JsonValue } from '@snowluma/common/json'; - diff --git a/packages/onebot/tests/backfill-reply-target.test.ts b/packages/onebot/tests/backfill-reply-target.test.ts index 55c810a0..529db2c2 100644 --- a/packages/onebot/tests/backfill-reply-target.test.ts +++ b/packages/onebot/tests/backfill-reply-target.test.ts @@ -188,6 +188,7 @@ describe('backfillReplyTarget', () => { expect(store.storeEvent).toHaveBeenCalledWith( targetId, true, 700, 123, GROUP_MESSAGE_EVENT, expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }), + { sequenceAuthoritative: false }, ); }); @@ -207,6 +208,7 @@ describe('backfillReplyTarget', () => { expect(store.storeEvent).toHaveBeenCalledWith( targetId, true, 700, 123, GROUP_MESSAGE_EVENT, expect.objectContaining({ message_id: targetId, message_type: 'group' }), + { sequenceAuthoritative: false }, ); }); }); diff --git a/packages/onebot/tests/event-pipeline.test.ts b/packages/onebot/tests/event-pipeline.test.ts index c99cf9be..b5e73818 100644 --- a/packages/onebot/tests/event-pipeline.test.ts +++ b/packages/onebot/tests/event-pipeline.test.ts @@ -145,6 +145,7 @@ describe('registerEventPipeline', () => { expect(metaCalls[0].meta.isGroup).toBe(false); expect(metaCalls[0].meta.targetId).toBe(PEER_UIN); expect(metaCalls[0].meta.sequence).toBe(11); + expect(metaCalls[0].meta.sequenceAuthoritative).toBe(true); expect(metaCalls[0].meta.random).toBe(555); expect(dispatchCalls).toHaveLength(1); diff --git a/packages/onebot/tests/extended-actions.test.ts b/packages/onebot/tests/extended-actions.test.ts index 021c6287..7255970f 100644 --- a/packages/onebot/tests/extended-actions.test.ts +++ b/packages/onebot/tests/extended-actions.test.ts @@ -16,6 +16,7 @@ function fakeMeta(overrides: Partial = {}): MessageMeta { isGroup: true, targetId: 100, sequence: 555, + sequenceAuthoritative: true, eventName: 'group_message', clientSequence: 0, random: 0, @@ -648,6 +649,19 @@ describe('extended-actions / set_/complete_/cancel_group_todo', () => { expect(res).toMatchObject({ status: 'failed', retcode: 100 }); }); + it('rejects a local-only message id without calling the group todo protocol', async () => { + const setGroupTodo = vi.fn(async () => {}); + const bridge = fakeBridge({ setGroupTodo }); + const ctx = fakeCtx(bridge, { + getMessageMeta: () => fakeMeta({ sequence: 0, sequenceAuthoritative: false }), + }); + + const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 }); + + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + expect(setGroupTodo).not.toHaveBeenCalled(); + }); + it('rejects missing params', async () => { const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 }); const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { group_id: 1 }); @@ -656,6 +670,26 @@ describe('extended-actions / set_/complete_/cancel_group_todo', () => { }); }); +describe('extended-actions / set_group_reaction', () => { + it('rejects a local-only message id without calling the reaction protocol', async () => { + const setGroupReaction = vi.fn(async () => {}); + const bridge = fakeBridge({ setGroupReaction }); + const ctx = fakeCtx(bridge, { + getMessageMeta: () => fakeMeta({ sequence: 0, sequenceAuthoritative: false }), + }); + + const res = await makeHandler(ctx).handle('set_group_reaction', { + group_id: 100, + message_id: 1, + code: '66', + is_set: true, + }); + + expect(res).toMatchObject({ status: 'failed', retcode: 100 }); + expect(setGroupReaction).not.toHaveBeenCalled(); + }); +}); + // ─── Tier 2: nc_get_user_status ─── describe('extended-actions / nc_get_user_status', () => { diff --git a/packages/onebot/tests/history-direction.test.ts b/packages/onebot/tests/history-direction.test.ts index 495b03e7..f71a7f4f 100644 --- a/packages/onebot/tests/history-direction.test.ts +++ b/packages/onebot/tests/history-direction.test.ts @@ -63,6 +63,7 @@ describe('history direction plumbing', () => { isGroup: true, targetId: GROUP_ID, sequence: 500, + sequenceAuthoritative: true, eventName: GROUP_MESSAGE_EVENT, clientSequence: 0, random: 0, @@ -91,6 +92,7 @@ describe('history direction plumbing', () => { isGroup: false, targetId: FRIEND_ID, sequence: 700, + sequenceAuthoritative: true, eventName: PRIVATE_MESSAGE_EVENT, clientSequence: 0, random: 0, @@ -124,6 +126,15 @@ describe('history direction plumbing', () => { message_id: 1, message_seq: 900, }); + messageStore.storeEvent(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, { + post_type: 'message_sent', + message_type: 'group', + group_id: GROUP_ID, + message_id: 2, + message_seq: 1799283572, + user_id: SELF_ID, + message: [{ type: 'file', data: { file_id: 'gfid-local' } }], + }, { sequenceAuthoritative: false }); const ref = { selfId: SELF_ID, bridge: { @@ -136,6 +147,31 @@ describe('history direction plumbing', () => { const messages = await getGroupHistory(ref, GROUP_ID, 0, 20, false); expect(messages.map((message) => message.message_seq)).toEqual([899, 900]); + expect(fetchHistory).toHaveBeenCalledWith(GROUP_ID, 900, 20, SELF_ID, true); + }); + + it('does not use an explicitly requested local-only id as a server history anchor', async () => { + const fetchHistory = vi.fn(async () => [groupMessage(1799283572)]); + messageStore.storeEvent(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, { + post_type: 'message_sent', + message_type: 'group', + group_id: GROUP_ID, + message_id: 2, + message_seq: 1799283572, + user_id: SELF_ID, + message: [{ type: 'file', data: { file_id: 'gfid-local' } }], + }, { sequenceAuthoritative: false }); + const ref = { + selfId: SELF_ID, + bridge: { + apis: { message: { getGroupHistory: fetchHistory } }, + }, + messageStore, + converterCtx, + } as any; + + await expect(getGroupHistory(ref, GROUP_ID, 2, 20, false)).resolves.toEqual([]); + expect(fetchHistory).not.toHaveBeenCalled(); }); it('rejects a private anchor from a different friend conversation', async () => { @@ -144,6 +180,7 @@ describe('history direction plumbing', () => { isGroup: false, targetId: 987654321, sequence: 800, + sequenceAuthoritative: true, eventName: PRIVATE_MESSAGE_EVENT, clientSequence: 0, random: 0, diff --git a/packages/onebot/tests/message-action-validation.test.ts b/packages/onebot/tests/message-action-validation.test.ts index 52626984..4c96d209 100644 --- a/packages/onebot/tests/message-action-validation.test.ts +++ b/packages/onebot/tests/message-action-validation.test.ts @@ -2,7 +2,8 @@ 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'; +import { deleteMessage, sendGroupMessage, setEssenceMessage } from '../src/modules/message-actions'; +import type { MessageMeta } from '../src/types'; function instanceContext(sendGroup: ReturnType): OneBotInstanceContext { const bridge = { @@ -95,3 +96,33 @@ describe('outbound message validation at the Action boundary', () => { expect(bridgeSend).not.toHaveBeenCalled(); }); }); + +describe('server-sequence action validation', () => { + const localOnlyMeta: MessageMeta = { + isGroup: true, + targetId: 12345, + sequence: 0, + sequenceAuthoritative: false, + eventName: 'group_message', + clientSequence: 0, + random: 0, + timestamp: 0, + }; + + it('does not recall a message that has only a local id', async () => { + const recallGroup = vi.fn(); + const bridge = { apis: { message: { recallGroup } } } as unknown as BridgeInterface; + + await expect(deleteMessage(bridge, localOnlyMeta)).rejects.toThrow('no authoritative QQ sequence'); + expect(recallGroup).not.toHaveBeenCalled(); + }); + + it('does not mark a message that has only a local id as essence', async () => { + const setEssence = vi.fn(); + const bridge = { apis: { interaction: { setEssence } } } as unknown as BridgeInterface; + const store = { findMeta: () => localOnlyMeta } as any; + + await expect(setEssenceMessage(bridge, store, 1, true)).rejects.toThrow('no authoritative QQ sequence'); + expect(setEssence).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/message-store.test.ts b/packages/onebot/tests/message-store.test.ts index e7843749..6125fb93 100644 --- a/packages/onebot/tests/message-store.test.ts +++ b/packages/onebot/tests/message-store.test.ts @@ -3,6 +3,7 @@ import { MessageStore } from '../src/message-store'; import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id'; import fs from 'fs'; import path from 'path'; +import { DatabaseSync } from 'node:sqlite'; describe('MessageStore', () => { const testDbPath = path.join('data', 'test', 'messages-test.db'); @@ -39,6 +40,7 @@ describe('MessageStore', () => { isGroup: true, targetId: groupId, sequence, + sequenceAuthoritative: true, eventName: GROUP_MESSAGE_EVENT, clientSequence: 0, random: 0, @@ -61,6 +63,7 @@ describe('MessageStore', () => { isGroup: false, targetId: senderUin, sequence, + sequenceAuthoritative: true, eventName: PRIVATE_MESSAGE_EVENT, clientSequence: 0, random: 0, @@ -105,6 +108,7 @@ describe('MessageStore', () => { isGroup: true, targetId: sessionId, sequence, + sequenceAuthoritative: true, eventName: GROUP_MESSAGE_EVENT, clientSequence: 0, random: 0, @@ -117,6 +121,7 @@ describe('MessageStore', () => { isGroup: false, targetId: sessionId, sequence, + sequenceAuthoritative: true, eventName: PRIVATE_MESSAGE_EVENT, clientSequence: 0, random: 0, @@ -170,6 +175,7 @@ describe('MessageStore', () => { isGroup: true, targetId: 123456, sequence: 100, + sequenceAuthoritative: true, eventName: GROUP_MESSAGE_EVENT, clientSequence: 1, random: 12345, @@ -218,6 +224,159 @@ describe('MessageStore', () => { expect(messages.map((message) => message.message_seq)).toEqual([1, 2, 3]); }); + + it('excludes unconfirmed sequences from replies and history anchors (#254)', () => { + const groupId = 123456; + store.storeEvent(1, true, groupId, 9748, GROUP_MESSAGE_EVENT, { + post_type: 'message', + message_type: 'group', + group_id: groupId, + group_name: 'Test group', + message_id: 1, + message_seq: 9748, + }); + store.storeEvent(2, true, groupId, 1799283572, GROUP_MESSAGE_EVENT, { + post_type: 'message_sent', + message_type: 'group', + group_id: groupId, + message_id: 2, + message_seq: 1799283572, + message: [{ type: 'file', data: { file: 'test.bin' } }], + }, { sequenceAuthoritative: false }); + + expect(store.findLatestAuthoritativeSequence(true, groupId)).toBe(9748); + expect(store.listSessionEvents(true, groupId).map((message) => message.message_seq)).toEqual([9748]); + expect(store.resolveReplySequence(true, groupId, 2)).toBeNull(); + expect(store.findMeta(2)).toMatchObject({ + sequence: 1799283572, + sequenceAuthoritative: false, + }); + }); + + it('migrates legacy synthetic group-file and reply-backfill sequences (#254)', () => { + const groupId = 123456; + store.close(); + + const legacy = new DatabaseSync(testDbPath); + legacy.exec(` + DROP TABLE messages; + CREATE TABLE messages ( + message_hash INTEGER PRIMARY KEY, + is_group INTEGER NOT NULL, + session_id INTEGER NOT NULL, + sequence INTEGER NOT NULL, + event_name TEXT NOT NULL, + client_sequence INTEGER NOT NULL DEFAULT 0, + random INTEGER NOT NULL DEFAULT 0, + timestamp INTEGER NOT NULL DEFAULT 0, + data TEXT + ) + `); + const insert = legacy.prepare(` + INSERT INTO messages + (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) + VALUES (?, 1, ?, ?, ?, 0, ?, ?, ?) + `); + const insertPrivate = legacy.prepare(` + INSERT INTO messages + (message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) + VALUES (?, 0, ?, ?, ?, 0, ?, ?, ?) + `); + insert.run(1, groupId, 9748, GROUP_MESSAGE_EVENT, 0, 1700000000, JSON.stringify({ + time: 1700000000, + post_type: 'message', + message_type: 'group', + group_id: groupId, + message_id: 1, + message_seq: 9748, + user_id: 222, + message: [{ type: 'text', data: { text: 'real' } }], + })); + insert.run(2, groupId, 1799283572, GROUP_MESSAGE_EVENT, 1799283572, 1700000100, JSON.stringify({ + time: 1700000100, + post_type: 'message_sent', + message_type: 'group', + group_id: groupId, + message_id: 2, + message_seq: 1799283572, + user_id: 10001, + message: [{ type: 'file', data: { file: 'test.bin' } }], + })); + insert.run(3, groupId, 1813530543, GROUP_MESSAGE_EVENT, 0, 1700000200, JSON.stringify({ + time: 1700000200, + post_type: 'message', + message_type: 'group', + group_id: groupId, + message_id: 3, + message_seq: 1813530543, + user_id: 0, + message: [{ type: 'text', data: { text: '[引用消息]' } }], + })); + insert.run(4, groupId, 9732, GROUP_MESSAGE_EVENT, 0, 0, JSON.stringify({ + time: 0, + post_type: 'message', + message_type: 'group', + group_id: groupId, + message_id: 4, + message_seq: 9732, + user_id: 0, + message: [{ type: 'text', data: { text: '[已删除]' } }], + })); + insert.run(5, groupId, 1813530544, GROUP_MESSAGE_EVENT, 0, 1700000300, JSON.stringify({ + time: 1700000300, + post_type: 'message', + message_type: 'group', + group_id: groupId, + message_id: 5, + message_seq: 1813530544, + user_id: 800, + message: [{ type: 'text', data: { text: 'quoted inline content' } }], + sender: { + user_id: 800, + nickname: '', + card: '', + role: 'member', + sex: 'unknown', + age: 0, + }, + anonymous: null, + })); + insertPrivate.run(6, 555, 800, PRIVATE_MESSAGE_EVENT, 1234, 1700000400, JSON.stringify({ + time: 1700000400, + post_type: 'message', + message_type: 'private', + sub_type: 'friend', + message_id: 6, + message_seq: 800, + user_id: 555, + message: [{ type: 'text', data: { text: 'real private message' } }], + sender: { user_id: 555, nickname: 'Alice', sex: 'unknown', age: 0 }, + })); + insertPrivate.run(7, 555, 1813530545, PRIVATE_MESSAGE_EVENT, 0, 1700000500, JSON.stringify({ + time: 1700000500, + post_type: 'message', + message_type: 'private', + sub_type: 'friend', + message_id: 7, + message_seq: 1813530545, + user_id: 555, + message: [{ type: 'text', data: { text: 'quoted private content' } }], + sender: { user_id: 555, nickname: '', sex: 'unknown', age: 0 }, + })); + legacy.close(); + + store = new MessageStore(testDbPath); + + expect(store.findLatestAuthoritativeSequence(true, groupId)).toBe(9748); + expect(store.listSessionEvents(true, groupId).map((message) => message.message_seq)).toEqual([9748]); + expect(store.findMeta(2)).toMatchObject({ sequenceAuthoritative: false }); + expect(store.findMeta(3)).toMatchObject({ sequenceAuthoritative: false }); + expect(store.findMeta(4)).toMatchObject({ sequenceAuthoritative: false }); + expect(store.findMeta(5)).toMatchObject({ sequenceAuthoritative: false }); + expect(store.findLatestAuthoritativeSequence(false, 555)).toBe(800); + expect(store.findMeta(6)).toMatchObject({ sequenceAuthoritative: true }); + expect(store.findMeta(7)).toMatchObject({ sequenceAuthoritative: false }); + }); }); describe('listReadSessions', () => { diff --git a/packages/onebot/tests/send-group-file.test.ts b/packages/onebot/tests/send-group-file.test.ts index 0d265382..9e161576 100644 --- a/packages/onebot/tests/send-group-file.test.ts +++ b/packages/onebot/tests/send-group-file.test.ts @@ -18,6 +18,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { OneBotInstanceContext } from '../src/instance-context'; +import { MessageStore } from '../src/message-store'; import { sendGroupMessage } from '../src/modules/message-actions'; function fakeBridge(overrides: Partial = {}): BridgeInterface { @@ -29,12 +30,17 @@ function fakeBridge(overrides: Partial = {}): BridgeInterface { }); } -function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { +function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext { + const store = messageStore + ?? ({ findEvent: () => null, resolveReplySequence: () => 0 } as any); return { uin: '10001', + selfId: 10001, bridge, - messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any, - cacheMessageMeta: vi.fn(), + messageStore: store, + cacheMessageMeta: messageStore + ? (messageId, meta) => messageStore.storeMeta(messageId, meta) + : vi.fn(), mediaStore: {} as any, musicSignUrl: '', } as unknown as OneBotInstanceContext; @@ -75,6 +81,133 @@ describe('send_group_msg with {type:"file"} segment', () => { expect(fileId).toBe('gfid-abc'); }); + it('keeps an OIDB-only group file id separate from a QQ server sequence (#254)', async () => { + const messageStore = new MessageStore(':memory:'); + try { + const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); + const bridge = fakeBridge({ + identity: { nickname: 'Bot' }, + apis: { + message: { sendGroup: vi.fn() }, + groupFile: { publish }, + } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge, messageStore); + + const result = await sendGroupMessage(ctx, 12345, [{ + type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 }, + }] as any, false); + + expect(result.messageId).not.toBe(0); + expect(messageStore.findMeta(result.messageId)).toMatchObject({ + sequence: 0, + sequenceAuthoritative: false, + }); + expect(messageStore.findEvent(result.messageId)).toMatchObject({ message_seq: 0 }); + expect(messageStore.findLatestAuthoritativeSequence(true, 12345)).toBeNull(); + } finally { + messageStore.close(); + } + }); + + it('rejects replying to an OIDB-only group file id as a QQ sequence (#254)', async () => { + const messageStore = new MessageStore(':memory:'); + try { + const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt); + const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); + const bridge = fakeBridge({ + identity: { nickname: 'Bot' }, + apis: { + message: { sendGroup }, + groupFile: { publish }, + } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge, messageStore); + + const file = await sendGroupMessage(ctx, 12345, [{ + type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 }, + }] as any, false); + + await expect(sendGroupMessage(ctx, 12345, [ + { type: 'reply', data: { id: file.messageId } }, + { type: 'text', data: { text: 'received' } }, + ] as any, false)).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'reply', + }); + expect(sendGroup).not.toHaveBeenCalled(); + } finally { + messageStore.close(); + } + }); + + it('rejects a local-only reply id even when its full event was not cached', async () => { + const messageStore = new MessageStore(':memory:'); + try { + const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt); + const bridge = fakeBridge({ + apis: { message: { sendGroup } } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge, messageStore); + messageStore.storeMeta(77, { + isGroup: true, + targetId: 12345, + sequence: 0, + sequenceAuthoritative: false, + eventName: 'group_message', + clientSequence: 0, + random: 42, + timestamp: 1700000000, + }); + + await expect(sendGroupMessage(ctx, 12345, [ + { type: 'reply', data: { id: 77 } }, + { type: 'text', data: { text: 'received' } }, + ] as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'reply' }); + expect(sendGroup).not.toHaveBeenCalled(); + } finally { + messageStore.close(); + } + }); + + it('does not apply local-only reply metadata from another group', async () => { + const messageStore = new MessageStore(':memory:'); + try { + const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt); + const bridge = fakeBridge({ + identity: { nickname: 'Bot' }, + apis: { message: { sendGroup } } as any, + resolveUserUid: vi.fn(), + } as any); + const ctx = makeCtx(bridge, messageStore); + messageStore.storeMeta(77, { + isGroup: true, + targetId: 99999, + sequence: 0, + sequenceAuthoritative: false, + eventName: 'group_message', + clientSequence: 0, + random: 42, + timestamp: 1700000000, + }); + + await sendGroupMessage(ctx, 12345, [ + { type: 'reply', data: { id: 77 } }, + { type: 'text', data: { text: 'direct sequence' } }, + ] as any, false); + + expect(sendGroup).toHaveBeenCalledWith(12345, [ + { type: 'reply', replySeq: 77 }, + { type: 'text', text: 'direct sequence' }, + ]); + } finally { + messageStore.close(); + } + }); + it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => { const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt); const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); diff --git a/packages/protocol/src/msg-push/fetch-group-history.ts b/packages/protocol/src/msg-push/fetch-group-history.ts index c9cb87bd..9ef9e7d7 100644 --- a/packages/protocol/src/msg-push/fetch-group-history.ts +++ b/packages/protocol/src/msg-push/fetch-group-history.ts @@ -1,4 +1,5 @@ import type { SendPacketResult } from '@snowluma/common/packet-sender'; +import { createLogger } from '@snowluma/common/logger'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg'; import type { QQEventVariant } from '../events'; @@ -11,6 +12,8 @@ export const SSO_GET_GROUP_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoG type GroupMessage = Extract; +const log = createLogger('MsgPush.GroupHistory'); + interface RawSender { sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise; } @@ -48,6 +51,22 @@ export async function fetchGroupMessageRange( for (const msg of messages) { const ctx = buildContextFromMessage(msg, selfUin, identity); if (!ctx) continue; + // QQ NT turns deleted/body-null roam entries into MsgType::kNull and its + // FilterBlankSeqsMsg pass removes them before exposing history to callers. + // SsoGetGroupMsg still carries a localized placeholder body for some of + // those entries (for example "[已删除]"), so the ordinary content-less + // filter below cannot recognize them. On the wire these null records have + // neither a sender nor a timestamp; require both structural absences rather + // than matching localized text so a real message is never language-filtered. + if (ctx.fromUin <= 0 && ctx.head.timestamp <= 0) { + log.debug( + 'dropping QQ null roam record: group=%d seq=%d msgId=%d', + groupUin, + ctx.head.sequence, + ctx.head.msgId, + ); + continue; + } for (const ev of decodeGroupMessage(ctx)) { if (ev.kind !== 'group_message' || ev.msgSeq <= 0) continue; // Drop content-less control pushes (the "[空消息]" phantom, #102) just as diff --git a/packages/protocol/tests/msg-push/fetch-group-history.test.ts b/packages/protocol/tests/msg-push/fetch-group-history.test.ts index 48ed6512..acf1230d 100644 --- a/packages/protocol/tests/msg-push/fetch-group-history.test.ts +++ b/packages/protocol/tests/msg-push/fetch-group-history.test.ts @@ -119,6 +119,37 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => { expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] }); }); + it('drops QQ null roam records even when they carry a deleted placeholder (#254)', async () => { + const resp = protobuf_encode({ + body: { + groupUin: 9999, + messages: [ + { + responseHead: { fromUin: 0, grp: { groupUin: 9999 } }, + contentHead: { msgType: 82, sequence: 110, timestamp: 0, msgId: 5110 }, + body: { richText: { elems: [{ text: { str: '[已删除]' } }] } }, + }, + { + responseHead: { fromUin: 222, grp: { groupUin: 9999, memberName: 'Bob' } }, + contentHead: { msgType: 82, sequence: 120, timestamp: 1700000120, msgId: 5120 }, + body: { richText: { elems: [{ text: { str: 'hi' } }] } }, + }, + ], + }, + }); + + const out = await fetchGroupMessageRange( + { sendRawPacket: async () => okResult(resp) }, + identity, + 10001, + 9999, + 100, + 120, + ); + + expect(out.map((message) => message.msgSeq)).toEqual([120]); + }); + it('returns [] on a failed packet or out-of-range request', async () => { const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) }; expect(await fetchGroupMessageRange(failSender, identity, 10001, 9999, 100, 120)).toEqual([]);