fix(protocol): decode XML forward identities from root attributes

Recognize forward cards with an omitted protocol service ID from the root msg attributes. Decode attribute references once so resource IDs and nested lookup keys survive XML escaping, while preserving ordinary XML when the root declaration is ambiguous.

Refs #547, #556, #558.

Co-authored-by: wanqing-last <[email protected]>
This commit is contained in:
DrSmoothlandwanqing-last committed 2026-10-20 13:49:53 +08:00
1 parent 76846f40b1
commit 9d8df59370
3 files changed
+222 -5

No files matched your search

@@ -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,
+121
View File
@@ -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<string, string> | undefined {
let cursor = content.startsWith('\uFEFF') ? 1 : 0;
for (;;) {
SPACE.lastIndex = cursor;
SPACE.exec(content);
cursor = SPACE.lastIndex;
const closing = content.startsWith('<!--', cursor)
? '-->'
: content.startsWith('<?', cursor)
? '?>'
: 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('<msg', cursor)) {
return undefined;
}
cursor += 4;
const attributes = new Map<string, string>();
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;
}
}
@@ -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&<>"\'&lt;\t\n\r中文😀end';
const elems = await buildSendElems([{ type: 'forward', resId }]);
const body = protobuf_decode<MessageBody>(
protobuf_encode<MessageBody>({ 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 <?xml version="1.0"?> <!-- header --> <?card data?>' +
'<msg brief="a > b" serviceID = \'&#51;&#x35;\' ' +
'm_resid = "res&amp;&lt;&gt;&quot;&apos;&amp;lt;" ' +
"m_fileName = 'key&#9;&#xA;&#13;&#x1F642;' />";
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
{
type: 'forward',
resId: 'res&<>"\'&lt;',
forwardUuid: 'key\t\n\r🙂',
},
]);
},
);
it.each([
'<msg><title>serviceID="35" m_resid="fake"</title></msg>',
'<msg><!-- serviceID="35" m_resid="fake" --></msg>',
'<msg><child serviceID="35" m_resid="fake" /></msg>',
'<wrapper><msg serviceID="35" m_resid="fake" /></wrapper>',
'<!-- <msg serviceID="35" m_resid="fake" /> --><msg />',
'<?test <msg serviceID="35" m_resid="fake" /> ?><msg />',
'<msg><![CDATA[<msg serviceID="35" m_resid="fake" />]]></msg>',
'<msg brief=\'serviceID="35" m_resid="fake"\' />',
'<msg data-serviceID="35" m_resid="fake" />',
'<msg serviceID="35" data-m_resid="fake" />',
'<msg serviceID="35"><child m_resid="fake" /></msg>',
'<msg serviceID="35" m_resid="first" m_resid="second" />',
'<msg 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 = '<msg serviceID="35"><msg m_resid="child" m_fileName="child-key" /></msg>';
expect(decodeRichBody(xmlCardBody(xml, serviceId), true)).toEqual([
{ type: 'xml', text: xml, subType: serviceId },
]);
});
it('preserves an explicit non-forward protocol type', () => {
const xml = '<msg serviceID="35" m_resid="other-card" />';
expect(decodeRichBody(xmlCardBody(xml, 2), true)).toEqual([
{ type: 'xml', text: xml, subType: 2 },
]);
});
it.each(['&unknown;', '&#0;', '&#xD800;', '&#x110000;', '&amp'])(
'preserves XML rather than inventing a lookup key for invalid entity %s',
(entity) => {
const xml = `<msg serviceID="35" m_resid="res${entity}" />`;
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 = {