12 files changed
+536
-46
No files matched your search
@@ -492,7 +492,12 @@ export const ELEMENT_CODECS = {
|
|||||||
},
|
},
|
||||||
|
|
||||||
markdown: {
|
markdown: {
|
||||||
// 收侧(S)无对应,仅发·解存在。
|
async toSegment(element) {
|
||||||
|
return {
|
||||||
|
type: 'markdown',
|
||||||
|
data: { content: element.text },
|
||||||
|
};
|
||||||
|
},
|
||||||
async fromSegment(data) {
|
async fromSegment(data) {
|
||||||
return {
|
return {
|
||||||
type: 'markdown',
|
type: 'markdown',
|
||||||
@@ -500,6 +505,36 @@ export const ELEMENT_CODECS = {
|
|||||||
};
|
};
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
|
|
||||||
|
inline_keyboard: {
|
||||||
|
async toSegment(element) {
|
||||||
|
return {
|
||||||
|
type: 'inline_keyboard',
|
||||||
|
data: {
|
||||||
|
bot_appid: element.botAppid,
|
||||||
|
rows: element.rows.map((row) => ({
|
||||||
|
buttons: row.buttons.map((button) => ({
|
||||||
|
id: button.id,
|
||||||
|
label: button.label,
|
||||||
|
visited_label: button.visitedLabel,
|
||||||
|
style: button.style,
|
||||||
|
type: button.type,
|
||||||
|
click_limit: button.clickLimit,
|
||||||
|
unsupport_tips: button.unsupportedTips,
|
||||||
|
data: button.data,
|
||||||
|
at_bot_show_channel_list: button.atBotShowChannelList,
|
||||||
|
permission_type: button.permissionType,
|
||||||
|
specify_role_ids: button.specifyRoleIds,
|
||||||
|
specify_user_ids: button.specifyUserIds,
|
||||||
|
is_reply: button.isReply,
|
||||||
|
enter: button.enter,
|
||||||
|
anchor: button.anchor,
|
||||||
|
})),
|
||||||
|
})),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
} satisfies ElementCodecMap;
|
} satisfies ElementCodecMap;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1791,6 +1791,7 @@ function elementPreview(element: MessageElement): string {
|
|||||||
case 'json': return '[JSON消息]';
|
case 'json': return '[JSON消息]';
|
||||||
case 'xml': return '[XML消息]';
|
case 'xml': return '[XML消息]';
|
||||||
case 'markdown': return '[Markdown]';
|
case 'markdown': return '[Markdown]';
|
||||||
|
case 'inline_keyboard': return '[交互按钮]';
|
||||||
case 'forward': return '[聊天记录]';
|
case 'forward': return '[聊天记录]';
|
||||||
case 'poke': return '[窗口抖动]';
|
case 'poke': return '[窗口抖动]';
|
||||||
default: return '';
|
default: return '';
|
||||||
|
|||||||
@@ -365,7 +365,7 @@ describe('convertEvent — request kinds', () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('convertEvent — message elements (13 segment types)', () => {
|
describe('convertEvent — message elements', () => {
|
||||||
// Round-trips one element through elementsToOneBotSegments and
|
// Round-trips one element through elementsToOneBotSegments and
|
||||||
// asserts the OneBot segment shape. Resolvers are wired only when
|
// asserts the OneBot segment shape. Resolvers are wired only when
|
||||||
// the element type needs them. JsonArray's index type is JsonValue
|
// the element type needs them. JsonArray's index type is JsonValue
|
||||||
@@ -523,6 +523,62 @@ describe('convertEvent — message elements (13 segment types)', () => {
|
|||||||
expect((seg2.data as Record<string, unknown>).resid).toBe(50);
|
expect((seg2.data as Record<string, unknown>).resid).toBe(50);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it('markdown: exposes the original content on receive', async () => {
|
||||||
|
const seg = await segment({ type: 'markdown', text: '# Bot answer' });
|
||||||
|
expect(seg).toEqual({ type: 'markdown', data: { content: '# Bot answer' } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('inline keyboard: exposes rows and actionable button metadata', async () => {
|
||||||
|
const seg = await segment({
|
||||||
|
type: 'inline_keyboard',
|
||||||
|
botAppid: '9007199254740993',
|
||||||
|
rows: [{
|
||||||
|
buttons: [{
|
||||||
|
id: 'btn-1',
|
||||||
|
label: 'Run',
|
||||||
|
visitedLabel: 'Done',
|
||||||
|
style: 1,
|
||||||
|
type: 2,
|
||||||
|
clickLimit: 3,
|
||||||
|
unsupportedTips: 'Admins only',
|
||||||
|
data: 'callback-data',
|
||||||
|
atBotShowChannelList: true,
|
||||||
|
permissionType: 2,
|
||||||
|
specifyRoleIds: ['admin'],
|
||||||
|
specifyUserIds: ['u_10001'],
|
||||||
|
isReply: false,
|
||||||
|
enter: true,
|
||||||
|
anchor: 9,
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
});
|
||||||
|
expect(seg).toEqual({
|
||||||
|
type: 'inline_keyboard',
|
||||||
|
data: {
|
||||||
|
bot_appid: '9007199254740993',
|
||||||
|
rows: [{
|
||||||
|
buttons: [{
|
||||||
|
id: 'btn-1',
|
||||||
|
label: 'Run',
|
||||||
|
visited_label: 'Done',
|
||||||
|
style: 1,
|
||||||
|
type: 2,
|
||||||
|
click_limit: 3,
|
||||||
|
unsupport_tips: 'Admins only',
|
||||||
|
data: 'callback-data',
|
||||||
|
at_bot_show_channel_list: true,
|
||||||
|
permission_type: 2,
|
||||||
|
specify_role_ids: ['admin'],
|
||||||
|
specify_user_ids: ['u_10001'],
|
||||||
|
is_reply: false,
|
||||||
|
enter: true,
|
||||||
|
anchor: 9,
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
it('file: canonical file/file_id/file_size + legacy name/size/id + url + file_hash', async () => {
|
it('file: canonical file/file_id/file_size + legacy name/size/id + url + file_hash', async () => {
|
||||||
const seg = await segment(
|
const seg = await segment(
|
||||||
{ type: 'file', fileName: 'doc.pdf', fileSize: 7, fileId: 'fid', fileHash: 'h' },
|
{ type: 'file', fileName: 'doc.pdf', fileSize: 7, fileId: 'fid', fileHash: 'h' },
|
||||||
|
|||||||
@@ -95,5 +95,11 @@ export interface MentionExtraSend {
|
|||||||
|
|
||||||
// MarkdownData
|
// MarkdownData
|
||||||
export interface MarkdownData {
|
export interface MarkdownData {
|
||||||
content?: pb<1, string>;
|
content?: pb<1, string>;
|
||||||
|
field2?: pb<2, string>;
|
||||||
|
field3?: pb<3, bytes>;
|
||||||
|
processMsg?: pb<4, string>;
|
||||||
|
summary?: pb<5, string>;
|
||||||
|
extType?: pb<6, uint_32>;
|
||||||
|
field7?: pb<7, bytes>;
|
||||||
}
|
}
|
||||||
@@ -241,6 +241,50 @@ export interface CommonElem {
|
|||||||
businessType?: pb<3, uint_32>;
|
businessType?: pb<3, uint_32>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** CommonElem services 46/50/51, business type 1. */
|
||||||
|
export interface InlineKeyboardPermission {
|
||||||
|
type?: pb<1, uint_32>;
|
||||||
|
specifyRoleIds?: pb_repeated<2, string>;
|
||||||
|
specifyUserIds?: pb_repeated<3, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardAction {
|
||||||
|
type?: pb<1, uint_32>;
|
||||||
|
permission?: pb<2, InlineKeyboardPermission>;
|
||||||
|
clickLimit?: pb<3, uint_32>;
|
||||||
|
unsupportedTips?: pb<4, string>;
|
||||||
|
data?: pb<5, string>;
|
||||||
|
atBotShowChannelList?: pb<6, bool>;
|
||||||
|
reply?: pb<7, bool>;
|
||||||
|
enter?: pb<8, bool>;
|
||||||
|
anchor?: pb<9, uint_32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardRenderData {
|
||||||
|
label?: pb<1, string>;
|
||||||
|
visitedLabel?: pb<2, string>;
|
||||||
|
style?: pb<3, uint_32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardButton {
|
||||||
|
id?: pb<1, string>;
|
||||||
|
renderData?: pb<2, InlineKeyboardRenderData>;
|
||||||
|
action?: pb<3, InlineKeyboardAction>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardRow {
|
||||||
|
buttons?: pb_repeated<1, InlineKeyboardButton>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardData {
|
||||||
|
rows?: pb_repeated<1, InlineKeyboardRow>;
|
||||||
|
botAppid?: pb<2, uint_64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardExtra {
|
||||||
|
keyboard?: pb<1, InlineKeyboardData>;
|
||||||
|
}
|
||||||
|
|
||||||
/** Payload carried by CommonElem serviceType=2 for private window shakes. */
|
/** Payload carried by CommonElem serviceType=2 for private window shakes. */
|
||||||
export interface PokeExtra {
|
export interface PokeExtra {
|
||||||
type?: pb<1, uint_32>;
|
type?: pb<1, uint_32>;
|
||||||
|
|||||||
@@ -201,10 +201,15 @@ export const ELEMENT_MANIFEST = {
|
|||||||
note: 'W 仅支持普通好友私聊窗口抖动;send_poke Action 仍表示拍一拍',
|
note: 'W 仅支持普通好友私聊窗口抖动;send_poke Action 仍表示拍一拍',
|
||||||
},
|
},
|
||||||
markdown: {
|
markdown: {
|
||||||
directions: { D: 'no', S: 'no', P: 'yes', W: 'yes' },
|
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
|
||||||
fields: fieldsFor<'markdown'>()(['text']),
|
fields: fieldsFor<'markdown'>()(['text']),
|
||||||
requiredFields: ['text'],
|
requiredFields: ['text'],
|
||||||
note: '收侧(D/S)无对应,仅发送方向存在',
|
},
|
||||||
|
inline_keyboard: {
|
||||||
|
directions: { D: 'yes', S: 'yes', P: 'no', W: 'no' },
|
||||||
|
fields: fieldsFor<'inline_keyboard'>()(['botAppid', 'rows']),
|
||||||
|
requiredFields: ['botAppid', 'rows'],
|
||||||
|
note: '机器人消息的交互按钮;当前仅解码并上报,不支持作为普通消息发送',
|
||||||
},
|
},
|
||||||
flash_file: {
|
flash_file: {
|
||||||
directions: { D: 'yes', S: 'yes', P: 'by-design-no', W: 'by-design-no' },
|
directions: { D: 'yes', S: 'yes', P: 'by-design-no', W: 'by-design-no' },
|
||||||
@@ -245,7 +250,7 @@ const STRING_FIELDS: ReadonlySet<string> = new Set([
|
|||||||
'text', 'uid', 'imageUrl', 'fileId', 'fileName', 'fileHash', 'url',
|
'text', 'uid', 'imageUrl', 'fileId', 'fileName', 'fileHash', 'url',
|
||||||
'thumbUrl', 'summary', 'emojiId', 'emojiKey', 'resId', 'filesetId',
|
'thumbUrl', 'summary', 'emojiId', 'emojiKey', 'resId', 'filesetId',
|
||||||
'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardUuid',
|
'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardUuid',
|
||||||
'md5Hex', 'sha1Hex',
|
'md5Hex', 'sha1Hex', 'botAppid',
|
||||||
]);
|
]);
|
||||||
const NUMBER_FIELDS: ReadonlySet<string> = new Set([
|
const NUMBER_FIELDS: ReadonlySet<string> = new Set([
|
||||||
'faceId', 'targetUin', 'fileSize', 'replySeq', 'replyMessageId',
|
'faceId', 'targetUin', 'fileSize', 'replySeq', 'replyMessageId',
|
||||||
@@ -301,6 +306,53 @@ function validateFieldValue(type: ElementType, field: string, value: unknown): v
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (field === 'rows') {
|
||||||
|
const stringFields = new Set([
|
||||||
|
'id', 'label', 'visitedLabel', 'unsupportedTips', 'data',
|
||||||
|
]);
|
||||||
|
const numberFields = new Set([
|
||||||
|
'style', 'type', 'clickLimit', 'permissionType', 'anchor',
|
||||||
|
]);
|
||||||
|
const booleanFields = new Set([
|
||||||
|
'atBotShowChannelList', 'isReply', 'enter',
|
||||||
|
]);
|
||||||
|
const stringArrayFields = new Set(['specifyRoleIds', 'specifyUserIds']);
|
||||||
|
const buttonFields = new Set([
|
||||||
|
...stringFields, ...numberFields, ...booleanFields, ...stringArrayFields,
|
||||||
|
]);
|
||||||
|
const valid = Array.isArray(value) && value.every((row) => {
|
||||||
|
if (typeof row !== 'object' || row === null || Array.isArray(row)) return false;
|
||||||
|
const rowRecord = row as Record<string, unknown>;
|
||||||
|
if (Object.keys(rowRecord).some((key) => key !== 'buttons') || !Array.isArray(rowRecord.buttons)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return rowRecord.buttons.every((button) => {
|
||||||
|
if (typeof button !== 'object' || button === null || Array.isArray(button)) return false;
|
||||||
|
const buttonRecord = button as Record<string, unknown>;
|
||||||
|
if (Object.keys(buttonRecord).some((key) => !buttonFields.has(key))) return false;
|
||||||
|
return [...stringFields].every((key) => typeof buttonRecord[key] === 'string')
|
||||||
|
&& [...numberFields].every((key) => (
|
||||||
|
typeof buttonRecord[key] === 'number'
|
||||||
|
&& Number.isSafeInteger(buttonRecord[key])
|
||||||
|
&& (buttonRecord[key] as number) >= 0
|
||||||
|
))
|
||||||
|
&& [...booleanFields].every((key) => typeof buttonRecord[key] === 'boolean')
|
||||||
|
&& [...stringArrayFields].every((key) => (
|
||||||
|
Array.isArray(buttonRecord[key])
|
||||||
|
&& (buttonRecord[key] as unknown[]).every((entry) => typeof entry === 'string')
|
||||||
|
));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
if (!valid) {
|
||||||
|
throwValidation(
|
||||||
|
'INVALID_FIELD',
|
||||||
|
'message element "inline_keyboard" field "rows" must contain normalized button rows',
|
||||||
|
type,
|
||||||
|
field,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
if (field === 'mediaNode') {
|
if (field === 'mediaNode') {
|
||||||
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
|
||||||
throwValidation('INVALID_FIELD', `message element "${type}" field "mediaNode" must be an object`, type, field);
|
throwValidation('INVALID_FIELD', `message element "${type}" field "mediaNode" must be an object`, type, field);
|
||||||
@@ -364,6 +416,17 @@ function validateSemantics(
|
|||||||
case 'markdown':
|
case 'markdown':
|
||||||
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'text');
|
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'text');
|
||||||
return;
|
return;
|
||||||
|
case 'inline_keyboard':
|
||||||
|
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'botAppid');
|
||||||
|
if (!/^\d+$/.test(element.botAppid)) {
|
||||||
|
throwValidation(
|
||||||
|
'INVALID_FIELD',
|
||||||
|
'message element "inline_keyboard" field "botAppid" must be an unsigned decimal integer',
|
||||||
|
element.type,
|
||||||
|
'botAppid',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
case 'json': {
|
case 'json': {
|
||||||
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'text');
|
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'text');
|
||||||
if (direction !== 'P' && direction !== 'W') return;
|
if (direction !== 'P' && direction !== 'W') return;
|
||||||
|
|||||||
@@ -68,6 +68,36 @@ export interface MarkdownElement {
|
|||||||
text: string;
|
text: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardButton {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
visitedLabel: string;
|
||||||
|
style: number;
|
||||||
|
type: number;
|
||||||
|
clickLimit: number;
|
||||||
|
unsupportedTips: string;
|
||||||
|
data: string;
|
||||||
|
atBotShowChannelList: boolean;
|
||||||
|
permissionType: number;
|
||||||
|
specifyRoleIds: string[];
|
||||||
|
specifyUserIds: string[];
|
||||||
|
isReply: boolean;
|
||||||
|
enter: boolean;
|
||||||
|
anchor: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InlineKeyboardRow {
|
||||||
|
buttons: InlineKeyboardButton[];
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Receive-side bot keyboard embedded in a CommonElem. */
|
||||||
|
export interface InlineKeyboardElement {
|
||||||
|
type: 'inline_keyboard';
|
||||||
|
/** Kept as decimal text because the wire identifier is uint64. */
|
||||||
|
botAppid: string;
|
||||||
|
rows: InlineKeyboardRow[];
|
||||||
|
}
|
||||||
|
|
||||||
export interface ForwardElement {
|
export interface ForwardElement {
|
||||||
type: 'forward';
|
type: 'forward';
|
||||||
resId: string;
|
resId: string;
|
||||||
@@ -171,6 +201,7 @@ type MessageElementVariant =
|
|||||||
| JsonElement
|
| JsonElement
|
||||||
| XmlElement
|
| XmlElement
|
||||||
| MarkdownElement
|
| MarkdownElement
|
||||||
|
| InlineKeyboardElement
|
||||||
| ForwardElement
|
| ForwardElement
|
||||||
| ImageElement
|
| ImageElement
|
||||||
| RecordElement
|
| RecordElement
|
||||||
|
|||||||
@@ -123,6 +123,7 @@ function renderSegment(type: string, data: Record<string, unknown>): string {
|
|||||||
}
|
}
|
||||||
case 'xml': return '[XML]';
|
case 'xml': return '[XML]';
|
||||||
case 'markdown': return '[Markdown]';
|
case 'markdown': return '[Markdown]';
|
||||||
|
case 'inline_keyboard': return '[交互按钮]';
|
||||||
case 'forward': return '[聊天记录]';
|
case 'forward': return '[聊天记录]';
|
||||||
case 'poke': return '[窗口抖动]';
|
case 'poke': return '[窗口抖动]';
|
||||||
case 'flash_file': {
|
case 'flash_file': {
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import type {
|
|||||||
FileInfo,
|
FileInfo,
|
||||||
GroupFileExtra,
|
GroupFileExtra,
|
||||||
IndexNode,
|
IndexNode,
|
||||||
|
InlineKeyboardExtra,
|
||||||
MentionExtra,
|
MentionExtra,
|
||||||
MsgInfo,
|
MsgInfo,
|
||||||
NotOnlineImage,
|
NotOnlineImage,
|
||||||
@@ -217,6 +218,93 @@ function decodeBigFacesOnce(elems: ElemDecoded[]): Map<ElemDecoded, QFaceExtra |
|
|||||||
return decoded;
|
return decoded;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MARKDOWN_BUSINESS_TYPES: ReadonlySet<number> = new Set([1, 3, 4]);
|
||||||
|
const INLINE_KEYBOARD_SERVICE_TYPES: ReadonlySet<number> = new Set([46, 50, 51]);
|
||||||
|
|
||||||
|
function decodeMarkdownCommonElement(pbElem: Uint8Array, businessType: number): MessageElement | null {
|
||||||
|
const md = decodeProtobufPayload(
|
||||||
|
'commonElem.markdown',
|
||||||
|
pbElem,
|
||||||
|
() => 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);
|
||||||
|
}
|
||||||
|
return { type: 'markdown', text: content };
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeMarkdownElementsOnce(elems: ElemDecoded[]): Map<ElemDecoded, MessageElement | null> {
|
||||||
|
const decoded = new Map<ElemDecoded, MessageElement | null>();
|
||||||
|
for (const elem of elems) {
|
||||||
|
const ce = elem.commonElem;
|
||||||
|
const businessType = ce?.businessType ?? 0;
|
||||||
|
if (ce?.serviceType !== 45 || !MARKDOWN_BUSINESS_TYPES.has(businessType) || !ce.pbElem?.length) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
decoded.set(elem, decodeMarkdownCommonElement(ce.pbElem, businessType));
|
||||||
|
}
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeInlineKeyboardCommonElement(pbElem: Uint8Array): MessageElement | null {
|
||||||
|
const extra = decodeProtobufPayload(
|
||||||
|
'commonElem.inlineKeyboard',
|
||||||
|
pbElem,
|
||||||
|
() => protobuf_decode<InlineKeyboardExtra>(pbElem),
|
||||||
|
);
|
||||||
|
const keyboard = extra?.keyboard;
|
||||||
|
if (!keyboard) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
type: 'inline_keyboard',
|
||||||
|
botAppid: String(keyboard.botAppid ?? 0),
|
||||||
|
rows: (keyboard.rows ?? []).map((row) => ({
|
||||||
|
buttons: (row.buttons ?? []).map((button) => {
|
||||||
|
const render = button.renderData;
|
||||||
|
const action = button.action;
|
||||||
|
const permission = action?.permission;
|
||||||
|
return {
|
||||||
|
id: button.id ?? '',
|
||||||
|
label: render?.label ?? '',
|
||||||
|
visitedLabel: render?.visitedLabel ?? '',
|
||||||
|
style: render?.style ?? 0,
|
||||||
|
type: action?.type ?? 0,
|
||||||
|
clickLimit: action?.clickLimit ?? 0,
|
||||||
|
unsupportedTips: action?.unsupportedTips ?? '',
|
||||||
|
data: action?.data ?? '',
|
||||||
|
atBotShowChannelList: action?.atBotShowChannelList ?? false,
|
||||||
|
permissionType: permission?.type ?? 0,
|
||||||
|
specifyRoleIds: permission?.specifyRoleIds ?? [],
|
||||||
|
specifyUserIds: permission?.specifyUserIds ?? [],
|
||||||
|
isReply: action?.reply ?? false,
|
||||||
|
enter: action?.enter ?? false,
|
||||||
|
anchor: action?.anchor ?? 0,
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function decodeInlineKeyboardsOnce(elems: ElemDecoded[]): Map<ElemDecoded, MessageElement | null> {
|
||||||
|
const decoded = new Map<ElemDecoded, MessageElement | null>();
|
||||||
|
for (const elem of elems) {
|
||||||
|
const ce = elem.commonElem;
|
||||||
|
if (!ce || !INLINE_KEYBOARD_SERVICE_TYPES.has(ce.serviceType ?? 0)
|
||||||
|
|| ce.businessType !== 1 || !ce.pbElem?.length) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
decoded.set(elem, decodeInlineKeyboardCommonElement(ce.pbElem));
|
||||||
|
}
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
|
||||||
function logUnknownWireMetadata(
|
function logUnknownWireMetadata(
|
||||||
value: unknown,
|
value: unknown,
|
||||||
path: string,
|
path: string,
|
||||||
@@ -387,27 +475,19 @@ export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean):
|
|||||||
|
|
||||||
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
||||||
const result: MessageElement[] = [];
|
const result: MessageElement[] = [];
|
||||||
// [#146] A QQ mini-program / ark share (B站 video, QQ 小程序, …) arrives as a
|
// [#146/#337] Rich cards and bot markdown arrive beside a plain compatibility
|
||||||
// `lightApp`/`richMsg` card element plus a plain `text` element carrying QQ's
|
// `text` element for older clients. That sibling has no independent wire
|
||||||
// graceful-degradation compat string ("当前QQ版本不支持此应用,请升级") — the text
|
// marker; QQ NT's codec structurally collapses the pair to the rich element.
|
||||||
// protocol-old clients render instead of the card. The text element has NO wire
|
// Mirror that rule only after the rich payload decodes successfully, so a
|
||||||
// marker distinguishing it (confirmed on-target: no pbReserve / attr6Buf), and
|
// malformed payload fails open and preserves its readable fallback text.
|
||||||
// the receiver binary contains none of these strings, so QQ does NOT match by
|
// Structural @/reply/face elements are not plain text and always survive.
|
||||||
// content. Instead QQ NT's kernel codec (msg_codec_mgr) collapses the message
|
|
||||||
// to a single ark element — the sibling text is never emitted (verified by RE:
|
|
||||||
// wrapper.linux.node has no fallback strings; NapCat maps kernel elements 1:1
|
|
||||||
// with no ark-aware skip yet surfaces only the card). We mirror that structural
|
|
||||||
// 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.
|
|
||||||
// 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 decodedCards = decodeCardsOnce(elems);
|
||||||
const decodedBigFaces = decodeBigFacesOnce(elems);
|
const decodedBigFaces = decodeBigFacesOnce(elems);
|
||||||
const hasCard = [...decodedCards.values()].some((cards) => (
|
const decodedMarkdown = decodeMarkdownElementsOnce(elems);
|
||||||
|
const decodedInlineKeyboards = decodeInlineKeyboardsOnce(elems);
|
||||||
|
const hasRichContent = [...decodedCards.values()].some((cards) => (
|
||||||
Boolean(cards.rich?.element || cards.light?.element)
|
Boolean(cards.rich?.element || cards.light?.element)
|
||||||
));
|
)) || [...decodedMarkdown.values()].some((element) => element?.type === 'markdown');
|
||||||
// QQ NT serializes a service-37 big face as the CommonElem followed by a
|
// QQ NT serializes a service-37 big face as the CommonElem followed by a
|
||||||
// compatibility TextElem. The latter repeats QFaceExtra.text in `str`, while
|
// compatibility TextElem. The latter repeats QFaceExtra.text in `str`, while
|
||||||
// field 12 contains a nested TextElem whose `str` is
|
// field 12 contains a nested TextElem whose `str` is
|
||||||
@@ -537,9 +617,8 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
|||||||
result.push(me);
|
result.push(me);
|
||||||
} else {
|
} else {
|
||||||
const text = t.str ?? '';
|
const text = t.str ?? '';
|
||||||
// [#146] drop QQ's ark-compat fallback text — structurally, like the
|
// Drop the successfully decoded card/markdown compatibility sibling.
|
||||||
// kernel codec: a card message collapses to just the card element.
|
if (text && hasRichContent) continue;
|
||||||
if (text && hasCard) continue;
|
|
||||||
if (text) result.push({ type: 'text', text });
|
if (text) result.push({ type: 'text', text });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -816,12 +895,11 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
|||||||
result.push({ type: 'face', faceId: extra.qsid });
|
result.push({ type: 'face', faceId: extra.qsid });
|
||||||
}
|
}
|
||||||
} else if (svcType === 45 && ce.pbElem && ce.pbElem.length > 0) {
|
} else if (svcType === 45 && ce.pbElem && ce.pbElem.length > 0) {
|
||||||
// Markdown commonElem. Older QQ clients (≤9.9.30) deliver a 闪传 (flash
|
const markdown = decodedMarkdown.get(elem);
|
||||||
// transfer) file as a richui markdown card (busId=FlashTransfer); newer
|
if (markdown) result.push(markdown);
|
||||||
// clients send a plain text+link message that decodes elsewhere. Pull
|
} else if (INLINE_KEYBOARD_SERVICE_TYPES.has(svcType) && bizType === 1 && ce.pbElem?.length) {
|
||||||
// the flash fields out so the message isn't dropped to empty (#199/#200).
|
const keyboard = decodedInlineKeyboards.get(elem);
|
||||||
const flash = decodeFlashTransferCard(ce.pbElem);
|
if (keyboard) result.push(keyboard);
|
||||||
if (flash) result.push(flash);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Route predicates alone are not proof that a payload decoded. Log any
|
// Route predicates alone are not proof that a payload decoded. Log any
|
||||||
@@ -862,14 +940,14 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decode a 闪传 richui markdown commonElem (svc=45) into a `flash_file`
|
* Decode the content of a 闪传 richui markdown commonElem (svc=45) into a
|
||||||
* element. The pbElem is a `MarkdownData` whose `content` is a markdown link
|
* `flash_file` element. The `MarkdownData.content` is a markdown link
|
||||||
* `[闪传](mqqapi://markdown/node?nodeType=richui&json=<url-encoded JSON>)`; the
|
* `[闪传](mqqapi://markdown/node?nodeType=richui&json=<url-encoded JSON>)`; the
|
||||||
* JSON's `busId` is `FlashTransfer`. Field NAMES (fileSetId / sceneType /
|
* JSON's `busId` is `FlashTransfer`. Field NAMES (fileSetId / sceneType /
|
||||||
* title) were confirmed against QQ NT's flash-transfer manager in
|
* 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
|
* 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. Returns
|
* sender's client), so we search recursively rather than pin a path. See
|
||||||
* null for any non-flash markdown. See #199 / #200.
|
* #199 / #200.
|
||||||
*/
|
*/
|
||||||
function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknown {
|
function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknown {
|
||||||
if (depth > 8 || obj === null || typeof obj !== 'object') return undefined;
|
if (depth > 8 || obj === null || typeof obj !== 'object') return undefined;
|
||||||
@@ -885,14 +963,7 @@ function deepFindValue(obj: unknown, keys: readonly string[], depth = 0): unknow
|
|||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
function decodeFlashTransferCard(pbElem: Uint8Array): MessageElement | null {
|
function decodeFlashTransferMarkdown(content: string): MessageElement | null {
|
||||||
const md = decodeProtobufPayload(
|
|
||||||
'commonElem.flashTransfer',
|
|
||||||
pbElem,
|
|
||||||
() => protobuf_decode<MarkdownData>(pbElem),
|
|
||||||
);
|
|
||||||
const content = md?.content ?? '';
|
|
||||||
if (!content.includes('FlashTransfer')) return null;
|
|
||||||
const m = content.match(/[?&]json=([^)\s]+)/);
|
const m = content.match(/[?&]json=([^)\s]+)/);
|
||||||
if (!m) return null;
|
if (!m) return null;
|
||||||
let obj: unknown;
|
let obj: unknown;
|
||||||
|
|||||||
@@ -55,10 +55,12 @@ describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)
|
|||||||
const sampleValue = (field: string): unknown => {
|
const sampleValue = (field: string): unknown => {
|
||||||
if (field === 'replyElements') return [];
|
if (field === 'replyElements') return [];
|
||||||
if (field === 'forwardNews') return [{ text: 'preview' }];
|
if (field === 'forwardNews') return [{ text: 'preview' }];
|
||||||
|
if (field === 'rows') return [{ buttons: [] }];
|
||||||
if (field === 'mediaNode') return {};
|
if (field === 'mediaNode') return {};
|
||||||
if (field === 'emojiId' || field === 'md5Hex') return 'ab'.repeat(16);
|
if (field === 'emojiId' || field === 'md5Hex') return 'ab'.repeat(16);
|
||||||
if (field === 'sha1Hex') return 'cd'.repeat(20);
|
if (field === 'sha1Hex') return 'cd'.repeat(20);
|
||||||
if (field === 'flash' || field === 'noByteFallback') return true;
|
if (field === 'flash' || field === 'noByteFallback') return true;
|
||||||
|
if (field === 'botAppid') return '1';
|
||||||
if (field === 'targetUin' || field === 'faceId' || field === 'fileSize'
|
if (field === 'targetUin' || field === 'faceId' || field === 'fileSize'
|
||||||
|| field.startsWith('reply') || field === 'subType' || field === 'duration'
|
|| field.startsWith('reply') || field === 'subType' || field === 'duration'
|
||||||
|| field === 'width' || field === 'height' || field === 'emojiPackageId'
|
|| field === 'width' || field === 'height' || field === 'emojiPackageId'
|
||||||
|
|||||||
@@ -0,0 +1,179 @@
|
|||||||
|
import { describe, expect, it } from 'vitest';
|
||||||
|
import {
|
||||||
|
protobuf_encode,
|
||||||
|
type bool,
|
||||||
|
type pb,
|
||||||
|
type pb_repeated,
|
||||||
|
type uint_32,
|
||||||
|
type uint_64,
|
||||||
|
} from '@snowluma/proton';
|
||||||
|
import type { MessageBody } from '@snowluma/proto-defs/message';
|
||||||
|
|
||||||
|
import { assertValidMessageElement } from '../../src/element-manifest';
|
||||||
|
import { decodeRichBody } from '../../src/msg-push/rich-body-decoder';
|
||||||
|
|
||||||
|
interface MarkdownFixture {
|
||||||
|
content?: pb<1, string>;
|
||||||
|
processMsg?: pb<4, string>;
|
||||||
|
summary?: pb<5, string>;
|
||||||
|
extType?: pb<6, uint_32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardPermissionFixture {
|
||||||
|
type?: pb<1, uint_32>;
|
||||||
|
roleIds?: pb_repeated<2, string>;
|
||||||
|
userIds?: pb_repeated<3, string>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardActionFixture {
|
||||||
|
type?: pb<1, uint_32>;
|
||||||
|
permission?: pb<2, KeyboardPermissionFixture>;
|
||||||
|
clickLimit?: pb<3, uint_32>;
|
||||||
|
unsupportedTips?: pb<4, string>;
|
||||||
|
data?: pb<5, string>;
|
||||||
|
atBotShowChannelList?: pb<6, bool>;
|
||||||
|
reply?: pb<7, bool>;
|
||||||
|
enter?: pb<8, bool>;
|
||||||
|
anchor?: pb<9, uint_32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardRenderFixture {
|
||||||
|
label?: pb<1, string>;
|
||||||
|
visitedLabel?: pb<2, string>;
|
||||||
|
style?: pb<3, uint_32>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardButtonFixture {
|
||||||
|
id?: pb<1, string>;
|
||||||
|
render?: pb<2, KeyboardRenderFixture>;
|
||||||
|
action?: pb<3, KeyboardActionFixture>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardRowFixture {
|
||||||
|
buttons?: pb_repeated<1, KeyboardButtonFixture>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardFixture {
|
||||||
|
rows?: pb_repeated<1, KeyboardRowFixture>;
|
||||||
|
botAppid?: pb<2, uint_64>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface KeyboardExtraFixture {
|
||||||
|
keyboard?: pb<1, KeyboardFixture>;
|
||||||
|
}
|
||||||
|
|
||||||
|
function commonBody(serviceType: number, businessType: number, pbElem: Uint8Array): MessageBody {
|
||||||
|
return {
|
||||||
|
richText: {
|
||||||
|
elems: [{ commonElem: { serviceType, businessType, pbElem } } as never],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('decodeRichBody / bot markdown (#337)', () => {
|
||||||
|
it('emits the original markdown and removes its plain-text compatibility sibling', () => {
|
||||||
|
const pbElem = protobuf_encode<MarkdownFixture>({
|
||||||
|
content: '# Weather\n**Sunny**',
|
||||||
|
processMsg: 'Weather: Sunny',
|
||||||
|
summary: 'Weather',
|
||||||
|
extType: 3,
|
||||||
|
});
|
||||||
|
const body: MessageBody = {
|
||||||
|
richText: {
|
||||||
|
elems: [
|
||||||
|
{ text: { str: 'Weather: Sunny' } } as never,
|
||||||
|
{ commonElem: { serviceType: 45, businessType: 1, pbElem } } as never,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(decodeRichBody(body, true)).toEqual([
|
||||||
|
{ type: 'markdown', text: '# Weather\n**Sunny**' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('decodes the current extended bot-markdown business type', () => {
|
||||||
|
const pbElem = protobuf_encode<MarkdownFixture>({ content: '## Agent answer' });
|
||||||
|
expect(decodeRichBody(commonBody(45, 4, pbElem), true)).toEqual([
|
||||||
|
{ type: 'markdown', text: '## Agent answer' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('keeps fallback text when the markdown protobuf is malformed', () => {
|
||||||
|
const body: MessageBody = {
|
||||||
|
richText: {
|
||||||
|
elems: [
|
||||||
|
{ text: { str: 'readable fallback' } } as never,
|
||||||
|
{
|
||||||
|
commonElem: {
|
||||||
|
serviceType: 45,
|
||||||
|
businessType: 1,
|
||||||
|
pbElem: Uint8Array.of(0x0A, 0x05, 0x41),
|
||||||
|
},
|
||||||
|
} as never,
|
||||||
|
],
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
expect(decodeRichBody(body, true)).toEqual([
|
||||||
|
{ type: 'text', text: 'readable fallback' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('decodeRichBody / inline keyboard (#337)', () => {
|
||||||
|
const pbElem = protobuf_encode<KeyboardExtraFixture>({
|
||||||
|
keyboard: {
|
||||||
|
botAppid: 9_007_199_254_740_993n,
|
||||||
|
rows: [{
|
||||||
|
buttons: [{
|
||||||
|
id: 'btn-1',
|
||||||
|
render: { label: 'Run', visitedLabel: 'Done', style: 1 },
|
||||||
|
action: {
|
||||||
|
type: 2,
|
||||||
|
permission: { type: 2, roleIds: ['admin'], userIds: ['u_10001'] },
|
||||||
|
clickLimit: 3,
|
||||||
|
unsupportedTips: 'Admins only',
|
||||||
|
data: 'callback-data',
|
||||||
|
atBotShowChannelList: true,
|
||||||
|
reply: false,
|
||||||
|
enter: true,
|
||||||
|
anchor: 9,
|
||||||
|
},
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
it.each([46, 50, 51])('decodes service %i business 1 without losing uint64 app id', (serviceType) => {
|
||||||
|
const elements = decodeRichBody(commonBody(serviceType, 1, pbElem), true);
|
||||||
|
expect(elements).toEqual([{
|
||||||
|
type: 'inline_keyboard',
|
||||||
|
botAppid: '9007199254740993',
|
||||||
|
rows: [{
|
||||||
|
buttons: [{
|
||||||
|
id: 'btn-1',
|
||||||
|
label: 'Run',
|
||||||
|
visitedLabel: 'Done',
|
||||||
|
style: 1,
|
||||||
|
type: 2,
|
||||||
|
clickLimit: 3,
|
||||||
|
unsupportedTips: 'Admins only',
|
||||||
|
data: 'callback-data',
|
||||||
|
atBotShowChannelList: true,
|
||||||
|
permissionType: 2,
|
||||||
|
specifyRoleIds: ['admin'],
|
||||||
|
specifyUserIds: ['u_10001'],
|
||||||
|
isReply: false,
|
||||||
|
enter: true,
|
||||||
|
anchor: 9,
|
||||||
|
}],
|
||||||
|
}],
|
||||||
|
}]);
|
||||||
|
expect(() => assertValidMessageElement(elements[0], 'D')).not.toThrow();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('does not reinterpret an unsupported business type as a keyboard', () => {
|
||||||
|
expect(decodeRichBody(commonBody(46, 2, pbElem), true)).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -40,8 +40,9 @@ describe('decodeRichBody / 闪传 flash_file (#199/#200)', () => {
|
|||||||
expect(out).toEqual([]);
|
expect(out).toEqual([]);
|
||||||
});
|
});
|
||||||
|
|
||||||
it('ignores a non-FlashTransfer markdown card (no flash_file element)', () => {
|
it('does not misclassify a non-FlashTransfer markdown card as flash_file', () => {
|
||||||
const out = decodeRichBody(flashBody({ busId: 'SomethingElse', templateId: 'button' }), true);
|
const out = decodeRichBody(flashBody({ busId: 'SomethingElse', templateId: 'button' }), true);
|
||||||
expect(out.some((e) => e.type === 'flash_file')).toBe(false);
|
expect(out.some((e) => e.type === 'flash_file')).toBe(false);
|
||||||
|
expect(out[0]?.type).toBe('markdown');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user