fix(protocol): decode current NT flash-transfer cards

Current clients put fileset identity on markdown extInfo and the
open_fileset scheme, not data.fileSetId. Empty message arrays were
the old scraper missing those fields.

Fixes #358
This commit is contained in:
DrSmoothl
2026-08-13 18:18:56 +08:00
parent 9e0dd5d75c
commit e7322e2e72
5 changed files with 257 additions and 38 deletions
+12 -2
View File
@@ -93,7 +93,17 @@ export interface MentionExtraSend {
uid?: pb<9, string>;
}
// MarkdownData
// Markdown commonElem (svc=45). Official DecodeMarkdownElement reads
// content / process_msg / summary / extType / mdExtInfo.
// extType=1 dispatches to DecodeMdExtInfoFileTransfer.
export interface MarkdownFlashTransferExt {
filesetId?: pb<1, string>;
name?: pb<2, string>;
fileSize?: pb<3, uint_32>;
thumbnail?: pb<4, bytes>;
expireTime?: pb<6, uint_32>;
}
export interface MarkdownData {
content?: pb<1, string>;
field2?: pb<2, string>;
@@ -101,5 +111,5 @@ export interface MarkdownData {
processMsg?: pb<4, string>;
summary?: pb<5, string>;
extType?: pb<6, uint_32>;
field7?: pb<7, bytes>;
extInfo?: pb<7, MarkdownFlashTransferExt>;
}
+1 -1
View File
@@ -215,7 +215,7 @@ export const ELEMENT_MANIFEST = {
directions: { D: 'yes', S: 'yes', P: 'by-design-no', W: 'by-design-no' },
fields: fieldsFor<'flash_file'>()(['filesetId', 'sceneType', 'fileName']),
requiredFields: ['filesetId'],
note: '闪传文件(#199/#200):旧客户端(≤9.9.30)的 richui markdown 卡片才有;仅收侧解码上报,发送走 send_flash_msg 动作,故 P/W 按设计不支持',
note: '闪传文件:收侧解码 markdown commonElem(旧卡 JSON data.fileSetId,现网 extType=1/extInfo + open_fileset scheme,#199/#200/#358);发送走 send_flash_msg,故 P/W 按设计不支持',
},
} as const satisfies ManifestShape;
@@ -228,15 +228,14 @@ function decodeMarkdownCommonElement(pbElem: Uint8Array, businessType: number):
() => protobuf_decode<MarkdownData>(pbElem),
);
const content = md?.content ?? '';
if (!content) return null;
// Business type 3 is also used by the old flash-transfer richui card. Keep
// that semantic element instead of exposing the transport markdown. If a
// payload identifies itself as FlashTransfer but is malformed, fail open to
// the sibling compatibility text rather than misreporting it as markdown.
if (businessType === 3 && content.includes('FlashTransfer')) {
return decodeFlashTransferMarkdown(content);
// Business type 3 carries the 闪传 card. Current NT puts fileset identity
// on extType=1 / extInfo (DecodeMdExtInfoFileTransfer); older cards only
// have it inside the richui JSON. If the payload looks like FlashTransfer
// but has no fileset, fail open to the sibling compatibility text.
if (md && businessType === 3 && isFlashTransferMarkdown(md, content)) {
return decodeFlashTransfer(md);
}
if (!content) return null;
return { type: 'markdown', text: content };
}
@@ -487,7 +486,9 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
const decodedInlineKeyboards = decodeInlineKeyboardsOnce(elems);
const hasRichContent = [...decodedCards.values()].some((cards) => (
Boolean(cards.rich?.element || cards.light?.element)
)) || [...decodedMarkdown.values()].some((element) => element?.type === 'markdown');
)) || [...decodedMarkdown.values()].some((element) => (
element?.type === 'markdown' || element?.type === 'flash_file'
));
// 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
@@ -940,14 +941,14 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
}
/**
* Decode the content of a 闪传 richui markdown commonElem (svc=45) into a
* `flash_file` element. The `MarkdownData.content` is a markdown link
* `[闪传](mqqapi://markdown/node?nodeType=richui&json=<url-encoded JSON>)`; the
* JSON's `busId` is `FlashTransfer`. Field NAMES (fileSetId / sceneType /
* title) were confirmed against QQ NT's flash-transfer manager in
* wrapper.node.i64; the exact nesting is unknown (the card is built by the
* sender's client), so we search recursively rather than pin a path. See
* #199 / #200.
* Decode a 闪传 markdown commonElem (svc=45, biz=3) into `flash_file`.
*
* Current NT (DecodeMarkdownElement + DecodeMdExtInfoFileTransfer, #358):
* extType=1, extInfo.filesetId / name; click scheme also carries
* `mqqrouter://flash_transfer/open_fileset?fileset_id=`.
* Older cards (#199/#200): only the richui JSON `data.fileSetId`.
* Field names on the JSON card are searched recursively because the
* sender builds that blob; extInfo tags are fixed.
*/
function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknown {
if (depth > 8 || obj === null || typeof obj !== 'object') return undefined;
@@ -963,28 +964,117 @@ function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknow
return undefined;
}
function decodeFlashTransferMarkdown(content: string): MessageElement | null {
const m = content.match(/[?&]json=([^)\s]+)/);
if (!m) return null;
let obj: unknown;
function isFlashTransferMarkdown(md: MarkdownData | null | undefined, content: string): boolean {
if (md?.extType === 1 && md.extInfo?.filesetId) return true;
return content.includes('FlashTransfer') || content.includes('flash_transfer');
}
function parseQueryValue(text: string, key: string): string {
const m = text.match(new RegExp(`[?&]${key}=([^&\\s"']+)`));
if (!m) return '';
try {
obj = JSON.parse(decodeURIComponent(m[1]));
return decodeURIComponent(m[1]).trim();
} catch {
return m[1].trim();
}
}
function collectSchemeFields(obj: unknown): { filesetId: string; sceneType: number | undefined } {
const schemes: string[] = [];
const walk = (value: unknown, depth: number): void => {
if (depth > 8 || value == null) return;
if (typeof value === 'string') {
if (value.includes('fileset_id=') || value.includes('open_fileset')) schemes.push(value);
return;
}
if (typeof value === 'object') {
for (const child of Object.values(value as Record<string, unknown>)) walk(child, depth + 1);
}
};
walk(obj, 0);
for (const scheme of schemes) {
const filesetId = parseQueryValue(scheme, 'fileset_id');
if (!filesetId) continue;
const rawScene = parseQueryValue(scheme, 'scene_type');
const n = Number(rawScene);
return {
filesetId,
sceneType: rawScene && Number.isSafeInteger(n) && n >= 0 ? n : undefined,
};
}
return { filesetId: '', sceneType: undefined };
}
function parseFlashTransferCard(content: string): {
filesetId: string;
fileName: string;
sceneType: number | undefined;
} | null {
const m = content.match(/[?&]json=([^)\s]+)/);
let obj: unknown;
let decodedJson = '';
if (m) {
try {
decodedJson = decodeURIComponent(m[1]);
} catch {
decodedJson = m[1];
}
try {
obj = JSON.parse(decodedJson);
} catch {
obj = undefined;
}
}
const fromKeys = obj
? String(deepFindValue(obj, ['fileSetId', 'filesetId', 'fileset_id', 'file_set_id']) ?? '').trim()
: '';
const fromScheme = obj ? collectSchemeFields(obj) : { filesetId: '', sceneType: undefined };
const fromRaw = {
filesetId: parseQueryValue(decodedJson, 'fileset_id'),
sceneType: Number(parseQueryValue(decodedJson, 'scene_type')),
};
const filesetId = fromKeys || fromScheme.filesetId || fromRaw.filesetId;
if (!filesetId && obj && deepFindValue(obj, ['busId']) !== 'FlashTransfer' && !content.includes('flash_transfer')) {
return null;
}
if (deepFindValue(obj, ['busId']) !== 'FlashTransfer') return 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;
const title = obj ? deepFindValue(obj, ['title', 'fileName', 'name']) : undefined;
const rawScene = obj ? deepFindValue(obj, ['sceneType', 'scene_type']) : undefined;
let sceneType: number | undefined;
if (rawScene != null && rawScene !== '') {
const n = Number(rawScene);
if (Number.isSafeInteger(n) && n >= 0) sceneType = n;
}
if (sceneType == null) sceneType = fromScheme.sceneType;
if (sceneType == null && Number.isSafeInteger(fromRaw.sceneType) && fromRaw.sceneType >= 0 && parseQueryValue(decodedJson, 'scene_type')) {
sceneType = fromRaw.sceneType;
}
return {
filesetId,
fileName: title != null ? String(title) : '',
sceneType,
};
}
function decodeFlashTransfer(md: MarkdownData): MessageElement | null {
const ext = md.extType === 1 ? md.extInfo : undefined;
const card = parseFlashTransferCard(md.content ?? '');
const filesetId = (ext?.filesetId ?? card?.filesetId ?? '').trim();
if (!filesetId) return null;
let fileName = (ext?.name ?? '').trim();
if (!fileName) fileName = (card?.fileName ?? '').trim();
if (!fileName && md.summary) {
fileName = md.summary.replace(/^\[QQ闪传\]\s*/, '').trim();
}
return {
type: 'flash_file',
filesetId: normalizedFilesetId,
fileName: title != null ? String(title) : '',
sceneType: normalizedSceneType,
filesetId,
fileName,
sceneType: card?.sceneType ?? 0,
};
}
File diff suppressed because one or more lines are too long
@@ -1,7 +1,9 @@
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { describe, expect, it } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { decodeRichBody } from '../../src/msg-push/rich-body-decoder';
import type { MessageBody } from '@snowluma/proto-defs/message';
import type { MessageBody, PushMsg } from '@snowluma/proto-defs/message';
import type { MarkdownData } from '@snowluma/proto-defs/action';
// Build a svc=45 richui markdown commonElem carrying a FlashTransfer card, the
@@ -46,3 +48,119 @@ describe('decodeRichBody / 闪传 flash_file (#199/#200)', () => {
expect(out[0]?.type).toBe('markdown');
});
});
// Current NT cards (#358) put fileset identity on MarkdownData.extInfo
// (extType=1 / DecodeMdExtInfoFileTransfer) and in the click scheme. The
// richui JSON no longer has `data.fileSetId`.
function currentNtFlashBody(json: unknown, ext?: MarkdownData['extInfo'], summary?: string): MessageBody {
const markdown = `[闪传](mqqapi://markdown/node?nodeType=richui&json=${encodeURIComponent(JSON.stringify(json))})`;
const pbElem = protobuf_encode<MarkdownData>({
content: markdown,
summary,
extType: ext ? 1 : undefined,
extInfo: ext,
});
return {
richText: { elems: [{ commonElem: { serviceType: 45, businessType: 3, pbElem } } as never] },
};
}
const currentNtCardJson = {
busId: 'FlashTransfer',
templateId: 'flash',
version: 2,
layout: { viewId: 'flash_file', width: -2, height: -2, direction: 'horizontal' },
attributes: {
viewId: 'flash_file',
attributes: [{
viewId: 'file',
scheme: 'mqqrouter://flash_transfer/open_fileset?fileset_id=fs-nt-358&version=1&channel_id=1&src_type=internal&scene_type=1',
}],
},
};
describe('decodeRichBody / 闪传 flash_file (#358 current NT card)', () => {
it('reads filesetId and name from markdown extInfo when the JSON has no data.fileSetId', () => {
const out = decodeRichBody(currentNtFlashBody(currentNtCardJson, {
filesetId: 'fs-nt-358',
name: 'cpwd截图.zip',
fileSize: 9196055,
expireTime: 1787815533,
}, '[QQ闪传] cpwd截图.zip'), true);
expect(out).toEqual([{
type: 'flash_file',
filesetId: 'fs-nt-358',
fileName: 'cpwd截图.zip',
sceneType: 1,
}]);
});
it('falls back to the open_fileset scheme when extInfo is absent', () => {
const out = decodeRichBody(currentNtFlashBody(currentNtCardJson), true);
expect(out).toEqual([{
type: 'flash_file',
filesetId: 'fs-nt-358',
fileName: '',
sceneType: 1,
}]);
});
it('still decodes from extInfo when the richui JSON is truncated', () => {
const markdown = '[闪传](mqqapi://markdown/node?nodeType=richui&json=%7B%22busId%22%3A%22FlashTransfer%22%2C%22src%22%3A%22';
const pbElem = protobuf_encode<MarkdownData>({
content: markdown,
summary: '[QQ闪传] report.pdf',
extType: 1,
extInfo: { filesetId: 'fs-from-ext', name: 'report.pdf' },
});
const out = decodeRichBody({
richText: { elems: [{ commonElem: { serviceType: 45, businessType: 3, pbElem } } as never] },
}, true);
expect(out).toEqual([{
type: 'flash_file',
filesetId: 'fs-from-ext',
fileName: 'report.pdf',
sceneType: 0,
}]);
});
it('drops the compatibility text sibling after a successful flash_file decode', () => {
const markdown = `[闪传](mqqapi://markdown/node?nodeType=richui&json=${encodeURIComponent(JSON.stringify(currentNtCardJson))})`;
const pbElem = protobuf_encode<MarkdownData>({
content: markdown,
extType: 1,
extInfo: { filesetId: 'fs-nt-358', name: 'a.zip' },
});
const out = decodeRichBody({
richText: {
elems: [
{ commonElem: { serviceType: 45, businessType: 3, pbElem } } as never,
{ text: { str: '[闪传]' } } as never,
],
},
}, true);
expect(out).toEqual([{
type: 'flash_file',
filesetId: 'fs-nt-358',
fileName: 'a.zip',
sceneType: 1,
}]);
});
it('decodes the sanitized #358 C2C push (extInfo + open_fileset scheme)', () => {
const hex = readFileSync(
fileURLToPath(new URL('./fixtures/issue-358-flash-push.hex', import.meta.url)),
'utf8',
).trim();
const push = protobuf_decode<PushMsg>(Buffer.from(hex, 'hex'));
const out = decodeRichBody(push.message?.body, false);
// Reporter redacted the richui JSON (unterminated src), so scene_type
// cannot be recovered from the scheme. extInfo still supplies fileset + name.
expect(out).toEqual([{
type: 'flash_file',
filesetId: '[UUID]',
fileName: 'cpwd截图.zip',
sceneType: 0,
}]);
});
});