fix(protocol): suppress big-face compatibility text

Identify QQ's service-37 fallback by its byte-exact nested Text reserve so compatibility descriptions are removed without consuming user-authored sibling text or malformed payload fallbacks.

Fixes #289
This commit is contained in:
DrSmoothl committed 2026-07-29 01:06:59 +08:00
1 parent a93785c0a8
commit 5eb5aaf0a3
2 files changed
+251 -48

No files matched your search

@@ -1,4 +1,4 @@
import { protobuf_decode, protobuf_getUnknownFieldMetadata } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode, protobuf_getUnknownFieldMetadata } from '@snowluma/proton';
import { toHex, toHexUpper } from '@snowluma/common/hex';
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement, MessageElementOf } from '../events';
@@ -12,6 +12,7 @@ import type {
NotOnlineImage,
QFaceExtra,
QSmallFaceExtra,
TextElem,
} 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';
@@ -202,6 +203,20 @@ function decodeCardsOnce(elems: ElemDecoded[]): Map<ElemDecoded, DecodedCards> {
return decoded;
}
function decodeBigFacesOnce(elems: ElemDecoded[]): Map<ElemDecoded, QFaceExtra | null> {
const decoded = new Map<ElemDecoded, QFaceExtra | null>();
for (const elem of elems) {
const ce = elem.commonElem;
if (ce?.serviceType !== 37 || !ce.pbElem) continue;
decoded.set(elem, decodeProtobufPayload(
'commonElem.bigFace',
ce.pbElem,
() => protobuf_decode<QFaceExtra>(ce.pbElem!),
));
}
return decoded;
}
function logUnknownWireMetadata(
value: unknown,
path: string,
@@ -278,6 +293,29 @@ function decodeProtobufPayload<T>(
}
}
const BIG_FACE_COMPAT_SUFFIX = ']请使用最新版手机QQ体验新功能';
function isValidBigFace(extra: QFaceExtra | null | undefined): extra is QFaceExtra & { qsid: number } {
return extra?.qsid !== undefined && Number.isSafeInteger(extra.qsid) && extra.qsid >= 0;
}
function bytesEqual(left: Uint8Array, right: Uint8Array): boolean {
return left.length === right.length && left.every((value, index) => value === right[index]);
}
function isBigFaceCompatibilityText(extra: QFaceExtra, text: TextElem): boolean {
const faceText = extra.text ?? '';
const reserveData = text.pbReserve;
if (!faceText.startsWith('/') || faceText.length === 1 || text.str !== faceText || !reserveData?.length) {
return false;
}
const expected = protobuf_encode<TextElem>({
str: `[${faceText.slice(1)}${BIG_FACE_COMPAT_SUFFIX}`,
});
return bytesEqual(reserveData, expected);
}
type FingerprintElement =
| MessageElementOf<'image'>
| MessageElementOf<'record'>
@@ -366,9 +404,16 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
// 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 decodedBigFaces = decodeBigFacesOnce(elems);
const hasCard = [...decodedCards.values()].some((cards) => (
Boolean(cards.rich?.element || cards.light?.element)
));
// QQ NT serializes a service-37 big face as the CommonElem followed by a
// compatibility TextElem. The latter repeats QFaceExtra.text in `str`, while
// field 12 contains a nested TextElem whose `str` is
// `[face name]请使用最新版手机QQ体验新功能`. Suppress only that proven wire
// shape (#289); a sibling user-authored text has no such reserve and survives.
let previousBigFace: QFaceExtra | null = null;
// [#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 —
@@ -379,6 +424,9 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
for (const elem of elems) {
const resultCountBeforeElement = result.length;
const precedingBigFace = previousBigFace;
const decodedBigFace = decodedBigFaces.get(elem);
previousBigFace = isValidBigFace(decodedBigFace) ? decodedBigFace : null;
logUnknownWireMetadata(elem, 'elem');
// Proton materializes every schema key with a null/default value, so key
@@ -449,45 +497,51 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
// Text (with possible @ detection)
if (elem.text) {
const t = elem.text;
let mention: MentionExtra | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
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);
const suppressBigFaceCompatibilityText = precedingBigFace
? isBigFaceCompatibilityText(precedingBigFace, t)
: false;
// [#127] drop the reply's structural auto-mention (type=2, uin=0) and the
// blank separator text right after it; keep real @s (non-zero uin).
if (sawReply && mention && mention.type === 2 && (mention.uin ?? 0) === 0) {
dropNextBlankText = true;
continue;
}
if (dropNextBlankText) {
dropNextBlankText = false;
if (!hasMention && (t.str ?? '').trim() === '') continue;
}
if (!suppressBigFaceCompatibilityText) {
let mention: MentionExtra | null = null;
if (t.pbReserve && t.pbReserve.length > 0) {
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);
if (hasAttr6 || hasMention) {
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;
// [#127] drop the reply's structural auto-mention (type=2, uin=0) and the
// blank separator text right after it; keep real @s (non-zero uin).
if (sawReply && mention && mention.type === 2 && (mention.uin ?? 0) === 0) {
dropNextBlankText = true;
continue;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
if (dropNextBlankText) {
dropNextBlankText = false;
if (!hasMention && (t.str ?? '').trim() === '') continue;
}
if (hasAttr6 || hasMention) {
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;
}
if (hasMention && mention) {
me.uid = mention.uid ?? '';
if (!me.targetUin) me.targetUin = mention.uin ?? 0;
}
result.push(me);
} else {
const text = t.str ?? '';
// [#146] drop QQ's ark-compat fallback text — structurally, like the
// kernel codec: a card message collapses to just the card element.
if (text && hasCard) continue;
if (text) result.push({ type: 'text', text });
}
result.push(me);
} else {
const text = t.str ?? '';
// [#146] drop QQ's ark-compat fallback text — structurally, like the
// kernel codec: a card message collapses to just the card element.
if (text && hasCard) continue;
if (text) result.push({ type: 'text', text });
}
}
@@ -754,13 +808,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
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 = decodeProtobufPayload(
'commonElem.bigFace',
ce.pbElem,
() => protobuf_decode<QFaceExtra>(ce.pbElem!),
);
if (extra?.qsid !== undefined && Number.isSafeInteger(extra.qsid) && extra.qsid >= 0) {
// Big face. Payloads are decoded before iteration so the immediately
// following compatibility TextElem can be classified without decoding
// this protobuf twice.
const extra = decodedBigFaces.get(elem);
if (isValidBigFace(extra)) {
result.push({ type: 'face', faceId: extra.qsid });
}
} else if (svcType === 45 && ce.pbElem && ce.pbElem.length > 0) {
@@ -18,7 +18,13 @@ 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 { Elem, MsgInfo, QFaceExtra, SrcMsgPbReserve } from '@snowluma/proto-defs/element';
import type {
Elem,
MsgInfo,
QFaceExtra,
SrcMsgPbReserve,
TextElem,
} from '@snowluma/proto-defs/element';
function lightAppBytes(json: unknown): Uint8Array {
const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8'));
@@ -529,7 +535,43 @@ describe('decodeRichBody / unknown wire element observability', () => {
expect(decodeRichBody(body, true)).toEqual([{ type: 'text', text: 'keep next' }]);
});
it('does not consume sibling text after a decoded big face', () => {
it('[#289] drops a big-face compatibility text identified by its nested Text reserve', () => {
const compatibilityReserve = protobuf_encode<TextElem>({
str: '[打call]请使用最新版手机QQ体验新功能',
});
// Issue #289 logged field 1 as bytes=51: one length byte plus the
// 50-byte UTF-8 compatibility string (the protobuf field key is separate).
expect(compatibilityReserve).toHaveLength(52);
const body: MessageBody = {
richText: {
elems: [
{
commonElem: {
serviceType: 37,
businessType: 1,
pbElem: protobuf_encode<QFaceExtra>({
qsid: 311,
text: '/打call',
}),
},
} as any,
{
text: {
str: '/打call',
pbReserve: compatibilityReserve,
},
} as any,
],
},
};
expect(decodeRichBody(body, true)).toEqual([
{ type: 'face', faceId: 311 },
]);
});
it('does not consume sibling user text after a decoded big face', () => {
const body: MessageBody = {
richText: {
elems: [
@@ -537,17 +579,126 @@ describe('decodeRichBody / unknown wire element observability', () => {
commonElem: {
serviceType: 37,
businessType: 0,
pbElem: protobuf_encode<QFaceExtra>({ qsid: 321 }),
pbElem: protobuf_encode<QFaceExtra>({ qsid: 321, text: '/same text' }),
},
} as any,
{ text: { str: 'keep after face' } } as any,
{ text: { str: '/same text' } } as any,
],
},
};
expect(decodeRichBody(body, true)).toEqual([
{ type: 'face', faceId: 321 },
{ type: 'text', text: 'keep after face' },
{ type: 'text', text: '/same text' },
]);
});
it('[#289] preserves compatibility text when the big face has no valid face id', () => {
const body: MessageBody = {
richText: {
elems: [
{
commonElem: {
serviceType: 37,
businessType: 1,
pbElem: protobuf_encode<QFaceExtra>({ text: '/打call' }),
},
} as any,
{
text: {
str: '/打call',
pbReserve: protobuf_encode<TextElem>({
str: '[打call]请使用最新版手机QQ体验新功能',
}),
},
} as any,
],
},
};
expect(decodeRichBody(body, true)).toEqual([
{ type: 'text', text: '/打call' },
]);
});
it('[#289] suppresses only compatibility text and decodes other fields in the same element', () => {
const compatibilityReserve = protobuf_encode<TextElem>({
str: '[打call]请使用最新版手机QQ体验新功能',
});
const body: MessageBody = {
richText: {
elems: [
{
commonElem: {
serviceType: 37,
businessType: 1,
pbElem: protobuf_encode<QFaceExtra>({ qsid: 311, text: '/打call' }),
},
} as any,
{
text: { str: '/打call', pbReserve: compatibilityReserve },
face: { index: 14 },
} as any,
],
},
};
expect(decodeRichBody(body, true)).toEqual([
{ type: 'face', faceId: 311 },
{ type: 'face', faceId: 14 },
]);
});
it('[#289] preserves text when the nested reserve has extra wire fields', () => {
const canonical = protobuf_encode<TextElem>({
str: '[打call]请使用最新版手机QQ体验新功能',
});
const nonCanonical = Uint8Array.from([...canonical, 0x12, 0x00]);
const body: MessageBody = {
richText: {
elems: [
{
commonElem: {
serviceType: 37,
businessType: 1,
pbElem: protobuf_encode<QFaceExtra>({ qsid: 311, text: '/打call' }),
},
} as any,
{ text: { str: '/打call', pbReserve: nonCanonical } } as any,
],
},
};
expect(decodeRichBody(body, true)).toEqual([
{ type: 'face', faceId: 311 },
{ type: 'text', text: '/打call' },
]);
});
it('[#289] preserves sibling text when its nested reserve is not QQ compatibility text', () => {
const body: MessageBody = {
richText: {
elems: [
{
commonElem: {
serviceType: 37,
businessType: 1,
pbElem: protobuf_encode<QFaceExtra>({ qsid: 311, text: '/打call' }),
},
} as any,
{
text: {
str: '/打call',
pbReserve: protobuf_encode<TextElem>({ str: '[打call]ordinary metadata' }),
},
} as any,
],
},
};
expect(decodeRichBody(body, true)).toEqual([
{ type: 'face', faceId: 311 },
{ type: 'text', text: '/打call' },
]);
});