feat: support client private-message reporting

Handle confirmed private messages sent from the client and preserve account isolation when sessions change. Surface unavailable messages without reporting incomplete content.

Refs #528.
This commit is contained in:
DrSmoothl committed 2026-10-21 16:59:26 +08:00
1 parent 617e7581dd
commit 491b531841
12 files changed
+963 -4

No files matched your search

@@ -0,0 +1,157 @@
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender } from '@snowluma/common/packet-sender';
import { isRealUin } from '@snowluma/common/uin';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { FriendMessage } from '../events';
import type { IdentityService } from '../identity-service';
import { classifyMessageSurvival } from './blank-filter';
import { buildContextFromMessage } from './context';
import { decodeFriendMessage } from './decoders/friend-message';
import { PkgType } from './enums';
import { SSO_GET_C2C_MSG_CMD } from './fetch-c2c-history';
import { requirePacketResponse } from './packet-response';
export interface ClientMessageReceipt {
readonly peerUid: string;
readonly clientSequence: number;
readonly sequence: number;
readonly timestamp: number;
}
export function decodeClientMessageReceipt(pkt: PacketInfo, selfUin: string): ClientMessageReceipt {
if (
pkt.source !== 'client-message' ||
pkt.serviceCmd !== CLIENT_MESSAGE_RECEIPT_CMD ||
!isRealUin(selfUin) ||
pkt.uin !== selfUin
) {
throw new Error('Client message receipt has an invalid source or account');
}
if (pkt.retCode !== 0) {
throw new Error(`Client message receipt is unavailable (status=${pkt.retCode})`);
}
const body = Buffer.from(pkt.body);
if (body.length < 12 || body.length > 8 + 128 + 65536) {
throw new Error('Client message receipt has an invalid length');
}
const peerLength = body[1]!;
const ackOffset = 8 + peerLength;
if (
body[0] !== 1 ||
body.readUInt16LE(2) !== 0 ||
peerLength < 3 ||
peerLength > 128 ||
ackOffset >= body.length ||
body.length - ackOffset > 65536
) {
throw new Error('Client message receipt has an invalid envelope');
}
const peerUid = body.subarray(8, ackOffset).toString('utf8');
const clientSequence = body.readUInt32LE(4);
if (!/^u_[A-Za-z0-9_-]+$/.test(peerUid) || clientSequence === 0) {
throw new Error('Client message receipt has an invalid message identity');
}
const ack = protobuf_decode<SendMessageResponse>(body.subarray(ackOffset));
if (
(ack.result ?? 0) !== 0 ||
(ack.reviewResult ?? 0) !== 0 ||
(ack.serverResult?.code ?? 0) !== 0
) {
throw new Error('Client message was not accepted');
}
const sequence = ack.privateSequence;
const timestamp = ack.timestamp1;
if (!sequence || !timestamp || (ack.groupSequence ?? 0) !== 0) {
throw new Error('Client message receipt has no valid private message confirmation');
}
return { peerUid, clientSequence, sequence, timestamp };
}
export async function fetchClientMessage(
sender: PacketSender,
identity: IdentityService,
receipt: ClientMessageReceipt,
): Promise<FriendMessage> {
const request = protobuf_encode<SsoGetC2cMsg>({
friendUid: receipt.peerUid,
startSequence: receipt.sequence,
endSequence: receipt.sequence,
});
const result = await sender.sendPacket(SSO_GET_C2C_MSG_CMD, Buffer.from(request));
const response = protobuf_decode<SsoGetC2cMsgResponse>(
requirePacketResponse(result, 'Client message lookup'),
);
if (response.friendUid && response.friendUid !== receipt.peerUid) {
throw new Error('Client message lookup returned another conversation');
}
if (response.messages?.length !== 1) {
throw new Error(
`Client message lookup expected one message, received ${response.messages?.length ?? 0}`,
);
}
const message = response.messages[0]!;
const head = message.contentHead;
const route = message.responseHead;
const selfUin = Number(identity.uin);
if (
!head ||
!route ||
route.fromUin !== selfUin ||
route.toUid !== receipt.peerUid ||
!route.toUin ||
route.grp != null ||
head.ntMsgSeq !== receipt.sequence ||
head.sequence !== receipt.clientSequence ||
head.timestamp !== receipt.timestamp
) {
throw new Error('Client message lookup did not match the confirmed message');
}
if (
![
PkgType.PrivateMessage,
PkgType.PrivateRecordMessage,
PkgType.PrivateFileMessage,
PkgType.ForwardFakePrivateMessage,
].includes(head.msgType ?? 0)
) {
throw new Error('Client message lookup returned an unsupported message type');
}
const context = buildContextFromMessage(message, selfUin, identity);
if (!context) {
throw new Error('Client message lookup has no message context');
}
const events = decodeFriendMessage(context);
const event = events[0];
if (
events.length !== 1 ||
event?.kind !== 'friend_message' ||
classifyMessageSurvival(context.head, event.elements, context.body) !== 'keep'
) {
throw new Error('Client message lookup has no supported message content');
}
return event;
}
+1
View File
@@ -26,6 +26,7 @@ import { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export { deriveSysMsgDedupIdentity, SysMsgDedup } from './sysmsg-dedup';
export type { SysMsgDedupIdentity } from './sysmsg-dedup';
export { decodeClientMessageReceipt, fetchClientMessage } from './client-message-receipt';
export { SSO_GET_GROUP_MSG_CMD, fetchGroupMessageRange } from './fetch-group-history';
export {
+11 -1
View File
@@ -85,8 +85,18 @@ export class IncomingPacketPipeline {
}
process(pkt: PacketInfo): Promise<void> {
return this.processWithHandlers(pkt, this.cmdHandlers_.get(pkt.serviceCmd));
}
processEvents(pkt: PacketInfo, events: readonly QQEventVariant[]): Promise<void> {
return this.processWithHandlers(pkt, [() => [...events]]);
}
private processWithHandlers(
pkt: PacketInfo,
handlers: readonly CmdParser[] | undefined,
): Promise<void> {
const startedAt = Date.now();
const handlers = this.cmdHandlers_.get(pkt.serviceCmd);
if (!handlers) {
this.packetLog.trace(() => [
@@ -0,0 +1,292 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { CLIENT_MESSAGE_RECEIPT_CMD, type PacketInfo } from '@snowluma/common/protocol-types';
import type { PacketSender, SendPacketResult } from '@snowluma/common/packet-sender';
import type { SendMessageResponse } from '@snowluma/proto-defs/action';
import type { SsoGetC2cMsg, SsoGetC2cMsgResponse } from '@snowluma/proto-defs/get-c2c-msg';
import type { PushMsgBody } from '@snowluma/proto-defs/message';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { IdentityService } from '../../src/identity-service';
import {
decodeClientMessageReceipt,
fetchClientMessage,
} from '../../src/msg-push/client-message-receipt';
import { SSO_GET_C2C_MSG_CMD } from '../../src/msg-push/fetch-c2c-history';
const self = '10001';
const peer = 'u_test_peer';
const time = 1_700_000_000;
const identities: IdentityService[] = [];
afterEach(async () => {
await Promise.all(identities.splice(0).map((identity) => identity.close()));
});
function packet(ack: SendMessageResponse = { privateSequence: 87, timestamp1: time }): PacketInfo {
const uid = Buffer.from(peer);
const header = Buffer.alloc(8);
header[0] = 1;
header[1] = uid.length;
header.writeUInt32LE(9, 4);
return {
pid: 1234,
uin: self,
seqId: 42,
retCode: 0,
fromClient: false,
source: 'client-message',
serviceCmd: CLIENT_MESSAGE_RECEIPT_CMD,
body: Buffer.concat([header, uid, protobuf_encode<SendMessageResponse>(ack)]),
};
}
function message(): PushMsgBody {
return {
responseHead: { fromUin: Number(self), fromUid: 'u_test_self', toUin: 20002, toUid: peer },
contentHead: { msgType: 166, sequence: 9, ntMsgSeq: 87, timestamp: time, msgId: 123456 },
body: { richText: { elems: [{ text: { str: 'hello' } }, { face: { index: 1 } }] } },
};
}
function setup(messages = [message()], friendUid = peer) {
const identity = IdentityService.memory(self);
identities.push(identity);
const sendPacket = vi.fn<PacketSender['sendPacket']>(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<SsoGetC2cMsgResponse>({ friendUid, messages })),
}));
const receipt = decodeClientMessageReceipt(packet(), self);
return {
sendPacket,
identity,
receipt,
run: () => fetchClientMessage({ sendPacket }, identity, receipt),
};
}
describe('client message receipts', () => {
it('decodes a confirmation and retrieves exactly its conversation and sequence', async () => {
const ctx = setup();
expect(ctx.receipt).toEqual({
peerUid: peer,
clientSequence: 9,
sequence: 87,
timestamp: time,
});
const event = await ctx.run();
expect(ctx.sendPacket).toHaveBeenCalledOnce();
const [cmd, body] = ctx.sendPacket.mock.calls[0]!;
expect(cmd).toBe(SSO_GET_C2C_MSG_CMD);
expect(protobuf_decode<SsoGetC2cMsg>(body)).toMatchObject({
friendUid: peer,
startSequence: 87,
endSequence: 87,
});
expect(event).toMatchObject({
kind: 'friend_message',
selfUin: 10001,
senderUin: 10001,
peerUin: 20002,
clientSeq: 9,
ntMsgSeq: 87,
sequenceAuthoritative: true,
time,
elements: [
{ type: 'text', text: 'hello' },
{ type: 'face', faceId: 1 },
],
});
});
it.each([
{ source: undefined },
{ serviceCmd: 'MessageSvc.PbSendMsg' },
{ uin: '20002' },
{ retCode: -1 },
] satisfies Partial<PacketInfo>[])('rejects invalid provenance or status: %j', (patch) => {
expect(() => decodeClientMessageReceipt({ ...packet(), ...patch }, self)).toThrow();
});
it.each([
{ result: 1 },
{ reviewResult: 1 },
{ serverResult: { code: -1 } },
{ privateSequence: 0 },
{ timestamp1: 0 },
{ groupSequence: 5 },
] satisfies SendMessageResponse[])(
'rejects an unsuccessful or incomplete confirmation: %j',
(patch) => {
expect(() =>
decodeClientMessageReceipt(
packet({ privateSequence: 87, timestamp1: time, ...patch }),
self,
),
).toThrow();
},
);
it.each([
[
'version',
(body: Buffer) => {
body[0] = 2;
},
],
[
'reserved',
(body: Buffer) => {
body[2] = 1;
},
],
[
'uid length',
(body: Buffer) => {
body[1] = 129;
},
],
[
'uid',
(body: Buffer) => {
body[8] = 0xff;
},
],
[
'client sequence',
(body: Buffer) => {
body.writeUInt32LE(0, 4);
},
],
] as const)('rejects a malformed %s', (_name, mutate) => {
const pkt = packet();
const body = Buffer.from(pkt.body);
mutate(body);
expect(() => decodeClientMessageReceipt({ ...pkt, body }, self)).toThrow();
});
it('rejects truncated and excessive bodies', () => {
for (const body of [
new Uint8Array(),
packet().body.subarray(0, 8 + peer.length),
new Uint8Array(8 + 128 + 65537),
]) {
expect(() => decodeClientMessageReceipt({ ...packet(), body }, self)).toThrow();
}
});
it.each([
[
'sender',
(msg: PushMsgBody) => {
msg.responseHead!.fromUin = 20002;
},
],
[
'recipient',
(msg: PushMsgBody) => {
msg.responseHead!.toUid = 'u_other';
},
],
[
'missing recipient',
(msg: PushMsgBody) => {
delete msg.responseHead!.toUin;
},
],
[
'client sequence',
(msg: PushMsgBody) => {
msg.contentHead!.sequence = 10;
},
],
[
'server sequence',
(msg: PushMsgBody) => {
msg.contentHead!.ntMsgSeq = 88;
},
],
[
'timestamp',
(msg: PushMsgBody) => {
msg.contentHead!.timestamp = time + 1;
},
],
[
'group',
(msg: PushMsgBody) => {
msg.responseHead!.grp = { groupCode: 30003 };
},
],
[
'type',
(msg: PushMsgBody) => {
msg.contentHead!.msgType = 82;
},
],
[
'empty content',
(msg: PushMsgBody) => {
msg.body = {};
},
],
[
'unknown content',
(msg: PushMsgBody) => {
msg.body = { richText: { elems: [{ commonElem: { serviceType: 999 } }] } };
},
],
[
'control',
(msg: PushMsgBody) => {
msg.contentHead!.c2cCmd = 1;
},
],
] as const)('rejects an incorrect %s in the lookup', async (_name, mutate) => {
const msg = message();
mutate(msg);
await expect(setup([msg]).run()).rejects.toThrow();
});
it('rejects missing, ambiguous and cross-conversation results', async () => {
await expect(setup([]).run()).rejects.toThrow('expected one');
await expect(setup([message(), message()]).run()).rejects.toThrow('expected one');
await expect(setup([message()], 'u_other').run()).rejects.toThrow('conversation');
});
it('preserves distinct identities for equal text', async () => {
const first = setup();
const msg = message();
msg.contentHead = { ...msg.contentHead, sequence: 10, ntMsgSeq: 88 };
const second = setup([msg]);
const event = await fetchClientMessage(second, second.identity, {
...second.receipt,
clientSequence: 10,
sequence: 88,
});
expect((await first.run()).ntMsgSeq).toBe(87);
expect(event.ntMsgSeq).toBe(88);
expect(event.elements).toEqual((await first.run()).elements);
});
it.each([
{ success: false, gotResponse: false, responseData: null },
{ success: true, gotResponse: false, responseData: null },
{ success: true, gotResponse: true, responseData: Buffer.alloc(0) },
] satisfies Partial<SendPacketResult>[])(
'surfaces unsuccessful lookup transport: %j',
async (result) => {
const ctx = setup();
ctx.sendPacket.mockResolvedValue({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: null,
...result,
});
await expect(ctx.run()).rejects.toThrow('Client message lookup');
},
);
});