From 920f75718a2f7fa94f828f5c4e4db0d9f551e7e0 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Fri, 10 Jul 2026 13:41:19 +0800 Subject: [PATCH] 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. --- packages/protocol/src/msg-push/helpers.ts | 56 +- .../src/msg-push/rich-body-decoder.ts | 569 ++++++++++++++---- .../msg-push/flash-transfer-decode.test.ts | 4 +- .../tests/msg-push/rich-body-decoder.test.ts | 516 +++++++++++++++- 4 files changed, 1016 insertions(+), 129 deletions(-) diff --git a/packages/protocol/src/msg-push/helpers.ts b/packages/protocol/src/msg-push/helpers.ts index 200d1abe..f14df2d4 100644 --- a/packages/protocol/src/msg-push/helpers.ts +++ b/packages/protocol/src/msg-push/helpers.ts @@ -3,24 +3,62 @@ import { inflateSync } from 'zlib'; import type { IdentityService } from '../identity-service'; import type { OperatorInfo } from '@snowluma/proto-defs/notify'; +export const MAX_RICH_CARD_OUTPUT_BYTES = 4 * 1024 * 1024; +export const MAX_RICH_CARD_MESSAGE_OUTPUT_BYTES = 8 * 1024 * 1024; + +export type DecompressDataResult = + | { ok: true; text: string; outputBytes: number } + | { ok: false; reason: string }; + export function makeImageUrl(origUrl: string): string { if (!origUrl) return ''; if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl; return 'http://gchat.qpic.cn' + origUrl; } -export function decompressData(data: Uint8Array): string { - if (!data || data.length === 0) return ''; - if (data[0] === 0x01 && data.length > 1) { +export function decompressData( + data: Uint8Array, + maxOutputBytes = MAX_RICH_CARD_OUTPUT_BYTES, +): DecompressDataResult { + if (!data || data.length === 0) return { ok: false, reason: 'empty_payload' }; + if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes <= 0) { + throw new Error(`invalid decompression output limit: ${maxOutputBytes}`); + } + if ((data[0] === 0x00 || data[0] === 0x01) && data.length === 1) { + return { ok: false, reason: 'marker_without_payload' }; + } + if (data[0] === 0x01) { try { - const inflated = inflateSync(Buffer.from(data.subarray(1))); - return inflated.toString('utf8'); - } catch { return ''; } + const inflated = inflateSync(Buffer.from(data.subarray(1)), { + maxOutputLength: maxOutputBytes, + }); + return inflated.length > 0 + ? { ok: true, text: inflated.toString('utf8'), outputBytes: inflated.length } + : { ok: false, reason: 'empty_output' }; + } catch (error) { + const code = typeof error === 'object' && error !== null && 'code' in error + ? String(error.code) + : ''; + return { + ok: false, + reason: code === 'ERR_BUFFER_TOO_LARGE' + ? 'output_limit_exceeded' + : code + ? `inflate_failed:${code}` + : 'inflate_failed', + }; + } } - if (data[0] === 0x00 && data.length > 1) { - return Buffer.from(data.subarray(1)).toString('utf8'); + if (data[0] === 0x00) { + if (data.length - 1 > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' }; + return { + ok: true, + text: Buffer.from(data.subarray(1)).toString('utf8'), + outputBytes: data.length - 1, + }; } - return Buffer.from(data).toString('utf8'); + if (data.length > maxOutputBytes) return { ok: false, reason: 'output_limit_exceeded' }; + return { ok: true, text: Buffer.from(data).toString('utf8'), outputBytes: data.length }; } export function isNumericUin(value: string): boolean { diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 16174b94..11416ace 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -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 = new Set([ + 'text', 'face', 'notOnlineImage', 'transElem', 'marketFace', 'customFace', + 'richMsg', 'groupFile', 'videoFile', 'srcMsg', 'lightApp', 'commonElem', + 'extraInfo', 'generalFlags', +]); +const METADATA_WIRE_FIELDS: ReadonlySet = 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 { + const decoded = new Map(); + 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(), +): 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( + 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(raw)); } catch { /* skip corrupt elem */ } + for (const [index, raw] of src.elemsRaw.entries()) { + const nested = decodeProtobufPayload( + `srcMsg.elemsRaw[${index}]`, + raw, + () => protobuf_decode(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(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(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(t.pbReserve); + mention = decodeProtobufPayload( + 'text.pbReserve', + t.pbReserve, + () => protobuf_decode(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(val.subarray(3, 3 + len)); + const payload = val.subarray(3, 3 + len); + const extra = decodeProtobufPayload( + 'transElem.groupFile', + payload, + () => protobuf_decode(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(pb.subarray(pos, pos + length)); + const payload = pb.subarray(pos, pos + length); + const img = decodeProtobufPayload( + 'commonElem.flashImage', + payload, + () => protobuf_decode(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(ce.pbElem); + const info = decodeProtobufPayload( + 'commonElem.msgInfo', + ce.pbElem, + () => protobuf_decode(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(ce.pbElem); - if (extra) result.push({ type: 'face', faceId: extra.faceId ?? 0 }); + const extra = decodeProtobufPayload( + 'commonElem.smallFace', + ce.pbElem, + () => protobuf_decode(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(ce.pbElem); - if (extra?.qsid !== undefined) result.push({ type: 'face', faceId: extra.qsid }); - skipNext = true; + const extra = decodeProtobufPayload( + 'commonElem.bigFace', + ce.pbElem, + () => protobuf_decode(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(pbElem); + const md = decodeProtobufPayload( + 'commonElem.flashTransfer', + pbElem, + () => protobuf_decode(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(msgContent); + const extra = decodeProtobufPayload( + 'messageBody.msgContent', + msgContent, + () => protobuf_decode(msgContent), + ); if (!extra?.file) return; const f = extra.file; if (!f.fileUuid) return; diff --git a/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts b/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts index 2d274ed1..712de609 100644 --- a/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts +++ b/packages/protocol/tests/msg-push/flash-transfer-decode.test.ts @@ -35,9 +35,9 @@ describe('decodeRichBody / 闪传 flash_file (#199/#200)', () => { expect(out).toEqual([{ type: 'flash_file', filesetId: 'fs-deep', fileName: 'a.zip', sceneType: 0 }]); }); - it('defaults missing fields (still emits a non-empty element)', () => { + it('drops a malformed card that has no fileset identity', () => { const out = decodeRichBody(flashBody({ busId: 'FlashTransfer', templateId: 'flash' }), true); - expect(out).toEqual([{ type: 'flash_file', filesetId: '', fileName: '', sceneType: 0 }]); + expect(out).toEqual([]); }); it('ignores a non-FlashTransfer markdown card (no flash_file element)', () => { diff --git a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts index c78768d5..c8c5c584 100644 --- a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -11,11 +11,14 @@ import { describe, expect, it } from 'vitest'; import { deflateSync } from 'zlib'; import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger'; import { decodeRichBody } from '../../src/msg-push/rich-body-decoder'; +import { MAX_RICH_CARD_OUTPUT_BYTES } from '../../src/msg-push/helpers'; import { buildSendElems } from '../../src/element-builder'; +import { assertValidMessageElement } from '../../src/element-manifest'; import type { MessageElement } from '../../src/events'; import type { MessageBody } from '@snowluma/proto-defs/message'; -import type { SrcMsgPbReserve } from '@snowluma/proto-defs/element'; +import type { Elem, MsgInfo, QFaceExtra, SrcMsgPbReserve } from '@snowluma/proto-defs/element'; function lightAppBytes(json: unknown): Uint8Array { const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8')); @@ -25,6 +28,26 @@ function lightAppBytes(json: unknown): Uint8Array { return out; } +function varint(value: number): number[] { + const out: number[] = []; + let current = value >>> 0; + do { + let byte = current & 0x7f; + current >>>= 7; + if (current !== 0) byte |= 0x80; + out.push(byte); + } while (current !== 0); + return out; +} + +function lengthDelimited(fieldNumber: number, payload: Uint8Array): Uint8Array { + return Uint8Array.from([ + ...varint((fieldNumber << 3) | 2), + ...varint(payload.length), + ...payload, + ]); +} + describe('decodeRichBody / forward LightApp', () => { it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => { const body: MessageBody = { @@ -228,6 +251,25 @@ describe('decodeRichBody / market face', () => { }); }); +describe('decodeRichBody / decoded element contract', () => { + it('omits an absent PTT fingerprint instead of emitting an invalid empty hash', () => { + const body: MessageBody = { + richText: { + ptt: { + fileName: 'voice.silk', + fileSize: 12, + time: 1, + fileMd5: new Uint8Array(), + }, + }, + } as any; + const out = decodeRichBody(body, true); + expect(out).toHaveLength(1); + expect(out[0]).not.toHaveProperty('md5Hex'); + expect(() => assertValidMessageElement(out[0], 'D')).not.toThrow(); + }); +}); + // Reply identity for c2c: the replied-to sequence is srcMsg.origSeqs[0] for BOTH // group 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 — @@ -269,3 +311,475 @@ describe('decodeRichBody / reply uses origSeqs[0] for c2c', () => { expect(decodeRichBody(body, false)).toContainEqual({ type: 'reply', replySeq: CLIENT_SEQ }); }); }); + +describe('decodeRichBody / unknown wire element observability', () => { + it('does not report Proton materialized null fields as wire elements', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const encoded = protobuf_encode({ + richText: { elems: [{ text: { str: 'known text' } }] }, + }); + const decodedBody = protobuf_decode(encoded); + expect(decodeRichBody(decodedBody, true)).toEqual([{ type: 'text', text: 'known text' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured.filter((entry) => entry.scope === 'MsgPush.UnknownElement')).toEqual([]); + }); + + it('records a service-48 CommonElem with an unknown business type', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [{ + commonElem: { + serviceType: 48, + businessType: 99, + pbElem: protobuf_encode({}), + }, + }], + }, + }; + expect(decodeRichBody(body, true)).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'serviceType=48 businessType=99 reason=no recognized MessageElement payload', + ), + })); + }); + + it('fails open and records the unsupported wire field plus reason', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [{ onlineImage: { filePath: '/unknown-wire-shape' } } as any], + }, + }; + let decoded: ReturnType | undefined; + expect(() => { decoded = decodeRichBody(body, true); }).not.toThrow(); + expect(decoded).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('fields=onlineImage reason=no MessageElement decoder'), + })); + }); + + it('retains and records a schema-unknown protobuf tag beside known text', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const knownElem = protobuf_encode({ + text: { str: 'known text' }, + }); + const unknownElem = lengthDelimited(60, Uint8Array.of(1, 2, 3)); + const richText = Uint8Array.from([ + ...lengthDelimited(2, knownElem), + ...lengthDelimited(2, unknownElem), + ]); + const rawBody = lengthDelimited(1, richText); + const decodedBody = protobuf_decode(rawBody); + + expect(decodeRichBody(decodedBody, true)).toEqual([{ type: 'text', text: 'known text' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'unknownTag=60 wireType=2 count=1 bytes=4 reason=no schema decoder path=elem', + ), + })); + }); + + it('logs repeated unknown tags once with an occurrence count', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const elemBytes: number[] = [...protobuf_encode({ text: { str: 'known' } })]; + const unknown = lengthDelimited(60, Uint8Array.of(7)); + for (let index = 0; index < 1_000; index++) elemBytes.push(...unknown); + const richText = lengthDelimited(2, Uint8Array.from(elemBytes)); + const decodedBody = protobuf_decode(lengthDelimited(1, richText)); + + expect(decodeRichBody(decodedBody, true)).toEqual([{ type: 'text', text: 'known' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + const logs = captured.filter((entry) => entry.message.includes('unknownTag=60')); + expect(logs).toHaveLength(1); + expect(logs[0]?.message).toContain('count=1000 bytes=2000'); + }); + + it('preserves sibling text and records a malformed known card field', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [ + { richMsg: { serviceId: 35, template1: Uint8Array.of(1, 1, 2, 3) } } as any, + { text: { str: 'keep me' } } as any, + ], + }, + }; + expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep me' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('fields=richMsg reason=no recognized MessageElement payload'), + })); + }); + + it('does not consume the next element when a structural CommonElem is malformed', () => { + const body: MessageBody = { + richText: { + elems: [ + { commonElem: { serviceType: 3, businessType: 0, pbElem: Uint8Array.of(0, 5) } } as any, + { text: { str: 'keep next' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep next' }]); + }); + + it('does not consume sibling text after a decoded big face', () => { + const body: MessageBody = { + richText: { + elems: [ + { + commonElem: { + serviceType: 37, + businessType: 0, + pbElem: protobuf_encode({ qsid: 321 }), + }, + } as any, + { text: { str: 'keep after face' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([ + { type: 'face', faceId: 321 }, + { type: 'text', text: 'keep after face' }, + ]); + }); + + it('records unknown tags inside bytes-embedded protobuf payloads', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const known = protobuf_encode({ qsid: 654 }); + const pbElem = Uint8Array.from([ + ...known, + ...lengthDelimited(60, Uint8Array.of(1, 2)), + ]); + const body: MessageBody = { + richText: { + elems: [{ + commonElem: { serviceType: 37, businessType: 0, pbElem }, + } as any], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([{ type: 'face', faceId: 654 }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + message: expect.stringContaining( + 'unknownTag=60 wireType=2 count=1 bytes=3 reason=no schema decoder path=commonElem.bigFace', + ), + })); + }); + + it('fails open when an embedded face protobuf is truncated', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [ + { + commonElem: { + serviceType: 37, + businessType: 0, + pbElem: Uint8Array.of(0x18, 0x80), + }, + } as any, + { text: { str: 'keep after malformed face' } } as any, + ], + }, + }; + + let decoded: ReturnType | undefined; + expect(() => { decoded = decodeRichBody(body, true); }).not.toThrow(); + expect(decoded).toEqual([ + { type: 'text', text: 'keep after malformed face' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'source=commonElem.bigFace bytes=2 reason=protobuf_truncated', + ), + })); + }); + + it('retains and records schema-unknown tags inside nested element messages', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const textPayload = Uint8Array.from([ + ...lengthDelimited(1, new TextEncoder().encode('nested known text')), + ...lengthDelimited(60, Uint8Array.of(9, 8, 7)), + ]); + const elemPayload = lengthDelimited(1, textPayload); + const richTextPayload = lengthDelimited(2, elemPayload); + const decodedBody = protobuf_decode(lengthDelimited(1, richTextPayload)); + + expect(decodeRichBody(decodedBody, true)).toEqual([ + { type: 'text', text: 'nested known text' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining( + 'unknownTag=60 wireType=2 count=1 bytes=4 reason=no schema decoder path=elem.text', + ), + })); + }); + + it('preserves sibling text when a LightApp is not a JSON object', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const body: MessageBody = { + richText: { + elems: [ + { + lightApp: { + data: Uint8Array.from([0, ...Buffer.from('not-json', 'utf8')]), + }, + } as any, + { text: { str: 'keep me' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep me' }]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('wire light card ignored inputBytes=9 reason=invalid_json'), + })); + expect(captured.some((entry) => entry.message.includes('not-json'))).toBe(false); + }); + + it('records unknown tags on MessageBody and RichText roots', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const knownElem = protobuf_encode({ text: { str: 'root known text' } }); + const richTextPayload = Uint8Array.from([ + ...lengthDelimited(2, knownElem), + ...lengthDelimited(61, Uint8Array.of(4, 5)), + ]); + const rawBody = Uint8Array.from([ + ...lengthDelimited(1, richTextPayload), + ...lengthDelimited(60, Uint8Array.of(6)), + ]); + const decodedBody = protobuf_decode(rawBody); + + expect(decodeRichBody(decodedBody, true)).toEqual([ + { type: 'text', text: 'root known text' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + message: expect.stringContaining('unknownTag=60 wireType=2 count=1 bytes=2 reason=no schema decoder path=body'), + })); + expect(captured).toContainEqual(expect.objectContaining({ + message: expect.stringContaining('unknownTag=61 wireType=2 count=1 bytes=3 reason=no schema decoder path=body.richText'), + })); + }); + + it('does not treat marker-only or non-XML RichMsg data as a card', () => { + const body: MessageBody = { + richText: { + elems: [ + { richMsg: { serviceId: 35, template1: Uint8Array.of(0) } } as any, + { + richMsg: { + serviceId: 35, + template1: Uint8Array.from([0, ...Buffer.from('not xml', 'utf8')]), + }, + } as any, + { text: { str: 'keep malformed card fallback' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([ + { type: 'text', text: 'keep malformed card fallback' }, + ]); + }); + + it('bounds compressed card output and preserves sibling text on overflow', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const compressed = deflateSync(Buffer.alloc(MAX_RICH_CARD_OUTPUT_BYTES + 1, 0x61)); + const data = new Uint8Array(compressed.length + 1); + data[0] = 1; + data.set(compressed, 1); + const body: MessageBody = { + richText: { + elems: [ + { lightApp: { data } } as any, + { text: { str: 'bounded fallback' } } as any, + ], + }, + }; + + expect(decodeRichBody(body, true)).toEqual([ + { type: 'text', text: 'bounded fallback' }, + ]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('reason=output_limit_exceeded'), + })); + }); + + it('bounds retained card output across the entire message', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const payload = { app: 'budget-test', data: 'x'.repeat(3 * 1024 * 1024) }; + const body: MessageBody = { + richText: { + elems: [ + { lightApp: { data: lightAppBytes(payload) } } as any, + { lightApp: { data: lightAppBytes(payload) } } as any, + { lightApp: { data: lightAppBytes(payload) } } as any, + ], + }, + }; + + const decoded = decodeRichBody(body, true); + expect(decoded).toHaveLength(2); + expect(decoded.every((element) => element.type === 'json')).toBe(true); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + expect(captured).toContainEqual(expect.objectContaining({ + scope: 'MsgPush.UnknownElement', + message: expect.stringContaining('reason=message_output_budget_exceeded'), + })); + }); + + it('charges malformed card inflation against the message budget', () => { + const previousLevel = getLogLevel(); + const captured: Array<{ scope: string; message: string }> = []; + setLogLevel('debug'); + const unsubscribe = subscribeLogs((entry) => captured.push(entry)); + try { + const compressed = deflateSync(Buffer.alloc(3 * 1024 * 1024, 0x78)); + const data = new Uint8Array(compressed.length + 1); + data[0] = 1; + data.set(compressed, 1); + const body: MessageBody = { + richText: { + elems: Array.from({ length: 4 }, () => ({ lightApp: { data } } as any)), + }, + }; + + expect(decodeRichBody(body, true)).toEqual([]); + } finally { + unsubscribe(); + setLogLevel(previousLevel); + } + + const exhausted = captured.filter((entry) => ( + entry.scope === 'MsgPush.UnknownElement' + && entry.message.includes('reason=message_output_budget_exceeded') + )); + expect(exhausted).toHaveLength(2); + }); +});