fix(protocol): harden history response decoding
Share packet response validation across group and private history fetches so transport failures and empty responses cannot masquerade as empty pages. Reject malformed group records and mismatched private-peer responses while preserving explicit QQ control-message filters. Mark fetched contexts as historical so old invite cards cannot overwrite live approval state. Add wire-level regression coverage for failed responses, malformed entries, peer mismatches, ordering, and live-only identity observations. Refs #280.
This commit is contained in:
7 files changed
+204
-25
No files matched your search
@@ -30,6 +30,11 @@ export interface MsgPushContext {
|
||||
readonly body: PushMsgBody | undefined;
|
||||
readonly responseHead: PushMsgResponseHead | undefined;
|
||||
readonly identity: IdentityService;
|
||||
/**
|
||||
* Historical messages reuse the live decoder but must not replay
|
||||
* live-only identity observations.
|
||||
*/
|
||||
readonly isHistorical: boolean;
|
||||
}
|
||||
|
||||
export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPushContext | null {
|
||||
@@ -49,7 +54,7 @@ export function buildContext(pkt: PacketInfo, identity: IdentityService): MsgPus
|
||||
if (!isNaN(n)) selfUin = n;
|
||||
}
|
||||
|
||||
return buildContextFromMessage(push.message, selfUin, identity);
|
||||
return buildContextFromMessage(push.message, selfUin, identity, false);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -63,6 +68,7 @@ export function buildContextFromMessage(
|
||||
msg: ProtoMessage,
|
||||
selfUin: number,
|
||||
identity: IdentityService,
|
||||
isHistorical = true,
|
||||
): MsgPushContext | null {
|
||||
if (!msg.contentHead) return null;
|
||||
|
||||
@@ -94,5 +100,6 @@ export function buildContextFromMessage(
|
||||
body: msg.body,
|
||||
responseHead: msg.responseHead,
|
||||
identity,
|
||||
isHistorical,
|
||||
};
|
||||
}
|
||||
@@ -28,12 +28,16 @@ export const decodeFriendMessage: MsgPushDecoder = (ctx) => {
|
||||
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
|
||||
// Stash the approval msgseq from a live private group-invite card so a later
|
||||
// `set_group_add_request` can approve a bot self-invite (issue #125).
|
||||
for (const el of elements) {
|
||||
if (el.type === 'json' && typeof el.text === 'string') {
|
||||
const card = parseGroupInviteCard(el.text);
|
||||
if (card) ctx.identity.rememberGroupInviteCardSequence(card.groupUin, card.sequence);
|
||||
// Historical decode is intentionally read-only: replaying an older card here
|
||||
// could overwrite the sequence observed from a newer live invite.
|
||||
if (!ctx.isHistorical) {
|
||||
for (const el of elements) {
|
||||
if (el.type === 'json' && typeof el.text === 'string') {
|
||||
const card = parseGroupInviteCard(el.text);
|
||||
if (card) ctx.identity.rememberGroupInviteCardSequence(card.groupUin, card.sequence);
|
||||
}
|
||||
}
|
||||
}
|
||||
const ev: FriendMessage = {
|
||||
|
||||
@@ -13,6 +13,7 @@ import type { IdentityService } from '../identity-service';
|
||||
import { isBlankMessage, isC2cControlPush } from './blank-filter';
|
||||
import { buildContextFromMessage } from './context';
|
||||
import { decodeFriendMessage } from './decoders/friend-message';
|
||||
import { requirePacketResponse } from './packet-response';
|
||||
|
||||
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';
|
||||
@@ -30,16 +31,6 @@ export interface C2cRoamPage {
|
||||
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,
|
||||
@@ -95,6 +86,9 @@ export async function fetchC2cMessageRange(
|
||||
const decoded = protobuf_decode<SsoGetC2cMsgResponse>(
|
||||
requirePacketResponse(res, 'SsoGetC2cMsg'),
|
||||
);
|
||||
if (decoded.friendUid && decoded.friendUid !== friendUid) {
|
||||
throw new Error(`SsoGetC2cMsg response friend uid mismatch: ${decoded.friendUid}`);
|
||||
}
|
||||
const messages = decoded?.messages ?? [];
|
||||
const out = decodeC2cMessages(messages, identity, selfUin, 'SsoGetC2cMsg');
|
||||
out.sort((a, b) => (a.ntMsgSeq ?? 0) - (b.ntMsgSeq ?? 0));
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { IdentityService } from '../identity-service';
|
||||
import { isBlankMessage } from './blank-filter';
|
||||
import { buildContextFromMessage } from './context';
|
||||
import { decodeGroupMessage } from './decoders/group-message';
|
||||
import { requirePacketResponse } from './packet-response';
|
||||
|
||||
export const SSO_GET_GROUP_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoGetGroupMsg';
|
||||
|
||||
@@ -42,15 +43,21 @@ export async function fetchGroupMessageRange(
|
||||
});
|
||||
|
||||
const res = await sender.sendRawPacket(SSO_GET_GROUP_MSG_CMD, req);
|
||||
if (!res.success || !res.gotResponse || !res.responseData) return [];
|
||||
|
||||
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(res.responseData);
|
||||
const decoded = protobuf_decode<SsoGetGroupMsgResponse>(
|
||||
requirePacketResponse(res, 'SsoGetGroupMsg'),
|
||||
);
|
||||
const messages = decoded?.body?.messages ?? [];
|
||||
|
||||
const out: GroupMessage[] = [];
|
||||
for (const msg of messages) {
|
||||
for (let index = 0; index < messages.length; index += 1) {
|
||||
const msg = messages[index];
|
||||
const ctx = buildContextFromMessage(msg, selfUin, identity);
|
||||
if (!ctx) continue;
|
||||
if (!ctx) {
|
||||
throw new Error(
|
||||
`SsoGetGroupMsg response message ${index} has no content head `
|
||||
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
|
||||
);
|
||||
}
|
||||
// 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
|
||||
@@ -68,7 +75,24 @@ export async function fetchGroupMessageRange(
|
||||
continue;
|
||||
}
|
||||
for (const ev of decodeGroupMessage(ctx)) {
|
||||
if (ev.kind !== 'group_message' || ev.msgSeq <= 0) continue;
|
||||
if (ev.kind !== 'group_message') {
|
||||
throw new Error(
|
||||
`SsoGetGroupMsg response message ${index} decoded as ${ev.kind} `
|
||||
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
|
||||
);
|
||||
}
|
||||
if (!Number.isSafeInteger(ev.msgSeq) || ev.msgSeq <= 0) {
|
||||
throw new Error(
|
||||
`SsoGetGroupMsg response message ${index} has invalid sequence ${String(ev.msgSeq)} `
|
||||
+ `(group=${groupUin} range=${startSeq}-${endSeq})`,
|
||||
);
|
||||
}
|
||||
if (ev.groupId !== groupUin) {
|
||||
throw new Error(
|
||||
`SsoGetGroupMsg response message ${index} belongs to group ${ev.groupId} `
|
||||
+ `(expected=${groupUin} range=${startSeq}-${endSeq})`,
|
||||
);
|
||||
}
|
||||
// Drop content-less control pushes (the "[空消息]" phantom, #102) just as
|
||||
// QQ NT does on its group roam/history fetch — keep history parity with live.
|
||||
if (isBlankMessage(ev.elements, ctx.body)) continue;
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
|
||||
export 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;
|
||||
}
|
||||
@@ -2,6 +2,7 @@
|
||||
// tags) and the fetched private-history decode path (each returned PushMsgBody
|
||||
// re-uses the regular friend decoder).
|
||||
|
||||
import { deflateSync } from 'node:zlib';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
@@ -11,7 +12,10 @@ import type {
|
||||
SsoGetRoamMsg,
|
||||
SsoGetRoamMsgResponse,
|
||||
} from '@snowluma/proto-defs/get-c2c-msg';
|
||||
import type { PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import type { IdentityService } from '../../src/identity-service';
|
||||
import { buildContextFromMessage } from '../../src/msg-push/context';
|
||||
import { decodeFriendMessage } from '../../src/msg-push/decoders/friend-message';
|
||||
import {
|
||||
SSO_GET_C2C_MSG_CMD,
|
||||
SSO_GET_ROAM_MSG_CMD,
|
||||
@@ -25,6 +29,28 @@ function okResult(data: Uint8Array): SendPacketResult {
|
||||
return { success: true, gotResponse: true, responseData: data } as SendPacketResult;
|
||||
}
|
||||
|
||||
function inviteCardMessage(sequence: number): PushMsgBody {
|
||||
const json = JSON.stringify({
|
||||
app: 'com.tencent.qun.invite',
|
||||
jumpUrl: `mqqapi://group/invite_join?groupcode=12345&msgseq=${sequence}`,
|
||||
});
|
||||
const compressed = deflateSync(Buffer.from(json));
|
||||
const data = new Uint8Array(compressed.length + 1);
|
||||
data[0] = 1;
|
||||
data.set(compressed, 1);
|
||||
return {
|
||||
responseHead: { fromUin: 222, forward: { friendName: 'Bob' } },
|
||||
contentHead: {
|
||||
msgType: 166,
|
||||
sequence,
|
||||
ntMsgSeq: sequence,
|
||||
timestamp: 1_700_000_000 + sequence,
|
||||
msgId: sequence,
|
||||
},
|
||||
body: { richText: { elems: [{ lightApp: { data } }] } },
|
||||
};
|
||||
}
|
||||
|
||||
describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
|
||||
it('sends the right command and request field tags', async () => {
|
||||
let captured: { cmd: string; body: Uint8Array } | null = null;
|
||||
@@ -129,6 +155,55 @@ describe('fetchC2cMessageRange / SsoGetC2cMsg', () => {
|
||||
expect(await fetchC2cMessageRange(guardSender, identity, 10001, 'u_x', 200, 100)).toEqual([]); // start > end
|
||||
expect(sent).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a response attributed to a different private peer', async () => {
|
||||
const response = protobuf_encode<SsoGetC2cMsgResponse>({
|
||||
friendUid: 'u_other',
|
||||
messages: [],
|
||||
});
|
||||
await expect(fetchC2cMessageRange(
|
||||
{ sendRawPacket: async () => okResult(response) },
|
||||
identity,
|
||||
10001,
|
||||
'u_friend',
|
||||
100,
|
||||
120,
|
||||
)).rejects.toThrow('friend uid mismatch');
|
||||
});
|
||||
|
||||
it('does not replay live-only invite observations from older history', async () => {
|
||||
const remembered: Array<[number, number]> = [];
|
||||
const observingIdentity = {
|
||||
findFriend: () => undefined,
|
||||
rememberGroupInviteCardSequence: (groupUin: number, sequence: number) => {
|
||||
remembered.push([groupUin, sequence]);
|
||||
},
|
||||
} as unknown as IdentityService;
|
||||
|
||||
const live = buildContextFromMessage(
|
||||
inviteCardMessage(222),
|
||||
10001,
|
||||
observingIdentity,
|
||||
false,
|
||||
);
|
||||
expect(live).not.toBeNull();
|
||||
decodeFriendMessage(live!);
|
||||
|
||||
const historyResponse = protobuf_encode<SsoGetC2cMsgResponse>({
|
||||
friendUid: 'u_friend',
|
||||
messages: [inviteCardMessage(111)],
|
||||
});
|
||||
await fetchC2cMessageRange(
|
||||
{ sendRawPacket: async () => okResult(historyResponse) },
|
||||
observingIdentity,
|
||||
10001,
|
||||
'u_friend',
|
||||
100,
|
||||
120,
|
||||
);
|
||||
|
||||
expect(remembered).toEqual([[12345, 222]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fetchC2cRoamMessagePage / SsoGetRoamMsg', () => {
|
||||
|
||||
@@ -150,10 +150,69 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => {
|
||||
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([]);
|
||||
it('keeps failed or empty transport responses observable', async () => {
|
||||
const failSender = {
|
||||
sendRawPacket: async () => ({
|
||||
success: false,
|
||||
gotResponse: false,
|
||||
errorMessage: 'history unavailable',
|
||||
} as SendPacketResult),
|
||||
};
|
||||
await expect(
|
||||
fetchGroupMessageRange(failSender, identity, 10001, 9999, 100, 120),
|
||||
).rejects.toThrow('history unavailable');
|
||||
|
||||
const emptySender = {
|
||||
sendRawPacket: async () => ({
|
||||
success: true,
|
||||
gotResponse: false,
|
||||
} as SendPacketResult),
|
||||
};
|
||||
await expect(
|
||||
fetchGroupMessageRange(emptySender, identity, 10001, 9999, 100, 120),
|
||||
).rejects.toThrow('response is empty');
|
||||
});
|
||||
|
||||
it('rejects malformed history entries instead of silently omitting them', async () => {
|
||||
const missingHead = protobuf_encode<SsoGetGroupMsgResponse>({
|
||||
body: {
|
||||
groupUin: 9999,
|
||||
messages: [{
|
||||
responseHead: { fromUin: 222, grp: { groupUin: 9999 } },
|
||||
body: { richText: { elems: [{ text: { str: 'missing head' } }] } },
|
||||
}],
|
||||
},
|
||||
});
|
||||
await expect(fetchGroupMessageRange(
|
||||
{ sendRawPacket: async () => okResult(missingHead) },
|
||||
identity,
|
||||
10001,
|
||||
9999,
|
||||
100,
|
||||
120,
|
||||
)).rejects.toThrow(/message 0 has no content head.*group=9999 range=100-120/);
|
||||
|
||||
const invalidSequence = protobuf_encode<SsoGetGroupMsgResponse>({
|
||||
body: {
|
||||
groupUin: 9999,
|
||||
messages: [{
|
||||
responseHead: { fromUin: 222, grp: { groupUin: 9999 } },
|
||||
contentHead: { msgType: 82, sequence: 0, timestamp: 1_700_000_000, msgId: 1 },
|
||||
body: { richText: { elems: [{ text: { str: 'invalid sequence' } }] } },
|
||||
}],
|
||||
},
|
||||
});
|
||||
await expect(fetchGroupMessageRange(
|
||||
{ sendRawPacket: async () => okResult(invalidSequence) },
|
||||
identity,
|
||||
10001,
|
||||
9999,
|
||||
100,
|
||||
120,
|
||||
)).rejects.toThrow(/message 0 has invalid sequence 0.*group=9999 range=100-120/);
|
||||
});
|
||||
|
||||
it('rejects an out-of-range request before sending', async () => {
|
||||
// start > end is rejected before any send
|
||||
let sent = false;
|
||||
const guardSender = { sendRawPacket: async () => { sent = true; return okResult(new Uint8Array()); } };
|
||||
|
||||
Reference in new issue
Block a user