diff --git a/packages/protocol/src/msg-push/rich-body-decoder.ts b/packages/protocol/src/msg-push/rich-body-decoder.ts index 26e9793e..6ece7838 100644 --- a/packages/protocol/src/msg-push/rich-body-decoder.ts +++ b/packages/protocol/src/msg-push/rich-body-decoder.ts @@ -35,6 +35,7 @@ import { MAX_RICH_CARD_OUTPUT_BYTES, ntImageUrlFromFileId, } from './helpers'; +import { readXmlMsgAttributes } from './xml-card'; type ElemDecoded = Elem; type RichTextDecoded = RichText; @@ -135,14 +136,16 @@ function decodeRichMsgCard( return invalidCard(data.length, 'invalid_xml', decoded.budgetBytes); } - if (svcId === 35) { - const match = /\bm_resid="([^"]+)"/.exec(content); + const rootAttributes = svcId === 0 || svcId === 35 ? readXmlMsgAttributes(content) : undefined; + + if (svcId === 35 || (svcId === 0 && rootAttributes?.get('serviceID') === '35')) { + const resId = rootAttributes?.get('m_resid'); // XML forwards link bundled inner messages by m_fileName, just as // LightApp forwards use uniseq. Keep it for the outer payload lookup. - const fileName = /\bm_fileName="([^"]+)"/.exec(content)?.[1]; + const fileName = rootAttributes?.get('m_fileName') || undefined; return { - element: match - ? { type: 'forward', resId: match[1], forwardUuid: fileName } + element: resId + ? { type: 'forward', resId, forwardUuid: fileName } : { type: 'xml', text: content, subType: svcId }, error: null, inputBytes: data.length, diff --git a/packages/protocol/src/msg-push/xml-card.ts b/packages/protocol/src/msg-push/xml-card.ts new file mode 100644 index 00000000..2abcf922 --- /dev/null +++ b/packages/protocol/src/msg-push/xml-card.ts @@ -0,0 +1,121 @@ +const NAME_START = + ':A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D' + + '\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF' + + '\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\u{10000}-\\u{EFFFF}'; +const ATTRIBUTE = new RegExp( + `([${NAME_START}][\\u0300-\\u036F${NAME_START}\\-.0-9\\u00B7\\u203F-\\u2040]*)` + + `[\\t\\r\\n ]*=[\\t\\r\\n ]*(?:"([^"<]*)"|'([^'<]*)')`, + 'uy', +); +const SPACE = /[\t\r\n ]*/y; +const ENTITIES = new Map([ + ['amp', '&'], + ['lt', '<'], + ['gt', '>'], + ['quot', '"'], + ['apos', "'"], +]); + +function decodeAttribute(value: string): string | undefined { + let valid = true; + // Literal whitespace is normalized before expanding character references. + const decoded = value + .replace(/\r\n|[\t\r\n]/g, ' ') + .replace( + /&(#x[0-9a-fA-F]+|#[0-9]+|amp|lt|gt|quot|apos);|&/g, + (_match, entity: string | undefined) => { + const named = entity === undefined ? undefined : ENTITIES.get(entity); + + if (named !== undefined) { + return named; + } + + if (entity?.startsWith('#')) { + const code = entity.startsWith('#x') + ? Number.parseInt(entity.slice(2), 16) + : Number.parseInt(entity.slice(1), 10); + + if ( + code === 9 || + code === 10 || + code === 13 || + (code >= 0x20 && code <= 0xd7ff) || + (code >= 0xe000 && code <= 0xfffd) || + (code >= 0x10000 && code <= 0x10ffff) + ) { + return String.fromCodePoint(code); + } + } + + valid = false; + return ''; + }, + ); + return valid ? decoded : undefined; +} + +/** Read the first element's attributes without searching comments, values or descendants. */ +export function readXmlMsgAttributes(content: string): ReadonlyMap | undefined { + let cursor = content.startsWith('\uFEFF') ? 1 : 0; + + for (;;) { + SPACE.lastIndex = cursor; + SPACE.exec(content); + cursor = SPACE.lastIndex; + const closing = content.startsWith('' + : content.startsWith('' + : undefined; + + if (!closing) { + break; + } + + const end = content.indexOf(closing, cursor + (closing === '-->' ? 4 : 2)); + + if (end < 0) { + return undefined; + } + + cursor = end + closing.length; + } + + if (!content.startsWith('(); + + for (;;) { + const beforeSpace = cursor; + SPACE.lastIndex = cursor; + SPACE.exec(content); + cursor = SPACE.lastIndex; + + if (content[cursor] === '>' || content.startsWith('/>', cursor)) { + return attributes; + } + + if (cursor === beforeSpace) { + return undefined; + } + + ATTRIBUTE.lastIndex = cursor; + const match = ATTRIBUTE.exec(content); + + if (!match || attributes.has(match[1]!)) { + return undefined; + } + + const value = decodeAttribute(match[2] ?? match[3]!); + + if (value === undefined) { + return undefined; + } + + attributes.set(match[1]!, value); + cursor = ATTRIBUTE.lastIndex; + } +} 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 355eb448..0ad4fd43 100644 --- a/packages/protocol/tests/msg-push/rich-body-decoder.test.ts +++ b/packages/protocol/tests/msg-push/rich-body-decoder.test.ts @@ -61,6 +61,99 @@ function lengthDelimited(fieldNumber: number, payload: Uint8Array): Uint8Array { ]); } +function xmlCardBody(xml: string, serviceId = 0): MessageBody { + return { + richText: { + elems: [ + { + richMsg: { + serviceId, + template1: Buffer.concat([Buffer.from([0]), Buffer.from(xml, 'utf8')]), + }, + }, + ], + }, + }; +} + +describe('decodeRichBody / XML forward attributes', () => { + it('round-trips escaped resource IDs through the real sender and receiver', async () => { + const resId = 'res&<>"\'<\t\n\r中文😀end'; + const elems = await buildSendElems([{ type: 'forward', resId }]); + const body = protobuf_decode( + protobuf_encode({ richText: { elems } }), + ); + expect(decodeRichBody(body, true)).toEqual([ + { type: 'forward', resId, forwardUuid: expect.any(String) }, + ]); + }); + + it.each([0, 35])( + 'reads quoted root attributes and decodes entities once (service=%s)', + (serviceId) => { + const xml = + '\uFEFF ' + + '"; + expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([ + { + type: 'forward', + resId: 'res&<>"\'<', + forwardUuid: 'key\t\n\r🙂', + }, + ]); + }, + ); + + it.each([ + 'serviceID="35" m_resid="fake"', + '', + '', + '', + '', + ' ?>', + ']]>', + '', + '', + '', + '', + '', + '', + ])( + 'preserves XML when forward attributes are not an unambiguous root declaration: %s', + (xml) => { + expect(decodeRichBody(xmlCardBody(xml), true)).toEqual([ + { type: 'xml', text: xml, subType: 0 }, + ]); + }, + ); + + it.each([0, 35])('does not borrow a child resource ID (service=%s)', (serviceId) => { + const xml = ''; + expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([ + { type: 'xml', text: xml, subType: serviceId }, + ]); + }); + + it('preserves an explicit non-forward protocol type', () => { + const xml = ''; + expect(decodeRichBody(xmlCardBody(xml, 2), true)).toEqual([ + { type: 'xml', text: xml, subType: 2 }, + ]); + }); + + it.each(['&unknown;', '�', '�', '�', '&'])( + 'preserves XML rather than inventing a lookup key for invalid entity %s', + (entity) => { + const xml = ``; + expect(decodeRichBody(xmlCardBody(xml, 35), true)).toEqual([ + { type: 'xml', text: xml, subType: 35 }, + ]); + }, + ); +}); + describe('decodeRichBody / forward LightApp', () => { it('emits {type:"forward", resId, forwardUuid} for com.tencent.multimsg', () => { const body: MessageBody = {