fix(protocol): bound rich message decoding
Reject malformed nested payloads, cap compressed card expansion, and enforce per-message decode budgets. Preserve unknown-wire metadata in diagnostics so unsupported QQ elements remain observable without exhausting memory.
This commit is contained in:
4 files changed
+1016
-129
No files matched your search
@@ -1,6 +1,7 @@
|
||||
import { protobuf_decode } from '@snowluma/proton';
|
||||
import { protobuf_decode, protobuf_getUnknownFieldMetadata } from '@snowluma/proton';
|
||||
import { toHex, toHexUpper } from '@snowluma/common/hex';
|
||||
import type { MessageElement } from '../events';
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement, MessageElementOf } from '../events';
|
||||
import type {
|
||||
Elem,
|
||||
FileInfo,
|
||||
@@ -14,12 +15,291 @@ import type {
|
||||
} from '@snowluma/proto-defs/element';
|
||||
import type { MarkdownData } from '@snowluma/proto-defs/action';
|
||||
import type { FileExtra, MessageBody, PushMsgBody as PushMsgBodyFull, RichText } from '@snowluma/proto-defs/message';
|
||||
import { decompressData, makeImageUrl } from './helpers';
|
||||
import {
|
||||
decompressData,
|
||||
makeImageUrl,
|
||||
MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES,
|
||||
MAX_RICH_CARD_OUTPUT_BYTES,
|
||||
} from './helpers';
|
||||
|
||||
type ElemDecoded = Elem;
|
||||
type RichTextDecoded = RichText;
|
||||
export type PushMsgBody = MessageBody;
|
||||
|
||||
const unknownElementLog = createLogger('MsgPush.UnknownElement');
|
||||
|
||||
// extraInfo/generalFlags are metadata attached to a real element, not message
|
||||
// content by themselves. Every other listed key has an explicit decoder below.
|
||||
// Anything outside this set is fail-open, but logged with its field name so a
|
||||
// QQ wire change leaves a breadcrumb instead of becoming a silent data loss.
|
||||
const DECODED_WIRE_FIELDS: ReadonlySet<string> = new Set([
|
||||
'text', 'face', 'notOnlineImage', 'transElem', 'marketFace', 'customFace',
|
||||
'richMsg', 'groupFile', 'videoFile', 'srcMsg', 'lightApp', 'commonElem',
|
||||
'extraInfo', 'generalFlags',
|
||||
]);
|
||||
const METADATA_WIRE_FIELDS: ReadonlySet<string> = new Set(['extraInfo', 'generalFlags']);
|
||||
|
||||
interface DecodedCardPayload {
|
||||
element: MessageElement | null;
|
||||
error: string | null;
|
||||
inputBytes: number;
|
||||
budgetBytes: number;
|
||||
}
|
||||
|
||||
interface DecodedCards {
|
||||
rich?: DecodedCardPayload;
|
||||
light?: DecodedCardPayload;
|
||||
}
|
||||
|
||||
function invalidCard(inputBytes: number, error: string, budgetBytes = 0): DecodedCardPayload {
|
||||
return { element: null, error, inputBytes, budgetBytes };
|
||||
}
|
||||
|
||||
function decodeCardData(data: Uint8Array, remainingOutputBytes: number) {
|
||||
if (remainingOutputBytes <= 0) {
|
||||
return { ok: false as const, reason: 'message_output_budget_exceeded', budgetBytes: 0 };
|
||||
}
|
||||
const limit = Math.min(MAX_RICH_CARD_OUTPUT_BYTES, remainingOutputBytes);
|
||||
const decoded = decompressData(data, limit);
|
||||
if (!decoded.ok && decoded.reason === 'output_limit_exceeded' && limit < MAX_RICH_CARD_OUTPUT_BYTES) {
|
||||
return { ok: false as const, reason: 'message_output_budget_exceeded', budgetBytes: limit };
|
||||
}
|
||||
if (!decoded.ok) {
|
||||
return {
|
||||
...decoded,
|
||||
budgetBytes: decoded.reason === 'output_limit_exceeded' ? limit : 0,
|
||||
};
|
||||
}
|
||||
return { ...decoded, budgetBytes: decoded.outputBytes };
|
||||
}
|
||||
|
||||
function isXmlCardContent(content: string): boolean {
|
||||
const trimmed = content.trim();
|
||||
return trimmed.startsWith('<') && trimmed.endsWith('>');
|
||||
}
|
||||
|
||||
function decodeRichMsgCard(
|
||||
elem: ElemDecoded,
|
||||
remainingOutputBytes: number,
|
||||
): DecodedCardPayload | undefined {
|
||||
const rm = elem.richMsg;
|
||||
const data = rm?.template1;
|
||||
if (!data || data.length === 0) return undefined;
|
||||
const decoded = decodeCardData(data, remainingOutputBytes);
|
||||
if (!decoded.ok) return invalidCard(data.length, decoded.reason, decoded.budgetBytes);
|
||||
|
||||
const content = decoded.text;
|
||||
const svcId = rm?.serviceId ?? 0;
|
||||
if (svcId !== 1 && !isXmlCardContent(content)) {
|
||||
return invalidCard(data.length, 'invalid_xml', decoded.budgetBytes);
|
||||
}
|
||||
if (svcId === 35) {
|
||||
const match = /\bm_resid="([^"]+)"/.exec(content);
|
||||
return {
|
||||
element: match
|
||||
? { type: 'forward', resId: match[1] }
|
||||
: { type: 'xml', text: content, subType: svcId },
|
||||
error: null,
|
||||
inputBytes: data.length,
|
||||
budgetBytes: decoded.budgetBytes,
|
||||
};
|
||||
}
|
||||
|
||||
if (svcId === 1) {
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(content);
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return invalidCard(data.length, 'invalid_json_object', decoded.budgetBytes);
|
||||
}
|
||||
} catch {
|
||||
return invalidCard(data.length, 'invalid_json', decoded.budgetBytes);
|
||||
}
|
||||
return {
|
||||
element: { type: 'json', text: content },
|
||||
error: null,
|
||||
inputBytes: data.length,
|
||||
budgetBytes: decoded.budgetBytes,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
element: { type: 'xml', text: content, subType: svcId },
|
||||
error: null,
|
||||
inputBytes: data.length,
|
||||
budgetBytes: decoded.budgetBytes,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeLightAppCard(
|
||||
elem: ElemDecoded,
|
||||
remainingOutputBytes: number,
|
||||
): DecodedCardPayload | undefined {
|
||||
const data = elem.lightApp?.data;
|
||||
if (!data || data.length === 0) return undefined;
|
||||
const decoded = decodeCardData(data, remainingOutputBytes);
|
||||
if (!decoded.ok) return invalidCard(data.length, decoded.reason, decoded.budgetBytes);
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(decoded.text);
|
||||
} catch {
|
||||
return invalidCard(data.length, 'invalid_json', decoded.budgetBytes);
|
||||
}
|
||||
if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
||||
return invalidCard(data.length, 'invalid_json_object', decoded.budgetBytes);
|
||||
}
|
||||
|
||||
const card = parsed as {
|
||||
app?: unknown;
|
||||
meta?: { detail?: { resid?: unknown; uniseq?: unknown } };
|
||||
};
|
||||
if (card.app === 'com.tencent.multimsg') {
|
||||
const detail = card.meta?.detail ?? {};
|
||||
const resId = typeof detail.resid === 'string' ? detail.resid : '';
|
||||
const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : '';
|
||||
if (resId) {
|
||||
return {
|
||||
element: { type: 'forward', resId, forwardUuid: uniseq || undefined },
|
||||
error: null,
|
||||
inputBytes: data.length,
|
||||
budgetBytes: decoded.budgetBytes,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
element: { type: 'json', text: decoded.text },
|
||||
error: null,
|
||||
inputBytes: data.length,
|
||||
budgetBytes: decoded.budgetBytes,
|
||||
};
|
||||
}
|
||||
|
||||
function decodeCardsOnce(elems: ElemDecoded[]): Map<ElemDecoded, DecodedCards> {
|
||||
const decoded = new Map<ElemDecoded, DecodedCards>();
|
||||
let remainingOutputBytes = MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES;
|
||||
for (const elem of elems) {
|
||||
const cards: DecodedCards = {};
|
||||
const rich = decodeRichMsgCard(elem, remainingOutputBytes);
|
||||
if (rich) remainingOutputBytes = Math.max(0, remainingOutputBytes - rich.budgetBytes);
|
||||
const light = decodeLightAppCard(elem, remainingOutputBytes);
|
||||
if (light) remainingOutputBytes = Math.max(0, remainingOutputBytes - light.budgetBytes);
|
||||
if (rich) cards.rich = rich;
|
||||
if (light) cards.light = light;
|
||||
if (!rich && !light) continue;
|
||||
decoded.set(elem, cards);
|
||||
for (const [source, card] of Object.entries(cards)) {
|
||||
if (card?.error) {
|
||||
unknownElementLog.debug(
|
||||
'wire %s card ignored inputBytes=%d reason=%s',
|
||||
source,
|
||||
card.inputBytes,
|
||||
card.error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
|
||||
function logUnknownWireMetadata(
|
||||
value: unknown,
|
||||
path: string,
|
||||
depth = 0,
|
||||
seen = new WeakSet<object>(),
|
||||
): void {
|
||||
if (depth > 16 || value === null || typeof value !== 'object' || ArrayBuffer.isView(value)) return;
|
||||
if (seen.has(value)) return;
|
||||
seen.add(value);
|
||||
|
||||
logUnknownWireFields(value, path);
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
value.forEach((entry, index) => logUnknownWireMetadata(entry, `${path}[${index}]`, depth + 1, seen));
|
||||
return;
|
||||
}
|
||||
for (const [key, entry] of Object.entries(value)) {
|
||||
logUnknownWireMetadata(entry, `${path}.${key}`, depth + 1, seen);
|
||||
}
|
||||
}
|
||||
|
||||
function logUnknownWireFields(value: unknown, path: string): void {
|
||||
const metadata = protobuf_getUnknownFieldMetadata(value);
|
||||
for (const unknown of metadata.fields) {
|
||||
unknownElementLog.debug(
|
||||
'wire element ignored unknownTag=%d wireType=%d count=%d bytes=%d reason=no schema decoder path=%s',
|
||||
unknown.fieldNumber,
|
||||
unknown.wireType,
|
||||
unknown.count,
|
||||
unknown.totalByteLength,
|
||||
path,
|
||||
);
|
||||
}
|
||||
if (metadata.omittedOccurrences > 0) {
|
||||
unknownElementLog.debug(
|
||||
'wire unknown metadata truncated totalOccurrences=%d retainedKinds=%d omittedOccurrences=%d omittedBytes=%d path=%s',
|
||||
metadata.totalOccurrences,
|
||||
metadata.fields.length,
|
||||
metadata.omittedOccurrences,
|
||||
metadata.omittedByteLength,
|
||||
path,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function classifyProtobufDecodeError(error: unknown): string {
|
||||
const message = error instanceof Error ? error.message.toLowerCase() : '';
|
||||
if (message.includes('truncated')) return 'protobuf_truncated';
|
||||
if (message.includes('overflow')) return 'protobuf_varint_overflow';
|
||||
if (message.includes('bounds') || message.includes('invalid progress')) return 'protobuf_bounds';
|
||||
if (message.includes('wire type')) return 'protobuf_invalid_wire_type';
|
||||
if (message.includes('field number')) return 'protobuf_invalid_field_number';
|
||||
if (message.includes('group')) return 'protobuf_invalid_group';
|
||||
return 'protobuf_decode_failed';
|
||||
}
|
||||
|
||||
function decodeProtobufPayload<T>(
|
||||
source: string,
|
||||
data: Uint8Array,
|
||||
decode: () => T,
|
||||
): T | null {
|
||||
try {
|
||||
const decoded = decode();
|
||||
logUnknownWireMetadata(decoded, source);
|
||||
return decoded;
|
||||
} catch (error) {
|
||||
unknownElementLog.debug(
|
||||
'wire protobuf payload ignored source=%s bytes=%d reason=%s',
|
||||
source,
|
||||
data.length,
|
||||
classifyProtobufDecodeError(error),
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
type FingerprintElement =
|
||||
| MessageElementOf<'image'>
|
||||
| MessageElementOf<'record'>
|
||||
| MessageElementOf<'video'>
|
||||
| MessageElementOf<'file'>;
|
||||
|
||||
function assignValidFingerprints(
|
||||
element: FingerprintElement,
|
||||
md5Hex: string | undefined,
|
||||
sha1Hex: string | undefined,
|
||||
source: string,
|
||||
): void {
|
||||
if (md5Hex) {
|
||||
if (/^[0-9a-fA-F]{32}$/.test(md5Hex)) element.md5Hex = md5Hex;
|
||||
else unknownElementLog.debug('wire %s ignored invalid md5 fingerprint length=%d', source, md5Hex.length);
|
||||
}
|
||||
if (sha1Hex) {
|
||||
if (/^[0-9a-fA-F]{40}$/.test(sha1Hex)) element.sha1Hex = sha1Hex;
|
||||
else unknownElementLog.debug('wire %s ignored invalid sha1 fingerprint length=%d', source, sha1Hex.length);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the `mediaNode` re-upload descriptor from an NTV2 IndexNode + FileInfo.
|
||||
* Record and video decode to the byte-identical `{ fileUuid, storeId,
|
||||
@@ -54,8 +334,10 @@ function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode
|
||||
|
||||
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
|
||||
const elements: MessageElement[] = [];
|
||||
logUnknownWireFields(body, 'body');
|
||||
if (body?.richText) {
|
||||
const rt = body.richText;
|
||||
logUnknownWireFields(rt, 'body.richText');
|
||||
if (rt.elems) elements.push(...convertElements(rt.elems as ElemDecoded[]));
|
||||
extractRichtextExtras(rt, elements, isGroup);
|
||||
}
|
||||
@@ -67,7 +349,6 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean):
|
||||
|
||||
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const result: MessageElement[] = [];
|
||||
let skipNext = false;
|
||||
// [#146] A QQ mini-program / ark share (B站 video, QQ 小程序, …) arrives as a
|
||||
// `lightApp`/`richMsg` card element plus a plain `text` element carrying QQ's
|
||||
// graceful-degradation compat string ("当前QQ版本不支持此应用,请升级") — the text
|
||||
@@ -81,7 +362,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// rule: when a card is present, drop sibling plain `text`. `@`/reply/face etc.
|
||||
// are not plain text and survive. `richMsg` covers json (svc=1) and xml (svc=35)
|
||||
// cards alike.
|
||||
const hasCard = elems.some((e) => e.lightApp || e.richMsg);
|
||||
// Only a card that can actually decode is allowed to suppress QQ's sibling
|
||||
// compatibility text. Field presence alone is insufficient: a malformed
|
||||
// card must fail open and preserve its otherwise-valid text sibling.
|
||||
const decodedCards = decodeCardsOnce(elems);
|
||||
const hasCard = [...decodedCards.values()].some((cards) => (
|
||||
Boolean(cards.rich?.element || cards.light?.element)
|
||||
));
|
||||
// [#127] A QQ NT reply carries the replied sender as a structural auto-mention
|
||||
// (MentionExtra.type=2, uin=0) right after srcMsg, followed by a blank
|
||||
// separator text. Both are part of the reply wire shape, not user content —
|
||||
@@ -91,7 +378,22 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
let dropNextBlankText = false;
|
||||
|
||||
for (const elem of elems) {
|
||||
if (skipNext) { skipNext = false; continue; }
|
||||
const resultCountBeforeElement = result.length;
|
||||
logUnknownWireMetadata(elem, 'elem');
|
||||
|
||||
// Proton materializes every schema key with a null/default value, so key
|
||||
// presence alone is not evidence that the wire carried that element.
|
||||
// Report only unsupported fields with an actual decoded value.
|
||||
const unsupportedFields = Object.entries(elem)
|
||||
.filter(([, value]) => value !== null && value !== undefined)
|
||||
.map(([key]) => key)
|
||||
.filter((key) => !DECODED_WIRE_FIELDS.has(key));
|
||||
if (unsupportedFields.length > 0) {
|
||||
unknownElementLog.debug(
|
||||
'wire element ignored fields=%s reason=no MessageElement decoder',
|
||||
unsupportedFields.join(','),
|
||||
);
|
||||
}
|
||||
|
||||
// Reply / quote. For a c2c (friend) reply the canonical replied-to sequence
|
||||
// is the srcMsg reserve's `friendSequence`, NOT `origSeqs[0]` — origSeqs
|
||||
@@ -119,8 +421,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// backfill can reconstruct it locally if it isn't in the store / server.
|
||||
if (src.elemsRaw?.length) {
|
||||
const decoded: ElemDecoded[] = [];
|
||||
for (const raw of src.elemsRaw) {
|
||||
try { decoded.push(protobuf_decode<Elem>(raw)); } catch { /* skip corrupt elem */ }
|
||||
for (const [index, raw] of src.elemsRaw.entries()) {
|
||||
const nested = decodeProtobufPayload(
|
||||
`srcMsg.elemsRaw[${index}]`,
|
||||
raw,
|
||||
() => protobuf_decode<Elem>(raw),
|
||||
);
|
||||
if (nested) decoded.push(nested);
|
||||
}
|
||||
if (decoded.length) reply.replyElements = convertElements(decoded);
|
||||
}
|
||||
@@ -128,18 +435,20 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// in elems[] — recover it from sourceMsg (field 9) when elems carried no
|
||||
// file, so a quoted file's content survives into get_msg (#124).
|
||||
if (src.sourceMsg?.length && !reply.replyElements?.some((e) => e.type === 'file')) {
|
||||
try {
|
||||
const pmsg = protobuf_decode<PushMsgBodyFull>(src.sourceMsg);
|
||||
const nof = pmsg?.body?.richText?.notOnlineFile;
|
||||
if (nof?.fileName) {
|
||||
(reply.replyElements ??= []).push({
|
||||
type: 'file',
|
||||
fileName: nof.fileName,
|
||||
fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0,
|
||||
fileId: nof.fileUuid ?? '',
|
||||
});
|
||||
}
|
||||
} catch { /* sourceMsg decode is best-effort */ }
|
||||
const pmsg = decodeProtobufPayload(
|
||||
'srcMsg.sourceMsg',
|
||||
src.sourceMsg,
|
||||
() => protobuf_decode<PushMsgBodyFull>(src.sourceMsg!),
|
||||
);
|
||||
const nof = pmsg?.body?.richText?.notOnlineFile;
|
||||
if (nof?.fileName) {
|
||||
(reply.replyElements ??= []).push({
|
||||
type: 'file',
|
||||
fileName: nof.fileName,
|
||||
fileSize: nof.fileSize !== undefined ? Number(nof.fileSize) : 0,
|
||||
fileId: nof.fileUuid ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
result.push(reply);
|
||||
}
|
||||
@@ -151,7 +460,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const t = elem.text;
|
||||
let mention: MentionExtra | null = null;
|
||||
if (t.pbReserve && t.pbReserve.length > 0) {
|
||||
mention = protobuf_decode<MentionExtra>(t.pbReserve);
|
||||
mention = decodeProtobufPayload(
|
||||
'text.pbReserve',
|
||||
t.pbReserve,
|
||||
() => protobuf_decode<MentionExtra>(t.pbReserve!),
|
||||
);
|
||||
}
|
||||
const hasAttr6 = t.attr6Buf && t.attr6Buf.length > 11;
|
||||
const hasMention = mention && (mention.type === 1 || mention.type === 2);
|
||||
@@ -168,7 +481,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
}
|
||||
|
||||
if (hasAttr6 || hasMention) {
|
||||
const me: MessageElement = { type: 'at', text: t.str ?? '' };
|
||||
const me: MessageElement = { type: 'at', targetUin: 0, text: t.str ?? '' };
|
||||
if (hasAttr6) {
|
||||
const buf = t.attr6Buf!;
|
||||
me.targetUin = ((buf[7] << 24) | (buf[8] << 16) | (buf[9] << 8) | buf[10]) >>> 0;
|
||||
@@ -189,7 +502,8 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
|
||||
// Face
|
||||
if (elem.face) {
|
||||
result.push({ type: 'face', faceId: elem.face.index ?? 0 });
|
||||
const faceId = elem.face.index ?? 0;
|
||||
if (Number.isSafeInteger(faceId) && faceId >= 0) result.push({ type: 'face', faceId });
|
||||
}
|
||||
|
||||
// MarketFace (商城表情). Keep the wire identity (`emojiId`/`tabId`/`key`)
|
||||
@@ -199,19 +513,21 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// `faceId` GUID bytes — it also forms the gxh gif URL on the segment side.
|
||||
if (elem.marketFace) {
|
||||
const mf = elem.marketFace;
|
||||
result.push({
|
||||
type: 'mface',
|
||||
text: mf.faceName ?? '',
|
||||
emojiId: mf.faceId && mf.faceId.length > 0 ? toHex(mf.faceId) : '',
|
||||
emojiPackageId: mf.tabId ?? 0,
|
||||
emojiKey: mf.key ?? '',
|
||||
});
|
||||
if (mf.faceId?.length === 16) {
|
||||
result.push({
|
||||
type: 'mface',
|
||||
text: mf.faceName ?? '',
|
||||
emojiId: toHex(mf.faceId),
|
||||
emojiPackageId: mf.tabId ?? 0,
|
||||
emojiKey: mf.key ?? '',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// NotOnlineImage (C2C image)
|
||||
if (elem.notOnlineImage) {
|
||||
const img = elem.notOnlineImage;
|
||||
if (img.picMd5 && img.picMd5.length > 0) {
|
||||
if (img.picMd5?.length === 16) {
|
||||
const urlPath = img.origUrl || img.bigUrl || '';
|
||||
result.push({
|
||||
type: 'image',
|
||||
@@ -234,7 +550,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// CustomFace (group image)
|
||||
if (elem.customFace) {
|
||||
const img = elem.customFace;
|
||||
if (img.md5 && img.md5.length > 0) {
|
||||
if (img.md5?.length === 16) {
|
||||
result.push({
|
||||
type: 'image',
|
||||
imageUrl: makeImageUrl(img.origUrl ?? ''),
|
||||
@@ -291,11 +607,17 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
// TransElem type=24 (group file via transport)
|
||||
if (elem.transElem) {
|
||||
const te = elem.transElem;
|
||||
const resultCountBeforeTrans = result.length;
|
||||
if ((te.elemType ?? 0) === 24 && te.elemValue && te.elemValue.length > 3) {
|
||||
const val = te.elemValue;
|
||||
const len = (val[1] << 8) | val[2];
|
||||
if (val.length >= 3 + len) {
|
||||
const extra = protobuf_decode<GroupFileExtra>(val.subarray(3, 3 + len));
|
||||
const payload = val.subarray(3, 3 + len);
|
||||
const extra = decodeProtobufPayload(
|
||||
'transElem.groupFile',
|
||||
payload,
|
||||
() => protobuf_decode<GroupFileExtra>(payload),
|
||||
);
|
||||
if (extra?.inner?.info) {
|
||||
const info = extra.inner.info;
|
||||
result.push({
|
||||
@@ -307,75 +629,27 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (result.length === resultCountBeforeTrans) {
|
||||
unknownElementLog.debug(
|
||||
'wire transElem ignored elemType=%d reason=no recognized MessageElement payload',
|
||||
te.elemType ?? 0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// RichMsg
|
||||
if (elem.richMsg) {
|
||||
const rm = elem.richMsg;
|
||||
if (rm.template1 && rm.template1.length > 0) {
|
||||
const content = decompressData(rm.template1);
|
||||
if (content) {
|
||||
const svcId = rm.serviceId ?? 0;
|
||||
if (svcId === 35) {
|
||||
const pos = content.indexOf('m_resid="');
|
||||
if (pos !== -1) {
|
||||
const start = pos + 9;
|
||||
const end = content.indexOf('"', start);
|
||||
if (end !== -1) {
|
||||
result.push({ type: 'forward', resId: content.substring(start, end) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
} else if (svcId === 1) {
|
||||
result.push({ type: 'json', text: content });
|
||||
} else {
|
||||
result.push({ type: 'xml', text: content, subType: svcId });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const cards = decodedCards.get(elem);
|
||||
if (cards?.rich?.element) result.push(cards.rich.element);
|
||||
|
||||
// LightApp
|
||||
if (elem.lightApp) {
|
||||
const la = elem.lightApp;
|
||||
if (la.data && la.data.length > 0) {
|
||||
const content = decompressData(la.data);
|
||||
if (content) {
|
||||
// `com.tencent.multimsg` is the multi-msg / forward preview
|
||||
// LightApp (the modern replacement for the XML serviceID=35
|
||||
// shape). Parse out resid + uniseq so downstream callers can
|
||||
// both render a `[聊天记录]` placeholder and walk into the
|
||||
// forward chain via `fetch(resId)` — the uniseq is what links
|
||||
// the inner layer to its piggybacked actions on the outer's
|
||||
// LongMsgResult. Other LightApp messages fall through to the
|
||||
// generic `{type: 'json'}` path.
|
||||
try {
|
||||
const parsed = JSON.parse(content);
|
||||
if (parsed && parsed.app === 'com.tencent.multimsg') {
|
||||
const detail = parsed.meta?.detail ?? {};
|
||||
const resId = typeof detail.resid === 'string' ? detail.resid : '';
|
||||
const uniseq = typeof detail.uniseq === 'string' ? detail.uniseq : '';
|
||||
if (resId) {
|
||||
result.push({
|
||||
type: 'forward',
|
||||
resId,
|
||||
forwardUuid: uniseq || undefined,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch { /* fall through to generic json element */ }
|
||||
result.push({ type: 'json', text: content });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (cards?.light?.element) result.push(cards.light.element);
|
||||
|
||||
// CommonElem
|
||||
if (elem.commonElem) {
|
||||
const ce = elem.commonElem;
|
||||
const svcType = ce.serviceType ?? 0;
|
||||
const bizType = ce.businessType ?? 0;
|
||||
const resultCountBeforeCommon = result.length;
|
||||
|
||||
if (svcType === 2) {
|
||||
// Poke
|
||||
@@ -392,7 +666,12 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
if ((b & 0x80) === 0) break;
|
||||
}
|
||||
if (pos + length <= pb.length) {
|
||||
const img = protobuf_decode<NotOnlineImage>(pb.subarray(pos, pos + length));
|
||||
const payload = pb.subarray(pos, pos + length);
|
||||
const img = decodeProtobufPayload(
|
||||
'commonElem.flashImage',
|
||||
payload,
|
||||
() => protobuf_decode<NotOnlineImage>(payload),
|
||||
);
|
||||
if (img) {
|
||||
const me: MessageElement = {
|
||||
type: 'image', fileId: img.filePath ?? '',
|
||||
@@ -406,10 +685,13 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
result.push(me);
|
||||
}
|
||||
}
|
||||
skipNext = true;
|
||||
} else if (ce.pbElem && (svcType === 48 || bizType === 10 || bizType === 20 || bizType === 11 || bizType === 21 || bizType === 12 || bizType === 22)) {
|
||||
// NTQQ new protocol image/record/video
|
||||
const info = protobuf_decode<MsgInfo>(ce.pbElem);
|
||||
const info = decodeProtobufPayload(
|
||||
'commonElem.msgInfo',
|
||||
ce.pbElem,
|
||||
() => protobuf_decode<MsgInfo>(ce.pbElem!),
|
||||
);
|
||||
if (info?.msgInfoBody && info.msgInfoBody.length > 0) {
|
||||
const body = info.msgInfoBody[0];
|
||||
if (body.index?.info) {
|
||||
@@ -434,8 +716,7 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
fileSize: fi.fileSize ?? 0, width: fi.width ?? 0,
|
||||
height: fi.height ?? 0, imageUrl: url,
|
||||
};
|
||||
if (fi.fileHash) me.md5Hex = fi.fileHash;
|
||||
if (fi.fileSha1) me.sha1Hex = fi.fileSha1;
|
||||
assignValidFingerprints(me, fi.fileHash, fi.fileSha1, 'commonElem image');
|
||||
if (fi.type?.picFormat) me.picFormat = fi.type.picFormat;
|
||||
if (info.extBizInfo?.pic) {
|
||||
me.subType = info.extBizInfo.pic.bizType ?? 0;
|
||||
@@ -445,42 +726,52 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
result.push(me);
|
||||
} else if (bizType === 12 || bizType === 22) {
|
||||
// Record
|
||||
result.push({
|
||||
const record: MessageElementOf<'record'> = {
|
||||
type: 'record', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
fileSize: fi.fileSize ?? 0,
|
||||
md5Hex: fi.fileHash ?? '',
|
||||
sha1Hex: fi.fileSha1 ?? '',
|
||||
voiceFormat: fi.type?.voiceFormat ?? 0,
|
||||
mediaNode: buildMediaNode(idx, fi),
|
||||
});
|
||||
};
|
||||
assignValidFingerprints(record, fi.fileHash, fi.fileSha1, 'commonElem record');
|
||||
result.push(record);
|
||||
} else if (bizType === 11 || bizType === 21) {
|
||||
// Video
|
||||
result.push({
|
||||
const video: MessageElementOf<'video'> = {
|
||||
type: 'video', fileName: fi.fileName ?? '',
|
||||
fileId: idx.fileUuid ?? '', fileSize: fi.fileSize ?? 0,
|
||||
duration: fi.time ?? 0,
|
||||
fileHash: fi.fileHash ?? '',
|
||||
width: fi.width ?? 0,
|
||||
height: fi.height ?? 0,
|
||||
md5Hex: fi.fileHash ?? '',
|
||||
sha1Hex: fi.fileSha1 ?? '',
|
||||
videoFormat: fi.type?.videoFormat ?? 0,
|
||||
mediaNode: buildMediaNode(idx, fi),
|
||||
});
|
||||
};
|
||||
assignValidFingerprints(video, fi.fileHash, fi.fileSha1, 'commonElem video');
|
||||
result.push(video);
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (svcType === 33 && ce.pbElem) {
|
||||
// Small face
|
||||
const extra = protobuf_decode<QSmallFaceExtra>(ce.pbElem);
|
||||
if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 });
|
||||
const extra = decodeProtobufPayload(
|
||||
'commonElem.smallFace',
|
||||
ce.pbElem,
|
||||
() => protobuf_decode<QSmallFaceExtra>(ce.pbElem!),
|
||||
);
|
||||
const faceId = extra?.faceId ?? 0;
|
||||
if (Number.isSafeInteger(faceId) && faceId >= 0) result.push({ type: 'face', faceId });
|
||||
} else if (svcType === 37 && ce.pbElem) {
|
||||
// Big face
|
||||
const extra = protobuf_decode<QFaceExtra>(ce.pbElem);
|
||||
if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid });
|
||||
skipNext = true;
|
||||
const extra = decodeProtobufPayload(
|
||||
'commonElem.bigFace',
|
||||
ce.pbElem,
|
||||
() => protobuf_decode<QFaceExtra>(ce.pbElem!),
|
||||
);
|
||||
if (extra?.qsid !== undefined && Number.isSafeInteger(extra.qsid) && extra.qsid >= 0) {
|
||||
result.push({ type: 'face', faceId: extra.qsid });
|
||||
}
|
||||
} else if (svcType === 45 && ce.pbElem && ce.pbElem.length > 0) {
|
||||
// Markdown commonElem. Older QQ clients (≤9.9.30) deliver a 闪传 (flash
|
||||
// transfer) file as a richui markdown card (busId=FlashTransfer); newer
|
||||
@@ -489,6 +780,38 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||
const flash = decodeFlashTransferCard(ce.pbElem);
|
||||
if (flash) result.push(flash);
|
||||
}
|
||||
|
||||
// Route predicates alone are not proof that a payload decoded. Log any
|
||||
// CommonElem that produced no MessageElement, including known service
|
||||
// types with a new businessType or a malformed/unrecognized payload.
|
||||
if (result.length === resultCountBeforeCommon) {
|
||||
unknownElementLog.debug(
|
||||
'wire commonElem ignored serviceType=%d businessType=%d reason=no recognized MessageElement payload',
|
||||
svcType,
|
||||
bizType,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Known content fields can also drift or arrive malformed. Preserve the
|
||||
// rest of the message, but make every standalone decode miss observable.
|
||||
// transElem/CommonElem emit richer diagnostics in their own branches.
|
||||
if (result.length === resultCountBeforeElement) {
|
||||
const ignoredKnownFields = Object.entries(elem)
|
||||
.filter(([, value]) => value !== null && value !== undefined)
|
||||
.map(([key]) => key)
|
||||
.filter((key) => (
|
||||
DECODED_WIRE_FIELDS.has(key)
|
||||
&& !METADATA_WIRE_FIELDS.has(key)
|
||||
&& key !== 'transElem'
|
||||
&& key !== 'commonElem'
|
||||
));
|
||||
if (ignoredKnownFields.length > 0) {
|
||||
unknownElementLog.debug(
|
||||
'wire element ignored fields=%s reason=no recognized MessageElement payload',
|
||||
ignoredKnownFields.join(','),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -520,7 +843,11 @@ function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknow
|
||||
}
|
||||
|
||||
function decodeFlashTransferCard(pbElem: Uint8Array): MessageElement | null {
|
||||
const md = protobuf_decode<MarkdownData>(pbElem);
|
||||
const md = decodeProtobufPayload(
|
||||
'commonElem.flashTransfer',
|
||||
pbElem,
|
||||
() => protobuf_decode<MarkdownData>(pbElem),
|
||||
);
|
||||
const content = md?.content ?? '';
|
||||
if (!content.includes('FlashTransfer')) return null;
|
||||
const m = content.match(/[?&]json=([^)\s]+)/);
|
||||
@@ -535,11 +862,15 @@ function decodeFlashTransferCard(pbElem: Uint8Array): MessageElement | null {
|
||||
const filesetId = deepFindValue(obj, ['fileSetId', 'filesetId', 'fileset_id', 'file_set_id']);
|
||||
const title = deepFindValue(obj, ['title', 'fileName', 'name']);
|
||||
const sceneType = deepFindValue(obj, ['sceneType', 'scene_type']);
|
||||
const normalizedFilesetId = filesetId != null ? String(filesetId).trim() : '';
|
||||
if (!normalizedFilesetId) return null;
|
||||
const normalizedSceneType = sceneType == null ? 0 : Number(sceneType);
|
||||
if (!Number.isSafeInteger(normalizedSceneType) || normalizedSceneType < 0) return null;
|
||||
return {
|
||||
type: 'flash_file',
|
||||
filesetId: filesetId != null ? String(filesetId) : '',
|
||||
filesetId: normalizedFilesetId,
|
||||
fileName: title != null ? String(title) : '',
|
||||
sceneType: sceneType != null ? Number(sceneType) : 0,
|
||||
sceneType: normalizedSceneType,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -551,14 +882,14 @@ function extractRichtextExtras(
|
||||
// Ptt (voice)
|
||||
if (rt.ptt) {
|
||||
const p = rt.ptt;
|
||||
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : '';
|
||||
const me: MessageElement = {
|
||||
const md5Hex = p.fileMd5 && p.fileMd5.length > 0 ? toHexUpper(p.fileMd5) : undefined;
|
||||
const me: MessageElementOf<'record'> = {
|
||||
type: 'record', fileName: p.fileName ?? '',
|
||||
fileSize: p.fileSize ?? 0, duration: p.time ?? 0,
|
||||
fileHash: md5Hex,
|
||||
md5Hex,
|
||||
fileHash: md5Hex ?? '',
|
||||
voiceFormat: p.format ?? 0,
|
||||
};
|
||||
assignValidFingerprints(me, md5Hex, undefined, 'ptt');
|
||||
if (isGroup && (p.fileId ?? 0n) !== 0n) {
|
||||
me.fileId = p.groupFileKey ?? '';
|
||||
} else {
|
||||
@@ -604,7 +935,11 @@ function extractMsgContent(msgContent: Uint8Array, elements: MessageElement[]):
|
||||
// "incomplete metadata". After consolidating FileExtra to wrap
|
||||
// `NotOnlineFile` (Lagrange.Core's `FileExtra { File: NotOnlineFile }`),
|
||||
// this reads the right tags.
|
||||
const extra = protobuf_decode<FileExtra>(msgContent);
|
||||
const extra = decodeProtobufPayload(
|
||||
'messageBody.msgContent',
|
||||
msgContent,
|
||||
() => protobuf_decode<FileExtra>(msgContent),
|
||||
);
|
||||
if (!extra?.file) return;
|
||||
const f = extra.file;
|
||||
if (!f.fileUuid) return;
|
||||
|
||||
Reference in new issue
Block a user