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
This commit is contained in:
DrSmoothl committed 2026-07-20 15:33:28 +08:00
1 parent 2c8a8af514
commit 4ba2b27398
17 files changed
+758 -45

No files matched your search

+8 -1
View File
@@ -2,7 +2,7 @@ import { readFile } from 'node:fs/promises';
import type { ApiActionContext } from '../api-handler'; import type { ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler'; import { asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions'; 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 { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
@@ -111,6 +111,9 @@ async function groupTodoRun(
if (!meta.isGroup || meta.targetId !== p.group_id) { if (!meta.isGroup || meta.targetId !== p.group_id) {
return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group'); 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)); await op(p.group_id, BigInt(meta.sequence));
return okResponse(); return okResponse();
} }
@@ -245,6 +248,10 @@ export const actions = [
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); 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); await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, p.code, p.is_set);
return okResponse(); return okResponse();
}, },
@@ -188,6 +188,7 @@ export const ELEMENT_CODECS = {
async fromSegment(data, options) { async fromSegment(data, options) {
const id = intOr(data.id, 0); const id = intOr(data.id, 0);
if (id === 0) return null; if (id === 0) return null;
const meta = options?.resolveReplyMeta?.(id) ?? null;
if (options?.resolveReplySequence) { if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id); const resolved = options.resolveReplySequence(id);
@@ -199,19 +200,27 @@ export const ELEMENT_CODECS = {
}; };
// Try to get additional meta info for better reply display // Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) { if (meta) {
const meta = options.resolveReplyMeta(id); element.replySenderUin = meta.senderUin;
if (meta) { element.replyTime = meta.time;
element.replySenderUin = meta.senderUin; element.replyRandom = meta.random;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
} }
return element; 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. // Backward-compatible path: allow direct seq reply IDs.
return id > 0 ? { type: 'reply', replySeq: id } : null; return id > 0 ? { type: 'reply', replySeq: id } : null;
}, },
+2
View File
@@ -190,6 +190,7 @@ function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEven
isGroup: true, isGroup: true,
targetId: event.groupId, targetId: event.groupId,
sequence: event.msgSeq, sequence: event.msgSeq,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT, eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: event.msgId, random: event.msgId,
@@ -209,6 +210,7 @@ function cachePrivateMessageMeta(
isGroup: false, isGroup: false,
targetId: sessionId, targetId: sessionId,
sequence: msgSeq, sequence: msgSeq,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT, eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random, random,
+3 -1
View File
@@ -38,7 +38,7 @@ import {
} from './modules/message-actions'; } from './modules/message-actions';
import { handleGroupAddRequest } from './modules/request-actions'; import { handleGroupAddRequest } from './modules/request-actions';
import type { ReactionStore } from './reaction-store'; import type { ReactionStore } from './reaction-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types'; import { hasAuthoritativeSequence, type JsonObject, type MessageMeta, type OneBotConfig } from './types';
export interface OneBotInstanceContext { export interface OneBotInstanceContext {
uin: string; uin: string;
@@ -108,12 +108,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const meta = messageStore.findMeta(messageId); const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found'); if (!meta) throw new Error('message not found');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages'); 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');
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set); await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
}, },
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => { fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
const meta = messageStore.findMeta(messageId); const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found'); if (!meta) throw new Error('message not found');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages'); 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 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 users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt }));
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId); const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
+6 -1
View File
@@ -15,7 +15,12 @@ export { MessageElementValidationError } from '@snowluma/protocol/element-manife
export interface ParseMessageOptions { export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null; 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<string | null>; resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
resolveContactArk?: (contactType: string, contactId: number) => string | null | Promise<string | null>; resolveContactArk?: (contactType: string, contactId: number) => string | null | Promise<string | null>;
musicSignUrl?: string; musicSignUrl?: string;
+142 -11
View File
@@ -1,12 +1,20 @@
import { DatabaseSync, type StatementSync } from 'node:sqlite'; import { DatabaseSync, type StatementSync } from 'node:sqlite';
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, MessageMeta } from './types'; import type { JsonObject, MessageMeta } from './types';
import { openSqliteDb } from './sqlite-open'; import { openSqliteDb } from './sqlite-open';
const log = createLogger('OneBot.MessageStore');
export interface ReadSessionTargets { export interface ReadSessionTargets {
groupIds: number[]; groupIds: number[];
privateUserIds: number[]; privateUserIds: number[];
} }
export interface StoreEventOptions {
/** False for locally reconstructed events whose sequence QQ never confirmed. */
sequenceAuthoritative?: boolean;
}
export class MessageStore { export class MessageStore {
private readonly db: DatabaseSync; private readonly db: DatabaseSync;
private readonly stmtStoreEvent: StatementSync; private readonly stmtStoreEvent: StatementSync;
@@ -18,6 +26,7 @@ export class MessageStore {
private readonly stmtListEventsAnchored: StatementSync; private readonly stmtListEventsAnchored: StatementSync;
private readonly stmtListEventsAnchoredForward: StatementSync; private readonly stmtListEventsAnchoredForward: StatementSync;
private readonly stmtListEventsLatest: StatementSync; private readonly stmtListEventsLatest: StatementSync;
private readonly stmtFindLatestAuthoritativeSequence: StatementSync;
private readonly stmtListIncomingC2CSessions: StatementSync; private readonly stmtListIncomingC2CSessions: StatementSync;
constructor(dbPath: string) { constructor(dbPath: string) {
@@ -30,12 +39,13 @@ export class MessageStore {
// Database instance — `close()` finalizes them automatically. // Database instance — `close()` finalizes them automatically.
this.stmtStoreEvent = this.db.prepare( this.stmtStoreEvent = this.db.prepare(
`INSERT INTO messages `INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data) (message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?) VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group, is_group = excluded.is_group,
session_id = excluded.session_id, session_id = excluded.session_id,
sequence = excluded.sequence, sequence = excluded.sequence,
sequence_authoritative = excluded.sequence_authoritative,
event_name = excluded.event_name, event_name = excluded.event_name,
timestamp = excluded.timestamp, timestamp = excluded.timestamp,
data = excluded.data`, data = excluded.data`,
@@ -43,12 +53,13 @@ export class MessageStore {
this.stmtStoreMeta = this.db.prepare( this.stmtStoreMeta = this.db.prepare(
`INSERT INTO messages `INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp) (message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group, is_group = excluded.is_group,
session_id = excluded.session_id, session_id = excluded.session_id,
sequence = excluded.sequence, sequence = excluded.sequence,
sequence_authoritative = excluded.sequence_authoritative,
event_name = excluded.event_name, event_name = excluded.event_name,
client_sequence = excluded.client_sequence, client_sequence = excluded.client_sequence,
random = excluded.random, random = excluded.random,
@@ -60,27 +71,28 @@ export class MessageStore {
); );
this.stmtFindMeta = this.db.prepare( 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( this.stmtResolveReplyGroup = this.db.prepare(
`SELECT sequence `SELECT sequence
FROM messages 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`, LIMIT 1`,
); );
this.stmtResolveReplyPrivate = this.db.prepare( this.stmtResolveReplyPrivate = this.db.prepare(
`SELECT sequence `SELECT sequence
FROM messages FROM messages
WHERE is_group = 0 AND message_hash = ? WHERE is_group = 0 AND message_hash = ? AND sequence_authoritative = 1
LIMIT 1`, LIMIT 1`,
); );
this.stmtListEventsAnchored = this.db.prepare( this.stmtListEventsAnchored = this.db.prepare(
`SELECT data `SELECT data
FROM messages 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 ORDER BY sequence DESC
LIMIT ?`, LIMIT ?`,
); );
@@ -88,7 +100,8 @@ export class MessageStore {
this.stmtListEventsAnchoredForward = this.db.prepare( this.stmtListEventsAnchoredForward = this.db.prepare(
`SELECT data `SELECT data
FROM messages 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 ORDER BY sequence ASC
LIMIT ?`, LIMIT ?`,
); );
@@ -97,10 +110,19 @@ export class MessageStore {
`SELECT data `SELECT data
FROM messages FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
AND sequence_authoritative = 1 AND sequence > 0
ORDER BY sequence DESC ORDER BY sequence DESC
LIMIT ?`, 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( this.stmtListIncomingC2CSessions = this.db.prepare(
`SELECT session_id `SELECT session_id
FROM messages FROM messages
@@ -124,13 +146,23 @@ export class MessageStore {
sessionId: number, sessionId: number,
sequence: number, sequence: number,
eventName: string, eventName: string,
event: JsonObject event: JsonObject,
options: StoreEventOptions = {},
): void { ): void {
if (!isValidMessageId(messageId)) return; if (!isValidMessageId(messageId)) return;
const json = JSON.stringify(event); const json = JSON.stringify(event);
const timestamp = toInt(event.time); 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 { storeMeta(messageId: number, meta: MessageMeta): void {
@@ -140,6 +172,7 @@ export class MessageStore {
meta.isGroup ? 1 : 0, meta.isGroup ? 1 : 0,
meta.targetId, meta.targetId,
meta.sequence, meta.sequence,
meta.sequenceAuthoritative === false ? 0 : 1,
meta.eventName, meta.eventName,
meta.clientSequence, meta.clientSequence,
meta.random, meta.random,
@@ -166,6 +199,7 @@ export class MessageStore {
is_group: number; is_group: number;
session_id: number; session_id: number;
sequence: number; sequence: number;
sequence_authoritative: number;
event_name: string; event_name: string;
client_sequence: number; client_sequence: number;
random: number; random: number;
@@ -178,6 +212,7 @@ export class MessageStore {
isGroup: row.is_group === 1, isGroup: row.is_group === 1,
targetId: row.session_id, targetId: row.session_id,
sequence: row.sequence, sequence: row.sequence,
sequenceAuthoritative: row.sequence_authoritative === 1,
eventName: row.event_name, eventName: row.event_name,
clientSequence: row.client_sequence, clientSequence: row.client_sequence,
random: row.random, random: row.random,
@@ -240,6 +275,16 @@ export class MessageStore {
return result; 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 * Build read-report targets from current groups plus genuine incoming C2C
* sessions. `is_group = 0` alone is insufficient: group temp sessions use * sessions. `is_group = 0` alone is insufficient: group temp sessions use
@@ -277,6 +322,7 @@ export class MessageStore {
is_group INTEGER NOT NULL, is_group INTEGER NOT NULL,
session_id INTEGER NOT NULL, session_id INTEGER NOT NULL,
sequence INTEGER NOT NULL, sequence INTEGER NOT NULL,
sequence_authoritative INTEGER NOT NULL DEFAULT 1,
event_name TEXT NOT NULL, event_name TEXT NOT NULL,
client_sequence INTEGER NOT NULL DEFAULT 0, client_sequence INTEGER NOT NULL DEFAULT 0,
random INTEGER NOT NULL DEFAULT 0, random INTEGER NOT NULL DEFAULT 0,
@@ -284,7 +330,92 @@ export class MessageStore {
data TEXT 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_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;
}
} }
} }
+119 -19
View File
@@ -10,7 +10,7 @@ import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '
import { MessageElementValidationError, parseMessage } from '../message-parser'; import { MessageElementValidationError, parseMessage } from '../message-parser';
import type { MessageStore } from '../message-store'; import type { MessageStore } from '../message-store';
import { sameSelfSentMessage } from '../self-sent-event'; 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'); const log = createLogger('OneBot');
@@ -92,7 +92,7 @@ export async function getGroupMsgHistory(
let anchorSequence: number | undefined; let anchorSequence: number | undefined;
if (hasAnchor) { if (hasAnchor) {
const meta = messageStore.findMeta(messageId as number); 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; anchorSequence = meta.sequence;
} }
@@ -120,7 +120,7 @@ export async function getFriendMsgHistory(
let anchorSequence: number | undefined; let anchorSequence: number | undefined;
if (hasAnchor) { if (hasAnchor) {
const meta = messageStore.findMeta(messageId as number); 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; anchorSequence = meta.sequence;
} }
@@ -164,15 +164,20 @@ export async function getGroupHistory(
let anchorSeq = 0; let anchorSeq = 0;
if (hasAnchor) { if (hasAnchor) {
const meta = ref.messageStore.findMeta(messageId as number); 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. // Anchor we don't know — best effort from the local store.
return getGroupMsgHistory(ref.messageStore, groupId, messageId, count, reverseOrder); return getGroupMsgHistory(ref.messageStore, groupId, messageId, count, reverseOrder);
} }
anchorSeq = meta.sequence; anchorSeq = meta.sequence;
} else { } else {
const latest = ref.messageStore.listSessionEvents(true, groupId, 1); anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
} }
log.debug(
'group history anchor selected: group=%d source=%s anchorSeq=%d',
groupId,
hasAnchor ? 'message_id' : 'latest_authoritative',
anchorSeq,
);
if (anchorSeq > 0) { if (anchorSeq > 0) {
try { try {
@@ -191,6 +196,12 @@ export async function getGroupHistory(
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path) out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
} }
if (out.length > 0) return out; 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) { } catch (err) {
log.warn( log.warn(
'group history server fetch failed: group=%d anchorSeq=%d count=%d reverseOrder=%s error=%s; using local store', '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; : null;
const belongsToPeer = meta?.targetId === userId const belongsToPeer = meta?.targetId === userId
|| (meta?.targetId === ref.selfId && toHistInt(storedEvent?.target_id) === 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); return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
} }
anchorSeq = meta.sequence; anchorSeq = meta.sequence;
@@ -246,9 +257,14 @@ export async function getFriendHistory(
// Current rows are keyed by conversation peer, so the latest local anchor // Current rows are keyed by conversation peer, so the latest local anchor
// covers both incoming and self-sent messages. Legacy sender-keyed rows are // covers both incoming and self-sent messages. Legacy sender-keyed rows are
// repaired when they are fetched through an explicit anchor. // repaired when they are fetched through an explicit anchor.
const latest = ref.messageStore.listSessionEvents(false, userId, 1); anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(false, userId) ?? 0;
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
} }
log.debug(
'friend history anchor selected: user=%d source=%s anchorSeq=%d',
userId,
hasAnchor ? 'message_id' : 'latest_authoritative',
anchorSeq,
);
if (anchorSeq > 0) { if (anchorSeq > 0) {
try { try {
@@ -279,6 +295,12 @@ export async function getFriendHistory(
out.push(sanitizeMessageEventForApi(json)); out.push(sanitizeMessageEventForApi(json));
} }
if (out.length > 0) return out; 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) { } catch (err) {
log.warn( log.warn(
@@ -369,7 +391,18 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
) as JsonArray; ) as JsonArray;
const fallback = buildBackfillEvent(targetId, replySeq, quotedSender, const fallback = buildBackfillEvent(targetId, replySeq, quotedSender,
reply.replyTime ?? 0, segments, ref.selfId, isGroup, session); 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; return;
} catch (err) { } catch (err) {
log.warn('reply-target backfill tier-2 failed (%s)', err instanceof Error ? err.message : String(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, const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender,
reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }], reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }],
ref.selfId, isGroup, session); 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). // 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<void> { export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
if (!hasAuthoritativeSequence(meta)) {
throw new Error('message has no authoritative QQ sequence and cannot be recalled');
}
if (meta.isGroup) { if (meta.isGroup) {
await bridge.apis.message.recallGroup(meta.targetId, meta.sequence); await bridge.apis.message.recallGroup(meta.targetId, meta.sequence);
} else { } else {
@@ -473,6 +517,9 @@ export async function setEssenceMessage(
): Promise<void> { ): Promise<void> {
const meta = messageStore.findMeta(messageId); const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message'); 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); await bridge.apis.interaction.setEssence(meta.targetId, meta.sequence, meta.random, enable);
} }
@@ -506,16 +553,33 @@ async function finalizeSend(
ref: OneBotInstanceContext, ref: OneBotInstanceContext,
isGroup: boolean, isGroup: boolean,
targetId: number, targetId: number,
receipt: { sequence: number; clientSequence: number; random: number; timestamp: number }, receipt: {
messageId?: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
},
elements: MessageElement[], elements: MessageElement[],
reportEcho = false, reportEcho = false,
): Promise<MessageSendResult> { ): Promise<MessageSendResult> {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT; 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, { ref.cacheMessageMeta(messageId, {
isGroup, isGroup,
targetId, targetId,
sequence: receipt.sequence, sequence: receipt.sequence,
sequenceAuthoritative,
eventName, eventName,
clientSequence: receipt.clientSequence, clientSequence: receipt.clientSequence,
random: receipt.random, random: receipt.random,
@@ -526,10 +590,11 @@ async function finalizeSend(
sessionId: targetId, sessionId: targetId,
messageId, messageId,
sequence: receipt.sequence, sequence: receipt.sequence,
sequenceAuthoritative,
timestamp: receipt.timestamp, timestamp: receipt.timestamp,
elements, elements,
}); });
return reportEcho && echoEvent && receipt.sequence > 0 && receipt.timestamp > 0 return reportEcho && echoEvent && sequenceAuthoritative && receipt.timestamp > 0
? { messageId, echoEvent } ? { messageId, echoEvent }
: { messageId }; : { messageId };
} }
@@ -541,11 +606,20 @@ async function cacheSelfSentMessage(
sessionId: number; // groupId or peer userId sessionId: number; // groupId or peer userId
messageId: number; messageId: number;
sequence: number; sequence: number;
sequenceAuthoritative: boolean;
timestamp: number; timestamp: number;
elements: MessageElement[]; elements: MessageElement[];
}, },
): Promise<JsonObject | null> { ): Promise<JsonObject | null> {
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; if (!Number.isInteger(messageId) || messageId === 0) return null;
// Defensive: tests may mock `ref.messageStore` without the full MessageStore // 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 // Persist before dispatch so `/get_msg` is immediately consistent for a
// client reacting to the synthetic message_sent notification. // 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; return event;
} catch (err) { } catch (err) {
// Never turn a successful QQ send into a failed Action after the fact. // Never turn a successful QQ send into a failed Action after the fact.
@@ -665,6 +748,7 @@ export async function sendPrivateMessage(
senderUin, senderUin,
time, time,
random: meta?.random ?? 0, random: meta?.random ?? 0,
sequenceAuthoritative: meta?.sequenceAuthoritative,
}; };
} }
const meta = ref.messageStore.findMeta(replyMessageId); const meta = ref.messageStore.findMeta(replyMessageId);
@@ -673,6 +757,7 @@ export async function sendPrivateMessage(
senderUin: ref.selfId, senderUin: ref.selfId,
time: meta.timestamp, time: meta.timestamp,
random: meta.random, random: meta.random,
sequenceAuthoritative: meta.sequenceAuthoritative,
}; };
} }
return null; return null;
@@ -838,6 +923,8 @@ export async function sendGroupMessage(
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId); return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
}, },
resolveReplyMeta: (replyMessageId) => { resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
if (!meta || !meta.isGroup || meta.targetId !== groupId) return null;
const event = ref.messageStore.findEvent(replyMessageId); const event = ref.messageStore.findEvent(replyMessageId);
if (event) { if (event) {
return { return {
@@ -847,10 +934,16 @@ export async function sendGroupMessage(
time: typeof event.time === 'number' time: typeof event.time === 'number'
? event.time ? event.time
: parseInt(String(event.time || '0'), 10), : 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), resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
resolveContactArk: (contactType, contactId) => resolveContactArk(ref, contactType, contactId), resolveContactArk: (contactType, contactId) => resolveContactArk(ref, contactType, contactId),
@@ -918,7 +1011,14 @@ export async function sendGroupMessage(
if (!lastReceipt) { if (!lastReceipt) {
let h = 0; let h = 0;
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 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'); if (!lastReceipt) throw new Error('message is empty');
+11 -1
View File
@@ -122,12 +122,23 @@ export interface MessageMeta {
isGroup: boolean; isGroup: boolean;
targetId: number; targetId: number;
sequence: number; sequence: number;
/** Whether `sequence` was confirmed by QQ and is safe for protocol actions. */
sequenceAuthoritative: boolean;
eventName: string; eventName: string;
clientSequence: number; clientSequence: number;
random: number; random: number;
timestamp: 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 = { export const RETCODE = {
ACTION_FAILED: 100, ACTION_FAILED: 100,
INTERNAL_ERROR: 1200, 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'; export type { JsonArray, JsonObject, JsonPrimitive, JsonValue } from '@snowluma/common/json';
@@ -188,6 +188,7 @@ describe('backfillReplyTarget', () => {
expect(store.storeEvent).toHaveBeenCalledWith( expect(store.storeEvent).toHaveBeenCalledWith(
targetId, true, 700, 123, GROUP_MESSAGE_EVENT, targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }), expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }),
{ sequenceAuthoritative: false },
); );
}); });
@@ -207,6 +208,7 @@ describe('backfillReplyTarget', () => {
expect(store.storeEvent).toHaveBeenCalledWith( expect(store.storeEvent).toHaveBeenCalledWith(
targetId, true, 700, 123, GROUP_MESSAGE_EVENT, targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'group' }), expect.objectContaining({ message_id: targetId, message_type: 'group' }),
{ sequenceAuthoritative: false },
); );
}); });
}); });
@@ -145,6 +145,7 @@ describe('registerEventPipeline', () => {
expect(metaCalls[0].meta.isGroup).toBe(false); expect(metaCalls[0].meta.isGroup).toBe(false);
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN); expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
expect(metaCalls[0].meta.sequence).toBe(11); expect(metaCalls[0].meta.sequence).toBe(11);
expect(metaCalls[0].meta.sequenceAuthoritative).toBe(true);
expect(metaCalls[0].meta.random).toBe(555); expect(metaCalls[0].meta.random).toBe(555);
expect(dispatchCalls).toHaveLength(1); expect(dispatchCalls).toHaveLength(1);
@@ -16,6 +16,7 @@ function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
isGroup: true, isGroup: true,
targetId: 100, targetId: 100,
sequence: 555, sequence: 555,
sequenceAuthoritative: true,
eventName: 'group_message', eventName: 'group_message',
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -648,6 +649,19 @@ describe('extended-actions / set_/complete_/cancel_group_todo', () => {
expect(res).toMatchObject({ status: 'failed', retcode: 100 }); 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 () => { it('rejects missing params', async () => {
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 }); 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 }); 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 ─── // ─── Tier 2: nc_get_user_status ───
describe('extended-actions / nc_get_user_status', () => { describe('extended-actions / nc_get_user_status', () => {
@@ -63,6 +63,7 @@ describe('history direction plumbing', () => {
isGroup: true, isGroup: true,
targetId: GROUP_ID, targetId: GROUP_ID,
sequence: 500, sequence: 500,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT, eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -91,6 +92,7 @@ describe('history direction plumbing', () => {
isGroup: false, isGroup: false,
targetId: FRIEND_ID, targetId: FRIEND_ID,
sequence: 700, sequence: 700,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT, eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -124,6 +126,15 @@ describe('history direction plumbing', () => {
message_id: 1, message_id: 1,
message_seq: 900, 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 = { const ref = {
selfId: SELF_ID, selfId: SELF_ID,
bridge: { bridge: {
@@ -136,6 +147,31 @@ describe('history direction plumbing', () => {
const messages = await getGroupHistory(ref, GROUP_ID, 0, 20, false); const messages = await getGroupHistory(ref, GROUP_ID, 0, 20, false);
expect(messages.map((message) => message.message_seq)).toEqual([899, 900]); 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 () => { it('rejects a private anchor from a different friend conversation', async () => {
@@ -144,6 +180,7 @@ describe('history direction plumbing', () => {
isGroup: false, isGroup: false,
targetId: 987654321, targetId: 987654321,
sequence: 800, sequence: 800,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT, eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import type { OneBotInstanceContext } from '../src/instance-context'; 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<typeof vi.fn>): OneBotInstanceContext { function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceContext {
const bridge = { const bridge = {
@@ -95,3 +96,33 @@ describe('outbound message validation at the Action boundary', () => {
expect(bridgeSend).not.toHaveBeenCalled(); 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();
});
});
+159
View File
@@ -3,6 +3,7 @@ import { MessageStore } from '../src/message-store';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id'; import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import fs from 'fs'; import fs from 'fs';
import path from 'path'; import path from 'path';
import { DatabaseSync } from 'node:sqlite';
describe('MessageStore', () => { describe('MessageStore', () => {
const testDbPath = path.join('data', 'test', 'messages-test.db'); const testDbPath = path.join('data', 'test', 'messages-test.db');
@@ -39,6 +40,7 @@ describe('MessageStore', () => {
isGroup: true, isGroup: true,
targetId: groupId, targetId: groupId,
sequence, sequence,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT, eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -61,6 +63,7 @@ describe('MessageStore', () => {
isGroup: false, isGroup: false,
targetId: senderUin, targetId: senderUin,
sequence, sequence,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT, eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -105,6 +108,7 @@ describe('MessageStore', () => {
isGroup: true, isGroup: true,
targetId: sessionId, targetId: sessionId,
sequence, sequence,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT, eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -117,6 +121,7 @@ describe('MessageStore', () => {
isGroup: false, isGroup: false,
targetId: sessionId, targetId: sessionId,
sequence, sequence,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT, eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0, clientSequence: 0,
random: 0, random: 0,
@@ -170,6 +175,7 @@ describe('MessageStore', () => {
isGroup: true, isGroup: true,
targetId: 123456, targetId: 123456,
sequence: 100, sequence: 100,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT, eventName: GROUP_MESSAGE_EVENT,
clientSequence: 1, clientSequence: 1,
random: 12345, random: 12345,
@@ -218,6 +224,159 @@ describe('MessageStore', () => {
expect(messages.map((message) => message.message_seq)).toEqual([1, 2, 3]); 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', () => { describe('listReadSessions', () => {
+136 -3
View File
@@ -18,6 +18,7 @@
import { describe, expect, it, vi } from 'vitest'; import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context'; import type { OneBotInstanceContext } from '../src/instance-context';
import { MessageStore } from '../src/message-store';
import { sendGroupMessage } from '../src/modules/message-actions'; import { sendGroupMessage } from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface { function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
@@ -29,12 +30,17 @@ function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
}); });
} }
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext { function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext {
const store = messageStore
?? ({ findEvent: () => null, resolveReplySequence: () => 0 } as any);
return { return {
uin: '10001', uin: '10001',
selfId: 10001,
bridge, bridge,
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any, messageStore: store,
cacheMessageMeta: vi.fn(), cacheMessageMeta: messageStore
? (messageId, meta) => messageStore.storeMeta(messageId, meta)
: vi.fn(),
mediaStore: {} as any, mediaStore: {} as any,
musicSignUrl: '', musicSignUrl: '',
} as unknown as OneBotInstanceContext; } as unknown as OneBotInstanceContext;
@@ -75,6 +81,133 @@ describe('send_group_msg with {type:"file"} segment', () => {
expect(fileId).toBe('gfid-abc'); 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 () => { 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 sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined); const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
@@ -1,4 +1,5 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender'; import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg'; import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg';
import type { QQEventVariant } from '../events'; 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<QQEventVariant, { kind: 'group_message' }>; type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
const log = createLogger('MsgPush.GroupHistory');
interface RawSender { interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>; sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
} }
@@ -48,6 +51,22 @@ export async function fetchGroupMessageRange(
for (const msg of messages) { for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity); const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) continue; 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)) { for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind !== 'group_message' || ev.msgSeq <= 0) continue; if (ev.kind !== 'group_message' || ev.msgSeq <= 0) continue;
// Drop content-less control pushes (the "[空消息]" phantom, #102) just as // Drop content-less control pushes (the "[空消息]" phantom, #102) just as
@@ -119,6 +119,37 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => {
expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] }); 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<SsoGetGroupMsgResponse>({
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 () => { it('returns [] on a failed packet or out-of-range request', async () => {
const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) }; const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) };
expect(await fetchGroupMessageRange(failSender, identity, 10001, 9999, 100, 120)).toEqual([]); expect(await fetchGroupMessageRange(failSender, identity, 10001, 9999, 100, 120)).toEqual([]);