fix(onebot): correct private message history (#256)

Use the C2C roam cursor and canonical NT sequence for bidirectional history. Persist direction-aware recall tombstones so recalled messages cannot reappear.
This commit is contained in:
DrSmoothl committed 2026-07-20 22:25:13 +08:00
1 parent 88216ce644
commit 4aa2cd1693
37 files changed
+1853 -242

No files matched your search

+15
View File
@@ -235,7 +235,14 @@ export interface FriendMessage extends QQEvent {
* index can preserve the exact C2C peer instead of re-resolving its UIN. */
senderUid?: string;
senderNick: string;
/** Sender-local sequence exposed as OneBot message_seq and used by replies. */
msgSeq: number;
/** Bidirectional C2C sequence used for history/actions and canonical message ids. */
ntMsgSeq?: number;
/** Sender-local sequence used by private recall requests. */
clientSeq?: number;
/** False only when an older packet omitted ContentHead field 11. */
sequenceAuthoritative?: boolean;
msgId: number;
elements: MessageElement[];
}
@@ -263,6 +270,9 @@ export interface TempMessage extends QQEvent {
groupId: number;
senderNick: string;
msgSeq: number;
ntMsgSeq?: number;
clientSeq?: number;
sequenceAuthoritative?: boolean;
elements: MessageElement[];
}
@@ -314,7 +324,12 @@ export interface GroupAdminEvent extends QQEvent {
export interface FriendRecall extends QQEvent {
kind: 'friend_recall';
userUin: number;
/** Legacy alias retained for converters; this is the sender-local sequence. */
msgSeq: number;
/** Sender-local sequence carried by the recall protocol. */
clientSeq?: number;
/** True for subtype 139, where the logged-in account recalled its own send. */
recalledBySelf?: boolean;
}
export interface GroupRecallEvent extends QQEvent {
@@ -13,7 +13,10 @@ export interface MsgPushHead {
/** C2C command (`contentHead` field 3). Discriminates control pushes — see
* `isC2cControlPush` in ./blank-filter. */
readonly c2cCmd: number;
/** Sender-local C2C client sequence (field 5), or the group sequence. */
readonly sequence: number;
/** Bidirectional C2C sequence (field 11); zero on groups/legacy packets. */
readonly ntMsgSeq: number;
readonly timestamp: number;
readonly msgId: number;
}
@@ -68,6 +71,7 @@ export function buildContextFromMessage(
subType: msg.contentHead.subType ?? 0,
c2cCmd: msg.contentHead.c2cCmd ?? 0,
sequence: msg.contentHead.sequence ?? 0,
ntMsgSeq: msg.contentHead.ntMsgSeq ?? 0,
timestamp: msg.contentHead.timestamp ?? 0,
msgId: msg.contentHead.msgId ?? 0,
};
@@ -173,6 +173,8 @@ function decodeFriendRecall(ctx: MsgPushContext): QQEventVariant[] {
selfUin: ctx.selfUin,
userUin: resolveUidToUin(ctx.identity, 0, peerUid, ctx.fromUin),
msgSeq: recall.info.clientSequence ?? 0,
clientSeq: recall.info.clientSequence ?? 0,
recalledBySelf: isSelfRecall,
};
return [ev];
}
@@ -27,6 +27,7 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
const elements = decodeRichBody(ctx.body, false);
const sentBySelf = ctx.fromUin > 0 && ctx.fromUin === ctx.selfUin;
const peerUin = sentBySelf ? (ctx.responseHead?.toUin ?? 0) : ctx.fromUin;
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
// Stash the approval msgseq from a private group-invite card so a later
// `set_group_add_request` can approve a bot self-invite (issue #125).
for (const el of elements) {
@@ -43,6 +44,9 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
senderUid: ctx.fromUid,
...(peerUin > 0 ? { peerUin } : {}),
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
msgId: ctx.head.msgId & 0x7FFFFFFF,
elements,
senderNick: '',
@@ -3,12 +3,16 @@ import type { MsgPushDecoder } from '../registry';
import { decodeRichBody } from '../rich-body-decoder';
export const decodeTempMessage: MsgPushDecoder = (ctx) => {
const sequenceAuthoritative = ctx.head.ntMsgSeq > 0;
const ev: TempMessage = {
kind: 'temp_message',
time: ctx.head.timestamp,
selfUin: ctx.selfUin,
senderUin: ctx.fromUin,
msgSeq: ctx.head.sequence,
ntMsgSeq: ctx.head.ntMsgSeq,
clientSeq: ctx.head.sequence,
sequenceAuthoritative,
elements: decodeRichBody(ctx.body, false),
groupId: 0,
senderNick: '',
@@ -1,6 +1,13 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type {
SsoGetC2cMsg,
SsoGetC2cMsgResponse,
SsoGetRoamMsg,
SsoGetRoamMsgResponse,
} from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { isBlankMessage, isC2cControlPush } from './blank-filter';
@@ -8,6 +15,9 @@ import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
export const SSO_GET_C2C_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetC2cMsg';
export const SSO_GET_ROAM_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetRoamMsg';
const log = createLogger('MsgPush.C2CHistory');
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
@@ -15,9 +25,52 @@ interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
export interface C2cRoamPage {
messages: FriendMessage[];
cursor: { time: number; random: number };
}
function requirePacketResponse(result: SendPacketResult, command: string): Uint8Array {
if (!result.success) {
throw new Error(`${command} transport failed: ${result.errorMessage || 'unknown transport error'}`);
}
if (!result.gotResponse || !result.responseData || result.responseData.length === 0) {
throw new Error(`${command} response is empty`);
}
return result.responseData;
}
function decodeC2cMessages(
messages: readonly PushMsgBody[],
identity: IdentityService,
selfUin: number,
source: string,
): FriendMessage[] {
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) {
throw new Error(`${source} response contains a message without a content head`);
}
if (isC2cControlPush(ctx.head)) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message') continue;
if (isBlankMessage(ev.elements, ctx.body)) continue;
if (ev.sequenceAuthoritative === false || !ev.ntMsgSeq || ev.ntMsgSeq <= 0) {
throw new Error(
`${source} message is missing the canonical NT sequence `
+ `(clientSeq=${ev.clientSeq ?? ev.msgSeq} from=${ev.senderUin} time=${ev.time})`,
);
}
out.push(ev);
}
}
return out;
}
/**
* Fetch one [startSeq, endSeq] window of private (c2c) history from the server
* via `SsoGetC2cMsg`, decoding each returned message with the regular friend
* Fetch one [startSeq, endSeq] NT-sequence window of private (c2c) history from
* the server via `SsoGetC2cMsg`, decoding each returned message with the regular friend
* decoder. `friendUid` is the conversation peer's UID. Returns `friend_message`
* events sorted oldest→newest by sequence. One packet per call — the caller
* owns chunking/throttling.
@@ -39,24 +92,76 @@ export async function fetchC2cMessageRange(
});
const res = await sender.sendRawPacket(SSO_GET_C2C_MSG_CMD, req);
if (!res.success || !res.gotResponse || !res.responseData) return [];
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(res.responseData);
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(res, 'SsoGetC2cMsg'),
);
const messages = decoded?.messages ?? [];
const out: FriendMessage[] = [];
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) continue;
for (const ev of decodeFriendMessage(ctx)) {
if (ev.kind !== 'friend_message' || ev.msgSeq <= 0) continue;
// Drop C2C control/system signals and content-less pushes (the "[空消息]"
// phantom, #102) just as QQ NT does on its roam/history fetch — keep
// history parity with live (parseMsgPush).
if (isC2cControlPush(ctx.head) || isBlankMessage(ev.elements, ctx.body)) continue;
out.push(ev);
}
}
out.sort((a, b) => a.msgSeq - b.msgSeq);
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
log.debug(
'SsoGetC2cMsg decoded friend=%s range=%d-%d wire=%d usable=%d',
friendUid,
startSeq,
endSeq,
messages.length,
out.length,
);
return out;
}
/**
* Fetch one timestamp-cursor page of C2C roaming history. QQ uses this endpoint
* for an unanchored latest page; it returns messages from both participants.
*/
export async function fetchC2cRoamMessagePage(
sender: RawSender,
identity: IdentityService,
selfUin: number,
friendUid: string,
beforeTime: number,
count: number,
beforeRandom = 0,
): Promise<C2cRoamPage> {
if (!friendUid) throw new Error('SsoGetRoamMsg friend uid is required');
if (!Number.isSafeInteger(beforeTime) || beforeTime < 0 || beforeTime > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor time is invalid: ${String(beforeTime)}`);
}
if (!Number.isSafeInteger(beforeRandom) || beforeRandom < 0 || beforeRandom > 0xffff_ffff) {
throw new Error(`SsoGetRoamMsg cursor random is invalid: ${String(beforeRandom)}`);
}
if (!Number.isSafeInteger(count) || count < 1 || count > 200) {
throw new Error(`SsoGetRoamMsg count is invalid: ${String(count)}`);
}
const req = protobuf_encode<SsoGetRoamMsg>({
friendUid,
time: beforeTime,
random: beforeRandom,
count,
direction: true,
});
const result = await sender.sendRawPacket(SSO_GET_ROAM_MSG_CMD, req);
const response = protobuf_decode<SsoGetRoamMsgResponse>(
requirePacketResponse(result, 'SsoGetRoamMsg'),
);
if (response.friendUid && response.friendUid !== friendUid) {
throw new Error(`SsoGetRoamMsg response friend uid mismatch: ${response.friendUid}`);
}
const wireMessages = response.messages ?? [];
const messages = decodeC2cMessages(wireMessages, identity, selfUin, 'SsoGetRoamMsg');
messages.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0) || a.time - b.time);
const cursor = { time: response.timestamp ?? 0, random: response.random ?? 0 };
log.debug(
'SsoGetRoamMsg decoded friend=%s before=%d/%d count=%d wire=%d usable=%d next=%d/%d',
friendUid,
beforeTime,
beforeRandom,
count,
wireMessages.length,
messages.length,
cursor.time,
cursor.random,
);
return { messages, cursor };
}
+27 -2
View File
@@ -26,7 +26,13 @@ import { SysMsgDedup } from './sysmsg-dedup';
export { SysMsgDedup } from './sysmsg-dedup';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export { SSO_GET_C2C_MSG_CMD, fetchC2cMessageRange } from './fetch-c2c-history';
export {
SSO_GET_C2C_MSG_CMD,
SSO_GET_ROAM_MSG_CMD,
fetchC2cMessageRange,
fetchC2cRoamMessagePage,
type C2cRoamPage,
} from './fetch-c2c-history';
export const MSG_PUSH_CMD = 'trpc.msg.olpush.OlPushService.MsgPush';
@@ -90,6 +96,21 @@ function describeUndecodedBody(body: PushMsgBody | undefined): string {
return `elems=[${parts.join('; ')}]${extras.length ? ` ${extras.join(' ')}` : ''}`;
}
function warnMissingC2cSequence(ev: QQEventVariant, fromUin: number): void {
if (
(ev.kind === 'friend_message' || ev.kind === 'temp_message')
&& ev.sequenceAuthoritative === false
) {
log.warn(
'c2c message omitted NT sequence; keeping non-authoritative client sequence (kind=%s from=%d clientSeq=%d time=%d)',
ev.kind,
fromUin,
ev.clientSeq ?? ev.msgSeq,
ev.time,
);
}
}
export function parseMsgPush(
pkt: PacketInfo,
identity: IdentityService,
@@ -111,7 +132,10 @@ export function parseMsgPush(
}
return false;
}
if ((ev as { elements?: unknown[] }).elements?.length !== 0) return true;
if ((ev as { elements?: unknown[] }).elements?.length !== 0) {
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
}
// Empty-element message that's NOT a known control cmd. Drop it when the body
// is genuinely empty (a content-less push we don't yet classify by c2cCmd).
// If instead the body *had* content we just couldn't decode, keep the
@@ -121,6 +145,7 @@ export function parseMsgPush(
log.warn('message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.subType,
describeUndecodedBody(ctx.body));
warnMissingC2cSequence(ev, ctx.fromUin);
return true;
}
return false;
@@ -395,22 +395,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
);
}
// Reply / quote. For a c2c (friend) reply the canonical replied-to sequence
// is the srcMsg reserve's `friendSequence`, NOT `origSeqs[0]` — origSeqs
// carries the per-sender clientSequence, which doesn't match how the
// original message is keyed (by its server/private sequence), so resolving
// the reply (and get_msg on the quoted message) would miss. Mirrors
// Lagrange's `Sequence = reserve.FriendSequence ?? OrigSeqs[0]`
// (ForwardEntity.cs). Group replies keep origSeqs[0] (the shared group seq).
// Reply / quote. `origSeqs[0]` is the shared group sequence for groups and
// the quoted sender's local client sequence for C2C. The latter is not the
// conversation-wide NT sequence used by private history/message ids, so the
// OneBot layer resolves it with peer + sender direction + quote time.
if (elem.srcMsg) {
// The reply resolves to srcMsg.origSeqs[0] — for BOTH group (shared group
// seq) and c2c. On-target capture (#114 / #124) proved origSeqs[0] equals
// the quoted message's head.sequence, i.e. the seq its message_id is
// hashed from. reserve.friendSequence is a small friend-relationship
// counter that does NOT match (e.g. 25 vs a head.sequence of 12707), so
// the earlier `friendSequence` override made reply.id != the quoted
// message_id: get_msg(reply_id) missed and a quoted File's content came
// back empty.
// On-target capture (#114 / #124) also proved reserve.friendSequence is a
// small friend-relationship counter, not either usable message sequence.
const src = elem.srcMsg;
const replySeq = src.origSeqs?.[0] ?? 0;
if (replySeq > 0) {