fix(protocol): enforce message element contracts end to end

Replace the open message bag with a validated discriminated union and preflight complete messages before uploads or sends. Return BAD_REQUEST for invalid or unsendable segments instead of dropping fields, sending partial content, or silently changing private messages.
This commit is contained in:
DrSmoothl
2026-07-10 13:47:06 +08:00
parent aff6ad9179
commit 01688c7567
24 changed files with 1883 additions and 417 deletions
+23 -4
View File
@@ -10,7 +10,8 @@ import type {
} from '@snowluma/proto-defs/longmsg';
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { parseMsgPush } from '@snowluma/protocol/msg-push';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { randomUUID } from 'crypto';
@@ -242,8 +243,8 @@ function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElemen
};
}
function stripFileSource(element: MessageElement): MessageElement {
const next: MessageElement = { ...element };
function stripFileSource(element: MessageElementOf<'file'>): MessageElementOf<'file'> {
const next: MessageElementOf<'file'> = { ...element };
delete next.url;
return next;
}
@@ -267,10 +268,28 @@ function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta):
return (element.fileName ?? cached?.fileName ?? '').trim();
}
function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
for (const node of nodes) {
const fileCount = node.elements.filter((element) => element.type === 'file').length;
if (fileCount > 1) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'a private forward node can contain at most one file element',
'file',
);
}
if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward);
}
}
export class ForwardApi {
constructor(private readonly ctx: BridgeContext) { }
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
// A c2c RichText owns exactly one msgContent/FileExtra payload. Validate
// the entire recursive tree before any file/media/long-message upload so a
// second file cannot be uploaded and then silently discarded.
if (groupId === undefined) assertPrivateForwardFileCapacity(nodes);
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
return resId;
}
@@ -290,7 +309,7 @@ export class ForwardApi {
name: string,
groupId?: number,
userId?: number,
): Promise<MessageElement> {
): Promise<MessageElementOf<'file'>> {
if (groupId !== undefined) {
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
@@ -267,6 +267,38 @@ describe('actions/forward — file segment inside forward node', () => {
})]);
});
it('rejects two files in one private forward node before uploading either file', async () => {
buildSendElemsMock.mockClear();
const uploadPrivate = vi.fn();
const sendRawPacket = vi.fn();
const bridge = mockBridge({
sendRawPacket: sendRawPacket as any,
apis: {
...mockBridge().apis,
groupFile: {
...mockBridge().apis.groupFile,
uploadPrivate,
},
},
});
await expect(new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'file', url: 'base64://AQID', fileName: 'one.txt' },
{ type: 'file', url: 'base64://BAUG', fileName: 'two.txt' },
] as any,
}], undefined, 67890)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'file',
});
expect(uploadPrivate).not.toHaveBeenCalled();
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(sendRawPacket).not.toHaveBeenCalled();
});
it('private file forward keeps the long-msg upload under the self uid namespace', async () => {
buildSendElemsMock.mockClear();
let captured: Uint8Array | undefined;
+61 -12
View File
@@ -28,6 +28,8 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
const fakeBridge = {} as any;
@@ -131,6 +133,55 @@ describe('element-builder / commonElem.businessType per scene', () => {
});
});
describe('element-builder / all-message validation preflight', () => {
it('does not upload an early image when a later segment is unsendable', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await expect(buildSendElems([
{ type: 'image', url: 'file:///tmp/valid-before-invalid.png' },
{ type: 'poke', subType: 1 },
] as any, { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'poke',
});
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
});
it('accepts a received imageUrl-only element for re-send', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await buildSendElems(
[{ type: 'image', imageUrl: 'https://gchat.qpic.cn/received.jpg' }],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(uploadImageMsgInfo).toHaveBeenCalledWith(
fakeBridge,
true,
12345,
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
);
});
it('does not upload an early image when a later fast-only media element lacks hashes', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await expect(buildSendElems([
{ type: 'image', url: 'file:///tmp/valid-before-invalid.png' },
{
type: 'image',
url: 'file:///tmp/must-not-fallback.png',
noByteFallback: true,
},
] as any, { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'image',
field: 'md5Hex',
});
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
});
});
describe('element-builder / file element is no longer carried in elems[]', () => {
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
@@ -141,8 +192,8 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
// segment is split off. The element-builder therefore must NOT emit
// any element for `{type:'file'}` anymore — if it does, the message
// ships with a transElem(24) payload and result=79 returns.
it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => {
const result = await buildSendElems(
it('fails fast when a live {type:"file"} reaches the element builder', async () => {
await expect(buildSendElems(
[{
type: 'file',
fileId: 'fid-abc',
@@ -152,8 +203,11 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
sha1Hex: '0102030405060708090a0b0c0d0e0f1011121314',
} as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(result).toEqual([]);
)).rejects.toMatchObject({
name: 'MessageElementValidationError',
code: 'UNSENDABLE_TYPE',
elementType: 'file',
});
});
});
@@ -228,15 +282,10 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
expect(JSON.parse(json.extra).tsum).toBe(3);
});
it('drops the forward element when resId is missing (preview unrenderable, fail open)', async () => {
// The dispatcher's `case 'forward': if (elem.resId) ...` short-
// circuits when resId is empty so a malformed segment from the
// OneBot client doesn't blow up the whole send. Receiver sees
// no forward bubble — same outcome as omitting the segment.
const out = await buildSendElems(
it('rejects a forward element when resId is missing', async () => {
await expect(buildSendElems(
[{ type: 'forward' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(out).toEqual([]);
)).rejects.toBeInstanceOf(MessageElementValidationError);
});
});
@@ -23,6 +23,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({
}));
import * as pipeline from '@snowluma/protocol/highway/pipeline';
import * as utils from '@snowluma/protocol/highway/utils';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/protocol/highway';
@@ -30,6 +31,7 @@ describe('image-upload', () => {
beforeEach(() => {
vi.mocked(pipeline.runNtv2Upload).mockClear();
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
vi.mocked(utils.loadBinarySource).mockClear();
});
it('group: uses 0x11C4_100 + GROUP_IMAGE_CMD_ID and tags scene as group', async () => {
@@ -58,6 +60,19 @@ describe('image-upload', () => {
expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined();
});
it('uses receive-side imageUrl when url/fileId are absent', async () => {
await uploadImageMsgInfo(
{} as any,
true,
12345,
{ type: 'image', imageUrl: 'https://gchat.qpic.cn/received.jpg' },
);
expect(utils.loadBinarySource).toHaveBeenCalledWith(
'https://gchat.qpic.cn/received.jpg',
'image',
);
});
it('encodes the detected picFormat and image dimensions into fileInfo', async () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x' } as any);
const fileInfo = (vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo[0] as any).fileInfo;
+13 -12
View File
@@ -1,6 +1,7 @@
import { renderParamsVerbose, summarizeParams } from '@snowluma/common/log-summary';
import { createLogger, getLogLevel, nextRequestId, runWithRequestId, type Logger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import {
ACTION_REGISTRY,
HANDLE_QUICK_OPERATION_ACTION,
@@ -244,23 +245,23 @@ export class ApiHandler {
response = await handler(params, sink);
this.log.trace(() => [`${action} ⇒ ${response.status} (${Date.now() - startedAt}ms)`]);
} catch (error) {
// Single error seam: any throw from a handler (bridge/OIDB business
// failure or an unexpected internal fault) maps here to one policy —
// ACTION_FAILED (100) + the error's message. Action `run` bodies
// shouldn't need to hand-roll their own try/catch → failedResponse:
// doing so only produced inconsistent retcodes (100 vs 1200) for the same
// kind of failure. The remaining per-action catches (qzone / group-album,
// still returning 1200) are being removed in a follow-up phase — until
// then their failures never reach this seam. `OidbError.message` already
// carries the QQ server code, so no special-casing is needed. warn (not
// error) keeps the log file a useful signal without drowning it in
// expected client-side failures.
// Single error seam: typed message-contract failures are caller errors
// and therefore map to BAD_REQUEST. Bridge/OIDB business failures and
// unexpected internal faults retain the shared ACTION_FAILED policy.
// Action `run` bodies should not hand-roll their own catch/response
// mapping: central classification keeps every transport consistent.
// `OidbError.message` already carries the QQ server code, so it needs no
// special casing. warn (not error) keeps the log file useful without
// drowning it in expected client-side failures.
this.log.warn('%s failed: %s\n%s',
action,
error instanceof Error ? error.message : String(error),
error instanceof Error ? (error.stack ?? '') : '');
const message = error instanceof Error ? error.message : String(error);
response = failedResponse(RETCODE.ACTION_FAILED, message);
const retcode = error instanceof MessageElementValidationError
? RETCODE.BAD_REQUEST
: RETCODE.ACTION_FAILED;
response = failedResponse(retcode, message);
}
this.notifyObservers(action, params, response, Date.now() - startedAt);
return response;
@@ -1,5 +1,10 @@
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
import type {
MessageElement,
MessageElementOf,
MessageElementType,
} from '@snowluma/protocol/events';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import type { JsonObject } from '../types';
import type { ParseMessageOptions } from '../message-parser';
import type {
@@ -22,7 +27,7 @@ import { resolveReplyId } from './utils';
// 见 element-manifest.ts 的说明。纯 OneBot 输入糖(骰子/分享/…)也不进表,留在
// message-parser 当前置 normalize。
//
// 行为对 to-segment / message-parser 的原实现 byte 级不变——仅把分支体平移到此。
// 每条目由判别类型精确约束:S 读错字段或 P 产出错 discriminant 会在 typecheck 报错。
// ─────────────────────────────────────────────────────────────────────────
const log = createLogger('MsgParser');
@@ -37,27 +42,58 @@ export interface ToSegmentContext {
mediaSegmentSink?: MediaSegmentSink | null;
}
export interface ElementCodec {
// The image segment is the one intentional triangular mapping: an image with
// emoji_id normalizes to a market-face element so it can round-trip as the
// original wire type. Every other codec emits its own discriminant.
type CodecOutput<T extends MessageElementType> = T extends 'image'
? MessageElementOf<'image'> | MessageElementOf<'mface'>
: MessageElementOf<T>;
export interface ElementCodec<T extends MessageElementType = MessageElementType> {
/** S 收·转:MessageElement → OneBot 段。 */
toSegment?: (element: MessageElement, ctx: ToSegmentContext) => Promise<JsonObject>;
/** P 发·解:OneBot 段 data → MessageElement(null = 丢弃该段)。 */
fromSegment?: (data: Record<string, unknown>, options?: ParseMessageOptions) => Promise<MessageElement | null>;
toSegment?: (element: MessageElementOf<T>, ctx: ToSegmentContext) => Promise<JsonObject>;
/** P 发·解:OneBot 段 data → MessageElement(null = 无法构造,parser 会 typed reject)。 */
fromSegment?: (data: Record<string, unknown>, options?: ParseMessageOptions) => Promise<CodecOutput<T> | null>;
}
type ElementCodecMap = Partial<{
readonly [T in MessageElementType]: ElementCodec<T>;
}>;
// ── 共享低层工具(原在 message-parser,移来供本表与 message-parser 的输入糖共用)──
export function intOr(value: unknown, fallback = 0): number {
if (value === undefined || value === null) return fallback;
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
const n = parseInt(String(value), 10);
return Number.isFinite(n) ? n : fallback;
if (typeof value === 'number') {
if (Number.isSafeInteger(value)) return value;
throw new MessageElementValidationError(
'INVALID_FIELD',
`numeric message segment field must be a safe integer, received ${String(value)}`,
);
}
if (typeof value === 'string') {
const text = value.trim();
if (!text) return fallback;
if (!/^[+-]?\d+$/.test(text)) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`numeric message segment field must contain only an integer, received ${JSON.stringify(value)}`,
);
}
const parsed = Number(text);
if (Number.isSafeInteger(parsed)) return parsed;
}
throw new MessageElementValidationError(
'INVALID_FIELD',
`numeric message segment field must be a safe integer, received ${String(value)}`,
);
}
/** Build a market-face (`mface`) element from an OneBot segment's data.
* Shared by the dedicated `mface` segment and the `image`-with-`emoji_id`
* round-trip path. `emojiId` is the hex GUID the wire builder converts back
* to `MarketFace.faceId`. */
export function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElement {
export function marketFaceElement(emojiId: string, data: Record<string, unknown>): MessageElementOf<'mface'> {
return {
type: 'mface',
text: String(data.summary ?? data.name ?? ''),
@@ -95,7 +131,7 @@ export function pickMediaSource(data: Record<string, unknown>): string {
// ── codec 表:一种元素类型一条,键即 element.type(收·转)/ 段 type(发·解,二者同名)──
export const ELEMENT_CODECS: Record<string, ElementCodec> = {
export const ELEMENT_CODECS = {
text: {
async toSegment(element) {
return { type: 'text', data: { text: element.text ?? '' } };
@@ -190,6 +226,7 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
if (element.flash) data.type = 'flash';
if (ctx.mediaSegmentSink) ctx.mediaSegmentSink('image', element, data, ctx.isGroup, ctx.sessionId);
return { type: 'image', data };
},
@@ -203,7 +240,7 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
type: 'image',
url: pickMediaSource(data),
flash: data.type === 'flash',
subType: intOr(data.subType, 0),
subType: intOr(data.sub_type ?? data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
};
},
@@ -276,7 +313,7 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
return {
type: 'xml',
text: String(data.data ?? ''),
subType: intOr(data.id, 0),
subType: intOr(data.resid ?? data.id, 0),
};
},
},
@@ -306,14 +343,16 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
};
},
async fromSegment(data) {
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
const source = String(data.file ?? data.url ?? data.path ?? '').trim();
const fileId = String(data.file_id ?? data.fileId ?? data.id ?? '').trim();
// Reuse the media-source rule: a bare `file` token is commonly only the
// display filename/internal id and must not mask a loadable HTTP URL.
const source = pickMediaSource(data);
if (!fileId && !source) {
log.warn('[MsgParser] file segment without file_id or file/url is unsupported');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
const fileSize = intOr(data.size ?? data.fileSize, 0);
const fileSize = intOr(data.file_size ?? data.size ?? data.fileSize, 0);
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
@@ -375,9 +414,10 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
};
},
async fromSegment(data) {
if (data.type === undefined && data.id === undefined) return null;
return {
type: 'poke',
faceId: intOr(data.type ?? data.id, 0),
subType: intOr(data.type ?? data.id, 0),
};
},
},
@@ -422,4 +462,13 @@ export const ELEMENT_CODECS: Record<string, ElementCodec> = {
};
},
},
};
} satisfies ElementCodecMap;
/**
* Dynamic lookup boundary. Each table entry is checked against its precise
* discriminant above; callers with a runtime type receive the safe union view.
*/
export function getElementCodec(type: string): ElementCodec | undefined {
if (!Object.hasOwn(ELEMENT_CODECS, type)) return undefined;
return (ELEMENT_CODECS as unknown as Record<string, ElementCodec>)[type];
}
@@ -6,7 +6,7 @@ import type {
MediaUrlResolver,
MessageIdResolver,
} from './index';
import { ELEMENT_CODECS } from './element-codecs';
import { getElementCodec } from './element-codecs';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('OneBot');
@@ -47,7 +47,7 @@ async function elementToSegment(
mediaSegmentSink?: MediaSegmentSink | null,
): Promise<JsonObject> {
// S 收·转:按 element.type 查 codec 表;缺条目则走 default 透传(保持原兜底)。
const codec = ELEMENT_CODECS[element.type];
const codec = getElementCodec(element.type);
if (codec?.toSegment) {
return codec.toSegment(element, {
isGroup,
@@ -58,5 +58,6 @@ async function elementToSegment(
mediaSegmentSink,
});
}
log.warn('segment convert fallback type=%s reason=no receive-side codec', element.type);
return { type: element.type, data: {} };
}
+205 -45
View File
@@ -1,11 +1,18 @@
import { createLogger } from '@snowluma/common/logger';
import type { MessageElement } from '@snowluma/protocol/events';
import {
assertValidMessageElement,
ELEMENT_MANIFEST,
MessageElementValidationError,
} from '@snowluma/protocol/element-manifest';
import { parseFromCQString } from './helper/cq';
import { ELEMENT_CODECS, intOr } from './event-converter/element-codecs';
import { getElementCodec, intOr } from './event-converter/element-codecs';
import type { JsonValue } from './types';
const log = createLogger('MsgParser');
export { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
@@ -16,7 +23,7 @@ export interface ParseMessageOptions {
// --- CQ Code parsing ---
export const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
export const CQ_REGEX = /\[CQ:([A-Za-z][A-Za-z0-9_]*)(?:,([^\]]*))?\]/g;
export function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
@@ -44,33 +51,108 @@ interface MessageSegment {
function isSegmentArray(val: unknown): val is MessageSegment[] {
return Array.isArray(val) && val.every(
(item) => typeof item === 'object' && item !== null && 'type' in item
(item) => typeof item === 'object' && item !== null && !Array.isArray(item)
&& typeof (item as { type?: unknown }).type === 'string'
&& (item as { type: string }).type.trim().length > 0,
);
}
function invalidMessageShape(message: string): MessageElementValidationError {
return new MessageElementValidationError('MISSING_FIELD', message, undefined, 'message');
}
function validatedOutboundElement(element: MessageElement): MessageElement {
// P validates the OneBot→MessageElement conversion; W ensures the resulting
// element can actually enter QQ's message-element send pipeline. Keeping
// both checks here makes parseMessage all-or-nothing before any send starts.
assertValidMessageElement(element, 'P');
assertValidMessageElement(element, 'W');
return element;
}
function assertScalarSegmentData(type: string, data: Record<string, unknown>): void {
for (const [field, value] of Object.entries(data)) {
if (
value === undefined
|| value === null
|| typeof value === 'string'
|| typeof value === 'number'
|| typeof value === 'boolean'
) continue;
throw new MessageElementValidationError(
'INVALID_FIELD',
`message segment "${type}" field "${field}" must be a scalar value`,
type,
field,
);
}
}
function requireNonEmptyStringField(
type: string,
data: Record<string, unknown>,
field: string,
): string {
const value = data[field];
if (typeof value !== 'string' || !value.trim()) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`message segment "${type}" field "${field}" must be a non-empty string`,
type,
field,
);
}
return value;
}
function requireCoordinate(
data: Record<string, unknown>,
field: 'lat' | 'lon',
): string {
const raw = data[field];
const text = typeof raw === 'number' ? String(raw) : typeof raw === 'string' ? raw : '';
const value = Number(text);
const limit = field === 'lat' ? 90 : 180;
if (!text.trim() || text !== text.trim() || !Number.isFinite(value) || value < -limit || value > limit) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`message segment "location" field "${field}" must be a finite coordinate between ${String(-limit)} and ${String(limit)}`,
'location',
field,
);
}
return text;
}
export async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
const normalizedType = type.toLowerCase();
// 纯 OneBot 输入糖:不是某种真实消息元素,只是被塌缩成 json/face/poke 的输入
// 便利(或 forward 组装用的中间 node),无收侧对应、无专属 wire 形态,故不进
// codec 表 —— 在这里前置处理。真实元素(收发同名)走下方的 ELEMENT_CODECS。
// Ordinary OneBot segment fields are scalar. Reject objects/arrays before
// codecs can stringify them into "[object Object]" and alter caller intent.
// Forward nodes deliberately own nested content but are rejected by their
// dedicated normal-send branch below; anonymous is rejected regardless of
// payload, so neither needs the scalar guard.
if (normalizedType !== 'node' && normalizedType !== 'anonymous') {
assertScalarSegmentData(normalizedType, data);
}
// 纯 OneBot 输入词:可执行的塌缩成 json/face;没有合法发送语义的 node / shake /
// anonymous 在这里明确拒绝。它们无收侧对应、无专属 wire 形态,故不进 codec 表。
// 真实元素(收发同名)走下方的 ELEMENT_CODECS。
switch (normalizedType) {
case 'node': {
// Fake forward node segment — store the raw data for later processing
// The content field may be a segment array, a single segment, or a CQ string
const name = String(data.nickname ?? data.name ?? '');
return {
type: 'node',
targetUin: intOr(data.user_id ?? data.uin, 0),
text: name,
// Raw content is stored as JSON string in resId for later processing
resId: JSON.stringify(data.content ?? ''),
};
// Forward-node arrays are consumed by parseForwardNodes before reaching
// this function. A node mixed into a normal message is not sendable.
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'message segment "node" is only valid inside a forward node list',
normalizedType,
);
}
case 'share': {
// Link share — map to json card message
const url = String(data.url ?? '');
const title = String(data.title ?? '');
const url = requireNonEmptyStringField(normalizedType, data, 'url');
const title = requireNonEmptyStringField(normalizedType, data, 'title');
const content = String(data.content ?? '');
const image = String(data.image ?? '');
const jsonData = JSON.stringify({
@@ -79,11 +161,26 @@ export async function segmentToElement(type: string, data: Record<string, unknow
prompt: title,
meta: { news: { title, desc: content, jumpUrl: url, preview: image } },
});
return { type: 'json', text: jsonData };
return validatedOutboundElement({ type: 'json', text: jsonData });
}
case 'music': {
// Music share — uses external signing service (NapCat-compatible)
const musicType = String(data.type ?? '');
const musicType = requireNonEmptyStringField(normalizedType, data, 'type');
// Non-custom platform names are deliberately open: musicSignUrl is
// configurable and private signers may support platforms beyond the
// built-in NapCat set. Their executable contract is non-empty type+id.
if (musicType === 'custom') {
requireNonEmptyStringField(normalizedType, data, 'url');
requireNonEmptyStringField(normalizedType, data, 'audio');
requireNonEmptyStringField(normalizedType, data, 'title');
} else if (data.id === undefined || data.id === null || String(data.id).trim() === '') {
throw new MessageElementValidationError(
'MISSING_FIELD',
'message segment "music" requires field "id" for a platform card',
normalizedType,
'id',
);
}
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
try {
let postData: Record<string, unknown>;
@@ -107,7 +204,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
});
if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`);
const musicJson = await resp.text();
return { type: 'json', text: musicJson };
return validatedOutboundElement({ type: 'json', text: musicJson });
} catch (e) {
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
// Fallback: build a basic card locally
@@ -126,13 +223,13 @@ export async function segmentToElement(type: string, data: Record<string, unknow
},
},
});
return { type: 'json', text: jsonData };
return validatedOutboundElement({ type: 'json', text: jsonData });
}
}
case 'location': {
// Location — map to json card
const lat = String(data.lat ?? '');
const lon = String(data.lon ?? '');
const lat = requireCoordinate(data, 'lat');
const lon = requireCoordinate(data, 'lon');
const title = String(data.title ?? '位置');
const content = String(data.content ?? `${lat},${lon}`);
const jsonData = JSON.stringify({
@@ -141,18 +238,34 @@ export async function segmentToElement(type: string, data: Record<string, unknow
prompt: `[位置]${title}`,
meta: { Location: { lat, lng: lon, title, address: content } },
});
return { type: 'json', text: jsonData };
return validatedOutboundElement({ type: 'json', text: jsonData });
}
case 'contact': {
// Contact card — map to json card
const contactType = String(data.type ?? 'qq');
const contactId = String(data.id ?? '');
const contactType = requireNonEmptyStringField(normalizedType, data, 'type');
if (contactType !== 'qq' && contactType !== 'group') {
throw new MessageElementValidationError(
'INVALID_FIELD',
'message segment "contact" field "type" must be "qq" or "group"',
normalizedType,
'type',
);
}
const contactId = String(data.id ?? '').trim();
const numericId = intOr(contactId, 0);
if (numericId <= 0) {
throw new MessageElementValidationError(
'INVALID_FIELD',
'message segment "contact" field "id" must be a positive integer',
normalizedType,
'id',
);
}
const normalizedContactType = contactType.trim().toLowerCase();
if (numericId > 0 && options?.resolveContactArk && (normalizedContactType === 'qq' || normalizedContactType === 'group')) {
const ark = await options.resolveContactArk(contactType, numericId);
if (!ark) throw new Error(`contact ark unavailable for ${contactType}:${numericId}`);
return { type: 'json', text: ark };
return validatedOutboundElement({ type: 'json', text: ark });
}
const jsonData = JSON.stringify({
app: 'com.tencent.contact.lua',
@@ -160,33 +273,55 @@ export async function segmentToElement(type: string, data: Record<string, unknow
prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`,
meta: { contact: { type: contactType, id: contactId } },
});
return { type: 'json', text: jsonData };
return validatedOutboundElement({ type: 'json', text: jsonData });
}
case 'rps': {
// Rock-paper-scissors — map to dice-like face
return { type: 'face', faceId: 359 };
return validatedOutboundElement({ type: 'face', faceId: 359 });
}
case 'dice': {
// Dice — map to dice face
return { type: 'face', faceId: 358 };
return validatedOutboundElement({ type: 'face', faceId: 358 });
}
case 'shake': {
// Window shake — map to poke
return { type: 'poke', faceId: 1 };
// Window shake normalizes to poke, then the W-direction guard returns the
// same explicit "use the dedicated poke Action" validation error.
return validatedOutboundElement({ type: 'poke', subType: 1 });
}
case 'anonymous': {
// Anonymous flag — ignored during send, the protocol handles anonymity
return null;
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'message segment "anonymous" has no executable send semantics',
normalizedType,
);
}
}
// 真实元素(P 发·解,段 type 与 element.type 同名):查 codec 表。
// 见 event-converter/element-codecs.ts。
const codec = ELEMENT_CODECS[normalizedType];
if (codec?.fromSegment) return codec.fromSegment(data, options);
const codec = getElementCodec(normalizedType);
if (codec?.fromSegment) {
const element = await codec.fromSegment(data, options);
if (!element) {
throw new MessageElementValidationError(
'MISSING_FIELD',
`message segment "${normalizedType}" is missing required or usable fields`,
normalizedType,
);
}
return validatedOutboundElement(element);
}
console.warn(`[MsgParser] unsupported segment type: ${type}`);
return null;
if (Object.hasOwn(ELEMENT_MANIFEST, normalizedType)) {
// Known receive-only/by-design-no type (currently flash_file). Ask the
// executable manifest for the stable error + dedicated-Action hint.
assertValidMessageElement({ type: normalizedType }, 'P');
}
throw new MessageElementValidationError(
'UNKNOWN_TYPE',
`unknown message segment type: ${type}`,
normalizedType,
);
}
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
@@ -203,31 +338,56 @@ function segmentPayload(seg: MessageSegment): Record<string, unknown> {
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
if (typeof message === 'string') {
if (message.length === 0) throw invalidMessageShape('message must not be empty');
if (autoEscape) {
return message ? [{ type: 'text', text: message }] : [];
return [validatedOutboundElement({ type: 'text', text: message })];
}
return parseFromCQString(message, options);
const elements = await parseFromCQString(message, options);
if (elements.length === 0) throw invalidMessageShape('message must contain at least one sendable segment');
return elements;
}
if (isSegmentArray(message)) {
if (Array.isArray(message)) {
if (!isSegmentArray(message)) {
throw new MessageElementValidationError(
'INVALID_FIELD',
'message segment array entries must be objects with a non-empty string type',
undefined,
'message',
);
}
if (message.length === 0) throw invalidMessageShape('message segment array must not be empty');
const elements: MessageElement[] = [];
for (const seg of message) {
const data = segmentPayload(seg);
const elem = await segmentToElement(seg.type, data, options);
if (elem) elements.push(elem);
}
if (elements.length === 0) throw invalidMessageShape('message must contain at least one sendable segment');
return elements;
}
// Single segment object
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
const seg = message as unknown as MessageSegment;
if (seg.type) {
if (typeof seg.type === 'string' && seg.type.trim()) {
const data = segmentPayload(seg);
const elem = await segmentToElement(seg.type, data, options);
return elem ? [elem] : [];
if (elem) return [elem];
throw invalidMessageShape('message must contain at least one sendable segment');
}
throw new MessageElementValidationError(
'MISSING_FIELD',
'single message segment requires a non-empty string type',
undefined,
'type',
);
}
return [];
throw new MessageElementValidationError(
'INVALID_FIELD',
'message must be a string, a segment object, or a segment array',
undefined,
'message',
);
}
+228 -51
View File
@@ -1,13 +1,13 @@
import { createLogger } from '@snowluma/common/logger';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, QQEventVariant } from '@snowluma/protocol/events';
import type { ForwardNodePayload, FriendMessage, GroupMessage, MessageElement, MessageElementOf, QQEventVariant } from '@snowluma/protocol/events';
import { getVideoSourceSize, MAX_VIDEO_SIZE } from '@snowluma/protocol/highway/video-upload';
import type { MessageSendResult } from '../api-handler';
import { convertEvent, elementsToOneBotSegments, type ConverterContext } from '../event-converter';
import { segmentsToRawMessage } from '../helper/cq';
import type { OneBotInstanceContext } from '../instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import { parseMessage } from '../message-parser';
import { MessageElementValidationError, parseMessage } from '../message-parser';
import type { MessageStore } from '../message-store';
import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types';
@@ -41,14 +41,35 @@ export function videoNeedsFileFallback(element: MessageElement, isSizeErr: boole
* else is returned for a normal re-send.
*/
export function splitVideoFileFallback(
elements: MessageElement[],
elements: Array<Exclude<MessageElement, { type: 'file' }>>,
isSizeErr: boolean,
): { fileEls: MessageElement[]; remaining: MessageElement[] } {
const fileEls: MessageElement[] = [];
const remaining: MessageElement[] = [];
): {
fileEls: Array<MessageElementOf<'file'>>;
remaining: Array<Exclude<MessageElement, { type: 'file' }>>;
} {
const fileEls: Array<MessageElementOf<'file'>> = [];
const remaining: Array<Exclude<MessageElement, { type: 'file' }>> = [];
for (const e of elements) {
if (videoNeedsFileFallback(e, isSizeErr)) {
fileEls.push({ type: 'file', url: e.url, fileId: e.fileId, fileName: e.fileName || 'video.mp4' });
const fileElement: MessageElementOf<'file'> = {
type: 'file',
url: e.url,
fileId: e.fileId,
fileName: e.fileName || 'video.mp4',
fileSize: e.fileSize,
fileHash: e.fileHash,
md5Hex: e.md5Hex,
sha1Hex: e.sha1Hex,
};
if (!fileElement.url && !fileElement.fileId) {
throw new MessageElementValidationError(
'MISSING_FIELD',
'oversized video fallback requires a file/url source; a fingerprint alone cannot enter the file upload pipeline',
'video',
'url',
);
}
fileEls.push(fileElement);
} else {
remaining.push(e);
}
@@ -597,29 +618,38 @@ export async function sendPrivateMessage(
});
if (elements.length === 0) throw new Error('message is empty');
// Private chats cannot @-mention anyone — QQ simply ignores the mention
// element in c2c messages. Many OneBot callers blindly append an `at`
// segment right after `reply` (the group-chat convention), which ends up
// producing a broken wire message. Strip `at` elements so they never
// reach the protocol layer.
const hasReply = elements.some(e => e.type === 'reply');
for (let i = elements.length - 1; i >= 0; i--) {
if (elements[i].type === 'at') {
if (!hasReply) {
log.warn('[OneBot] at segment in private message is unsupported — stripped');
}
elements.splice(i, 1);
// Private chats cannot @-mention anyone. Reject the whole request rather
// than deleting the at and sending a different message than the caller gave.
const hasAt = elements.some(e => e.type === 'at');
if (hasAt) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'message element "at" cannot be sent in a private chat',
'at',
);
}
// Temp sessions only have the message-element transport. File elements use
// the friend c2c upload path, so reject them before sending any preceding
// text/media batch; discovering this after sendText would create a partial
// send followed by a failed Action response.
if (tempGroupId !== undefined) {
const unsupported = elements.find((element) =>
element.type === 'file' || videoNeedsFileFallback(element, false));
if (unsupported) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
`message element "${unsupported.type}" cannot be sent in a temp session`,
unsupported.type,
);
}
}
if (elements.length === 0) throw new Error('message is empty');
// C2C `{type:'file'}` segments can't ride on the elems[] pipeline —
// c2c files live on `RichText.notOnlineFile`, parallel to elems
// (see `@snowluma/proto-defs/message:notOnlineFile`). The element-builder
// explicitly drops them with a warn ("file send via elems[] is
// group-only"), so a private message that bundled a file alongside
// anything else used to either ship as "[空消息]" (only-file case,
// 0 elements after drop) or silently lose the file (mixed case).
// rejects them as a routing error. Split them before invoking the element
// builder so they enter the dedicated c2c-file pipeline.
//
// NapCat splits the same way (`dev/NapCatQQ/.../SendMsg.ts:404-415`):
// FILE / VIDEO / ARK / PTT each go in their own sendMsg call,
@@ -631,6 +661,14 @@ export async function sendPrivateMessage(
// b) has file_id from a prior upload_private_file → sendC2cFile() only
let allFileElements = elements.filter(e => e.type === 'file');
let nonFileElements = elements.filter(e => e.type !== 'file');
let fileTargetUid: string | null = null;
const ensureFileTargetUid = async (): Promise<string> => {
if (fileTargetUid) return fileTargetUid;
const resolved = await ref.bridge.resolveUserUid(userId);
if (!resolved) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
fileTargetUid = resolved;
return resolved;
};
// [#145] Videos up to MAX_VIDEO_SIZE (1.5 GiB) send as real videos; only
// above that do we route to the file pipeline (the whole video is buffered
@@ -646,6 +684,12 @@ export async function sendPrivateMessage(
}
}
// Resolve every deterministic prerequisite for the dedicated file path
// before sending a preceding text/media batch. Otherwise a mixed
// `[text, file]` request could publish the text and only then discover that
// the recipient UID required by RichText.notOnlineFile is unavailable.
if (allFileElements.length > 0) await ensureFileTargetUid();
// Route text/media batches through the temp-session primitive when replying
// passively, else the normal friend c2c path.
const sendText = (elems: MessageElement[]) =>
@@ -671,6 +715,7 @@ export async function sendPrivateMessage(
const { fileEls, remaining } = splitVideoFileFallback(nonFileElements, isSizeErr);
allFileElements = [...allFileElements, ...fileEls];
nonFileElements = remaining;
if (fileEls.length > 0) await ensureFileTargetUid();
if (nonFileElements.length > 0) {
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
logSentMessage(false, userId, nonFileElements);
@@ -679,10 +724,9 @@ export async function sendPrivateMessage(
}
if (allFileElements.length > 0) {
if (tempGroupId !== undefined) {
throw new Error('temp-session reply does not support file or oversized-video segments');
throw new Error('temp-session file preflight invariant failed');
}
const userUid = await ref.bridge.resolveUserUid(userId);
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
const userUid = await ensureFileTargetUid();
for (const fileEl of allFileElements) {
if (fileEl.url && !fileEl.fileId) {
// uploadPrivate() already calls sendC2cFile() internally — do NOT call it again.
@@ -701,7 +745,11 @@ export async function sendPrivateMessage(
lastReceipt = await ref.bridge.apis.message.sendC2cFile(userId, userUid, { fileId: fileEl.fileId, fileName, fileSize, fileMd5, fileHash });
logSentMessage(false, userId, [fileEl]);
} else {
log.warn('[OneBot] private file segment without file_id or url — skipped');
throw new MessageElementValidationError(
'MISSING_FIELD',
'private file segment requires file_id or url',
'file',
);
}
}
}
@@ -787,12 +835,16 @@ export async function sendGroupMessage(
const name = fileEl.fileName || fileEl.url.split('/').pop() || 'file';
const result = await ref.bridge.apis.groupFile.upload(groupId, fileEl.url, name, '/', true);
fileId = result.fileId ?? '';
if (!fileId) { log.warn('[OneBot] group file auto-upload returned no file_id — skipped'); continue; }
if (!fileId) throw new Error('group file auto-upload returned no file_id');
} else if (fileEl.fileId) {
fileId = fileEl.fileId;
await ref.bridge.apis.groupFile.publish(groupId, fileId);
} else {
log.warn('[OneBot] group file segment without file_id or url — skipped');
throw new MessageElementValidationError(
'MISSING_FIELD',
'group file segment requires file_id or url',
'file',
);
continue;
}
logSentMessage(true, groupId, [fileEl]);
@@ -1143,10 +1195,9 @@ interface ParseForwardOptions {
/**
* Are all entries of this array `{type:'node'}` segments? Then `content`
* itself is a nested forward chain (vs a regular flat segment list).
* Mixed content (some nodes + some text/image) returns false: that's
* not a meaningful protocol shape, so we treat it as flat-segment and
* let the node entries fall through to parseMessage (which drops them
* with a warning).
* Mixed content (some nodes + some text/image) returns false: that's not a
* meaningful nested-forward shape, so the regular strict parser rejects the
* embedded node before any upload starts.
*/
function isNestedNodeArray(value: JsonValue): boolean {
if (!Array.isArray(value) || value.length === 0) return false;
@@ -1157,6 +1208,25 @@ function isNestedNodeArray(value: JsonValue): boolean {
return true;
}
function assertForwardNodeMetadataIsScalar(
nodeData: JsonObject,
index: number,
): void {
for (const [field, value] of Object.entries(nodeData)) {
if (field === 'content' || field === 'message') continue;
if (
value === undefined || value === null || typeof value === 'string'
|| typeof value === 'number' || typeof value === 'boolean'
) continue;
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}].${field} must be a scalar value`,
'node',
field,
);
}
}
async function parseForwardNodes(
ref: OneBotInstanceContext,
messages: JsonValue,
@@ -1164,38 +1234,121 @@ async function parseForwardNodes(
): Promise<ForwardNodePayload[]> {
const depth = options.depth ?? 0;
if (depth >= MAX_FORWARD_DEPTH) {
throw new Error(`forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`);
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward nesting depth exceeds ${MAX_FORWARD_DEPTH}`,
'node',
'content',
);
}
if (!Array.isArray(messages)) {
throw new Error('forward messages must be an array');
throw new MessageElementValidationError(
'INVALID_FIELD',
'forward messages must be an array of node segments',
'node',
'messages',
);
}
if (messages.length === 0) {
throw new MessageElementValidationError(
'MISSING_FIELD',
'forward messages must contain at least one node',
'node',
'messages',
);
}
const nodes: ForwardNodePayload[] = [];
for (const item of messages) {
// Validate the entire top-level node list before parsing any content. The
// old loop silently continued past malformed/unknown entries, so a forward
// Action could upload the remaining nodes and report success with altered
// caller intent.
const prepared = messages.map((item, index) => {
const segment = asJsonObject(item);
if (!segment) continue;
let nodeData: JsonObject | null = null;
if (String(segment.type ?? '') === 'node') {
nodeData = asJsonObject(segment.data);
} else if (segment.content !== undefined || segment.message !== undefined) {
nodeData = segment;
if (!segment) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}] must be an object`,
'node',
`messages[${index}]`,
);
}
const rawType = segment.type;
if (rawType !== undefined && typeof rawType !== 'string') {
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}].type must be "node"`,
'node',
'type',
);
}
if (typeof rawType === 'string' && rawType !== 'node') {
throw new MessageElementValidationError(
'UNKNOWN_TYPE',
`unknown forward message segment type: ${rawType}`,
rawType,
'type',
);
}
if (!nodeData) continue;
const messageId = toPositiveInt(nodeData.id ?? nodeData.message_id);
if (messageId > 0) {
if (rawType === 'node') {
const nodeData = asJsonObject(segment.data);
if (!nodeData) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward messages[${index}].data must be an object`,
'node',
'data',
);
}
assertForwardNodeMetadataIsScalar(nodeData, index);
return { segment, nodeData };
}
// Preserve the existing bare-node compatibility form, but require it to
// carry content explicitly instead of silently ignoring arbitrary objects.
if (segment.content === undefined && segment.message === undefined) {
throw new MessageElementValidationError(
'MISSING_FIELD',
`forward messages[${index}] requires type:"node" data or bare content/message`,
'node',
'content',
);
}
assertForwardNodeMetadataIsScalar(segment, index);
return { segment, nodeData: segment };
});
const nodes: ForwardNodePayload[] = [];
for (const { nodeData } of prepared) {
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
if (messageId !== 0) {
const event = ref.messageStore.findEvent(messageId);
if (!event) throw new Error(`forward node message_id not found: ${messageId}`);
if (!event) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward node message_id not found: ${String(messageId)}`,
'node',
'message_id',
);
}
const eventSender = asJsonObject(event.sender) ?? {};
const senderCard = eventSender.card !== undefined ? String(eventSender.card) : undefined;
const nickname = String(eventSender.card ?? eventSender.nickname ?? nodeData.nickname ?? nodeData.name ?? '');
const userUin = toPositiveInt(event.user_id);
if (userUin <= 0) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`forward node message_id ${String(messageId)} has no valid sender user_id`,
'node',
'user_id',
);
}
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
const elements = await parseMessage(content, false);
if (userUin > 0 && elements.length > 0) {
if (elements.length > 0) {
const messageType = event.message_type === 'group' ? 'group' : 'private';
const groupIdValue = toPositiveInt(event.group_id);
nodes.push({
@@ -1203,7 +1356,7 @@ async function parseForwardNodes(
nickname: nickname || String(userUin),
elements,
time: typeof event.time === 'number' ? event.time : toPositiveInt(event.time),
msgId: toPositiveInt(event.message_id),
msgId: toSafeSignedInteger(event.message_id),
msgSeq: toPositiveInt(event.message_seq),
groupId: groupIdValue > 0 ? groupIdValue : undefined,
senderCard,
@@ -1371,3 +1524,27 @@ function toPositiveInt(value: JsonValue | undefined): number {
}
return 0;
}
function toSafeSignedInteger(value: JsonValue | undefined): number {
if (typeof value === 'number' && Number.isSafeInteger(value)) return value;
if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) {
const parsed = Number(value.trim());
if (Number.isSafeInteger(parsed)) return parsed;
}
return 0;
}
function parseForwardMessageId(value: JsonValue | undefined): number {
if (value === undefined || value === null || value === '') return 0;
if (typeof value === 'number' && Number.isSafeInteger(value)) return value;
if (typeof value === 'string' && /^-?\d+$/.test(value.trim())) {
const parsed = Number(value.trim());
if (Number.isSafeInteger(parsed)) return parsed;
}
throw new MessageElementValidationError(
'INVALID_FIELD',
'forward node id/message_id must be a non-zero safe integer',
'node',
'message_id',
);
}
@@ -5,6 +5,7 @@
// from blowing the line width.
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { OidbError } from '@snowluma/protocol/oidb-service';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { summarizeParams } from '@snowluma/common/log-summary';
@@ -120,6 +121,25 @@ describe('ApiHandler dispatch logging', () => {
expect(result).toMatchObject({ status: 'failed', retcode: 100, wording: 'permission denied' });
});
it('maps typed outbound message-contract failures to BAD_REQUEST', async () => {
const handler = createCompiledTestHandler(emptyContext(), [
testAction('bad_message', async () => {
throw new MessageElementValidationError(
'UNKNOWN_TYPE',
'unknown message segment type: surprise',
'surprise',
);
}),
], 12345);
const result = await handler.handle('bad_message', {});
expect(result).toMatchObject({
status: 'failed',
retcode: 1400,
wording: 'unknown message segment type: surprise',
});
});
it('surfaces the OidbError code + server message through error.message (no special-casing)', async () => {
const handler = createCompiledTestHandler(emptyContext(), [
testAction('oidb_boom', async () => { throw new OidbError(34, 'no permission', 0x11ec, 2); }),
+11 -2
View File
@@ -34,8 +34,8 @@ describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', ()
expect(codecTypesWith('fromSegment')).toEqual(sorted(typesForDirection('P')));
});
it('输入糖仍由 message-parser 前置处理,未被静默丢弃', () => {
// 输入糖(骰子/分享/…)不进 codec 表,留在 message-parser 当前置 normalize。
it('OneBot 输入词仍由 message-parser 前置处理或明确拒绝,未被静默丢弃', () => {
// 输入词(骰子/分享/node/anonymous/…)不进 codec 表,留在 parser 前置处理。
// 用源码扫描锁住它们确实存在,防止将来重构时被悄悄删掉。
const abs = fileURLToPath(new URL('../src/message-parser.ts', import.meta.url));
const src = readFileSync(abs, 'utf8')
@@ -51,4 +51,13 @@ describe('element-manifest 对账(onebot 侧:S 收·转 / P 发·解)', ()
const realLeftInParser = [...cases].filter((t) => !INPUT_SUGAR_SEGMENTS.has(t));
expect(realLeftInParser).toEqual([]);
});
it('poke 的 P/S 字段都使用 subType,不再漂移到 faceId', async () => {
const parsed = await ELEMENT_CODECS.poke!.fromSegment!({ type: 7 });
expect(parsed).toEqual({ type: 'poke', subType: 7 });
expect(parsed).not.toHaveProperty('faceId');
const segment = await ELEMENT_CODECS.poke!.toSegment!(parsed!, {} as never);
expect(segment).toEqual({ type: 'poke', data: { type: 7 } });
});
});
@@ -383,6 +383,19 @@ describe('convertEvent — message elements (13 segment types)', () => {
});
});
it('image: preserves the flash marker on the OneBot segment', async () => {
const seg = await segment({
type: 'image',
fileId: 'fid',
imageUrl: 'http://x',
flash: true,
});
expect(seg).toMatchObject({
type: 'image',
data: { type: 'flash' },
});
});
it('at: targetUin -> qq string', async () => {
const seg = await segment({ type: 'at', targetUin: PEER_UIN });
expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } });
+141 -12
View File
@@ -209,14 +209,144 @@ describe('forward — nested {type:"node"} content', () => {
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
});
it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => {
it('rejects an unknown top-level entry before uploading valid siblings', async () => {
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
const messages = [
{
type: 'node',
data: {
user_id: 111,
nickname: 'valid',
content: [{ type: 'text', data: { text: 'must not upload' } }],
},
},
{ type: 'surprise', data: { content: 'silently dropped before' } },
];
await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({
code: 'UNKNOWN_TYPE',
elementType: 'surprise',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
it('rejects object-valued node metadata before uploading', async () => {
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
await expect(sendGroupForwardMessage(ctx, 12345, [{
type: 'node',
data: {
user_id: { accidental: 111 },
nickname: 'invalid',
content: [{ type: 'text', data: { text: 'must not upload' } }],
},
}] as any)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'node',
field: 'user_id',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
it('rejects a cached message node with no valid sender instead of dropping it', async () => {
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = {
findEvent: () => ({
user_id: 0,
message_type: 'group',
message: [{ type: 'text', data: { text: 'cached' } }],
sender: { nickname: 'missing-id' },
}),
};
await expect(sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: 7 } },
{ type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'sibling' } }] } },
] as any)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'node',
field: 'user_id',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
it('resolves a cached node by a signed negative OneBot message_id', async () => {
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 1, clientSequence: 0, random: 1, timestamp: 1,
}));
const findEvent = vi.fn((id: number) => id === -123 ? ({
user_id: 111,
message_id: -123,
message_seq: 42,
message_type: 'group',
group_id: 12345,
time: 1700000000,
message: [{ type: 'text', data: { text: 'cached negative id' } }],
sender: { nickname: 'alice' },
}) : null);
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
(ctx as any).messageStore = { findEvent };
await sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: -123 } },
] as any);
expect(findEvent).toHaveBeenCalledWith(-123);
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])[0]).toMatchObject({
userUin: 111,
msgId: -123,
elements: [{ type: 'text', text: 'cached negative id' }],
});
});
it('reports a missing cached message_id as caller-invalid before upload', async () => {
const uploadForwardNodes = vi.fn(async () => 'RES');
const sendGroupMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } },
} as any);
const ctx = makeCtx(bridge);
await expect(sendGroupForwardMessage(ctx, 12345, [
{ type: 'node', data: { id: -404 } },
] as any)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'node',
field: 'message_id',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
it('rejects mixed node/non-node content instead of partially dropping the node', async () => {
// Recursion only kicks in when *all* content entries are nodes —
// mixed content is ambiguous (do the non-node parts belong to the
// outer node or are they parallel siblings?), so we keep the legacy
// behaviour and let parseMessage handle it. Non-node parts come
// through, node parts get parsed via `case 'node':` and then
// dropped by element-builder. A user who wants nested forward
// should pass a pure node list.
// behaviour is ambiguous, so reject it before upload. A user who wants a
// nested forward must pass a pure node list.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
@@ -235,13 +365,12 @@ describe('forward — nested {type:"node"} content', () => {
},
}];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
// Only the text element survives — the legacy "node MessageElement"
// that parseMessage produces is opaque to the element-builder.
const [nodes] = uploadForwardNodes.mock.calls[0]!;
const elements = (nodes as any[])[0]!.elements;
expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true);
await expect(sendGroupForwardMessage(ctx, 12345, messages as any)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'node',
});
expect(uploadForwardNodes).not.toHaveBeenCalled();
expect(sendGroupMessage).not.toHaveBeenCalled();
});
it('[#203] node with user_id "0" or missing falls back to the bot self_id', async () => {
@@ -0,0 +1,73 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import type { OneBotInstanceContext } from '../src/instance-context';
import { sendGroupMessage } from '../src/modules/message-actions';
function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceContext {
const bridge = {
apis: { message: { sendGroup } },
resolveUserUid: vi.fn(async () => 'u_peer'),
} as unknown as BridgeInterface;
return {
uin: '10001',
selfId: 10001,
bridge,
messageStore: {
resolveReplySequence: () => 0,
findEvent: () => null,
findMeta: () => null,
} as never,
cacheMessageMeta: vi.fn(),
mediaStore: {} as never,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
describe('outbound message validation at the Action boundary', () => {
it('returns BAD_REQUEST and performs no send when a later segment is unknown', async () => {
const bridgeSend = vi.fn();
const ref = instanceContext(bridgeSend);
const api = new ApiHandler({
sendGroupMessage: (groupId, message, autoEscape) =>
sendGroupMessage(ref, groupId, message, autoEscape),
} as ApiActionContext);
const response = await api.handle('send_group_msg', {
group_id: 12345,
message: [
{ type: 'text', data: { text: 'must not be sent' } },
{ type: 'unknown_late_segment', data: {} },
],
});
expect(response).toMatchObject({
status: 'failed',
retcode: 1400,
wording: expect.stringContaining('unknown message segment type'),
});
expect(bridgeSend).not.toHaveBeenCalled();
});
it('returns BAD_REQUEST and performs no send for malformed JSON cards', async () => {
const bridgeSend = vi.fn();
const ref = instanceContext(bridgeSend);
const api = new ApiHandler({
sendGroupMessage: (groupId, message, autoEscape) =>
sendGroupMessage(ref, groupId, message, autoEscape),
} as ApiActionContext);
const response = await api.handle('send_group_msg', {
group_id: 12345,
message: [{ type: 'json', data: { data: 'not-json' } }],
});
expect(response).toMatchObject({
status: 'failed',
retcode: 1400,
wording: expect.stringContaining('must contain a JSON object'),
});
expect(bridgeSend).not.toHaveBeenCalled();
});
});
+203 -55
View File
@@ -3,7 +3,7 @@ import os from 'os';
import path from 'path';
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { parseMessage } from '../src/message-parser';
import { MessageElementValidationError, parseMessage } from '../src/message-parser';
import { buildSendElems } from '@snowluma/protocol/element-builder';
import type { MentionExtraSend } from '@snowluma/proto-defs/action';
import type { MarketFacePbReserve } from '@snowluma/proto-defs/element';
@@ -17,9 +17,12 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'text', text: 'hello world' }]);
});
it('returns empty for empty string', async () => {
const result = await parseMessage('', false);
expect(result).toEqual([]);
it('rejects an empty string', async () => {
await expect(parseMessage('', false)).rejects.toMatchObject({
name: 'MessageElementValidationError',
code: 'MISSING_FIELD',
field: 'message',
});
});
it('autoEscape treats CQ codes as text', async () => {
@@ -62,6 +65,21 @@ describe('parseMessage', () => {
const result = await parseMessage('a&amp;b&#91;c&#93;d', false);
expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]);
});
it('recognizes underscored CQ types and rejects receive-only flash_file', async () => {
await expect(parseMessage('[CQ:flash_file,file_set_id=x]', false)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'flash_file',
message: expect.stringContaining('send_flash_msg'),
});
});
it('does not send an unknown underscored CQ code as literal text', async () => {
await expect(parseMessage('[CQ:unknown_segment]', false)).rejects.toMatchObject({
code: 'UNKNOWN_TYPE',
elementType: 'unknown_segment',
});
});
});
describe('JSON segment array', () => {
@@ -73,6 +91,25 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'text', text: 'hello' }]);
});
it('rejects object-valued fields instead of stringifying caller input', async () => {
await expect(parseMessage(
[{ type: 'text', data: { text: { bad: true } } }] as any,
false,
)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'text',
field: 'text',
});
await expect(parseMessage(
[{ type: 'json', data: { data: { app: 'unexpected-object' } } }] as any,
false,
)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'json',
field: 'data',
});
});
it('parses face segment', async () => {
const result = await parseMessage(
[{ type: 'face', data: { id: 123 } }] as any,
@@ -83,6 +120,21 @@ describe('parseMessage', () => {
expect(result[0].faceId).toBe(123);
});
it('rejects numeric fields with suffix garbage or fractional values', async () => {
await expect(parseMessage(
[{ type: 'at', data: { qq: '123abc' } }] as any,
false,
)).rejects.toMatchObject({ code: 'INVALID_FIELD' });
await expect(parseMessage(
[{ type: 'reply', data: { id: '456junk' } }] as any,
false,
)).rejects.toMatchObject({ code: 'INVALID_FIELD' });
await expect(parseMessage(
[{ type: 'face', data: { id: 1.9 } }] as any,
false,
)).rejects.toMatchObject({ code: 'INVALID_FIELD' });
});
it('parses image segment', async () => {
const result = await parseMessage(
[{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any,
@@ -111,6 +163,7 @@ describe('parseMessage', () => {
);
expect(result[0].type).toBe('image');
expect(result[0].url).toBe('https://multimedia.nt.qq.com.cn/download?fileid=abc&rkey=xyz');
expect(result[0].subType).toBe(1);
});
it('keeps file when it is itself loadable even if a url is also present', async () => {
@@ -167,12 +220,15 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]);
});
it('drops video segment with empty source', async () => {
const result = await parseMessage(
it('rejects a video segment with an empty source', async () => {
await expect(parseMessage(
[{ type: 'video', data: {} }] as any,
false,
);
expect(result).toEqual([]);
)).rejects.toMatchObject({
name: 'MessageElementValidationError',
code: 'MISSING_FIELD',
elementType: 'video',
});
});
it('parses record segment from data.path (NapCat parity)', async () => {
@@ -183,12 +239,15 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'record', url: 'C:\\voices\\hi.silk' }]);
});
it('drops record segment with empty source', async () => {
const result = await parseMessage(
it('rejects a record segment with an empty source', async () => {
await expect(parseMessage(
[{ type: 'record', data: {} }] as any,
false,
);
expect(result).toEqual([]);
)).rejects.toMatchObject({
name: 'MessageElementValidationError',
code: 'MISSING_FIELD',
elementType: 'record',
});
});
it('parses at segment', async () => {
@@ -248,11 +307,7 @@ describe('parseMessage', () => {
expect(protoElems[0].text?.str).toBe('@User ');
});
it('skips record send when SendContext is absent (graceful no-bridge path)', async () => {
// Without a SendContext, buildSendElems can't run highway upload —
// it should warn and drop the element instead of throwing into the
// ffmpegAddon (which would explode for callers that don't actually
// need to send).
it('rejects the whole message when record SendContext is absent', async () => {
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
@@ -260,13 +315,10 @@ describe('parseMessage', () => {
] as any,
false,
);
const protoElems = await buildSendElems(elements);
// Only the leading text should make it through.
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
await expect(buildSendElems(elements)).rejects.toBeInstanceOf(MessageElementValidationError);
});
it('skips video send when SendContext is absent (graceful no-bridge path)', async () => {
it('rejects the whole message when video SendContext is absent', async () => {
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
@@ -274,9 +326,7 @@ describe('parseMessage', () => {
] as any,
false,
);
const protoElems = await buildSendElems(elements);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
await expect(buildSendElems(elements)).rejects.toBeInstanceOf(MessageElementValidationError);
});
it('builds video commonElem through NTV2 fast-upload response', async () => {
@@ -357,16 +407,18 @@ describe('parseMessage', () => {
expect(result[2].type).toBe('text');
});
it('skips unknown segment types', async () => {
const result = await parseMessage(
it('rejects the whole message when one segment type is unknown', async () => {
await expect(parseMessage(
[
{ type: 'text', data: { text: 'ok' } },
{ type: 'unknown_type_xyz', data: {} },
] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('text');
)).rejects.toMatchObject({
name: 'MessageElementValidationError',
code: 'UNKNOWN_TYPE',
elementType: 'unknown_type_xyz',
});
});
});
@@ -409,12 +461,22 @@ describe('parseMessage', () => {
expect((result[0] as any).emojiId).toBeUndefined();
});
it('drops an mface segment without emoji_id', async () => {
const result = await parseMessage(
it('rejects an mface segment without emoji_id', async () => {
await expect(parseMessage(
[{ type: 'mface', data: { emoji_package_id: 12, summary: 'x' } }] as any,
false,
);
expect(result).toEqual([]);
)).rejects.toMatchObject({ code: 'MISSING_FIELD', elementType: 'mface' });
});
it('rejects a non-hex market-face GUID before wire encoding', async () => {
await expect(parseMessage(
[{ type: 'mface', data: { emoji_id: 'zz', summary: 'broken' } }] as any,
false,
)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'mface',
field: 'emojiId',
});
});
it('builds the wire marketFace element (faceId = hex(emoji_id), NapCat constants)', async () => {
@@ -447,6 +509,32 @@ describe('parseMessage', () => {
expect(result[0].text).toBe('{"app":"test"}');
});
it('reads canonical xml resid and file_size fields', async () => {
const xml = await parseMessage(
[{ type: 'xml', data: { data: '<msg/>', resid: '35' } }] as any,
false,
);
expect(xml).toEqual([{ type: 'xml', text: '<msg/>', subType: 35 }]);
const file = await parseMessage(
[{ type: 'file', data: { file_id: 'fid', file_size: '4096' } }] as any,
false,
);
expect(file).toEqual([{ type: 'file', fileId: 'fid', fileSize: 4096 }]);
await expect(parseMessage([{
type: 'file',
data: { file: 'report.pdf', url: 'https://example.com/report.pdf' },
}] as any, false)).resolves.toEqual([{
type: 'file',
url: 'https://example.com/report.pdf',
}]);
await expect(parseMessage('[CQ:file,id=fid-from-raw]', false)).resolves.toEqual([
{ type: 'file', fileId: 'fid-from-raw' },
]);
});
it('parses reply segment with resolveReplySequence', async () => {
const result = await parseMessage(
[{ type: 'reply', data: { id: 42 } }] as any,
@@ -471,6 +559,29 @@ describe('parseMessage', () => {
expect(parsed.meta.news.title).toBe('Test');
});
it('rejects malformed rich input sugar before resolver or signer side effects', async () => {
const resolveContactArk = vi.fn();
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
try {
await expect(parseMessage([{ type: 'share', data: {} }] as any, false))
.rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'share' });
await expect(parseMessage([{ type: 'location', data: { lat: '', lon: '181' } }] as any, false))
.rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'location' });
await expect(parseMessage(
[{ type: 'contact', data: { type: 'channel', id: '123' } }] as any,
false,
{ resolveContactArk },
)).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'contact' });
await expect(parseMessage([{ type: 'music', data: { type: '163' } }] as any, false))
.rejects.toMatchObject({ code: 'MISSING_FIELD', elementType: 'music' });
} finally {
vi.unstubAllGlobals();
}
expect(resolveContactArk).not.toHaveBeenCalled();
expect(fetchMock).not.toHaveBeenCalled();
});
it('parses rps as face', async () => {
const result = await parseMessage(
[{ type: 'rps', data: {} }] as any,
@@ -491,25 +602,36 @@ describe('parseMessage', () => {
expect(result[0].faceId).toBe(358);
});
it('parses shake as poke', async () => {
const result = await parseMessage(
it('rejects shake/poke with a dedicated-Action hint', async () => {
await expect(parseMessage(
[{ type: 'shake', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('poke');
)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'poke',
message: expect.stringContaining('dedicated poke Action'),
});
await expect(parseMessage(
[{ type: 'poke', data: { type: 7 } }] as any,
false,
)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'poke',
});
});
it('ignores anonymous segment', async () => {
const result = await parseMessage(
it('rejects anonymous because it has no executable send semantics', async () => {
await expect(parseMessage(
[
{ type: 'anonymous', data: {} },
{ type: 'text', data: { text: 'hi' } },
] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('text');
)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'anonymous',
});
});
it('parses location as json card', async () => {
@@ -576,14 +698,20 @@ describe('parseMessage', () => {
});
describe('edge cases', () => {
it('returns empty for null', async () => {
const result = await parseMessage(null as any, false);
expect(result).toEqual([]);
it('rejects null', async () => {
await expect(parseMessage(null as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD' });
});
it('returns empty for number', async () => {
const result = await parseMessage(42 as any, false);
expect(result).toEqual([]);
it('rejects a number', async () => {
await expect(parseMessage(42 as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD' });
});
it('rejects an empty segment array and an object without type', async () => {
await expect(parseMessage([] as any, false)).rejects.toMatchObject({ code: 'MISSING_FIELD' });
await expect(parseMessage({ data: { text: 'x' } } as any, false)).rejects.toMatchObject({
code: 'MISSING_FIELD',
field: 'type',
});
});
});
@@ -615,24 +743,44 @@ describe('parseMessage', () => {
expect(result).toEqual([{ type: 'file', url: '/local/path/a.bin' }]);
});
it('drops a file segment with neither file_id nor file/url', async () => {
it('does not let an empty file field mask a valid url', async () => {
const result = await parseMessage(
[{ type: 'file', data: {} } as any],
[{ type: 'file', data: { file: '', url: 'https://example.com/a.bin' } } as any],
false,
);
expect(result).toEqual([]);
expect(result).toEqual([{ type: 'file', url: 'https://example.com/a.bin' }]);
});
it('rejects a file segment with neither file_id nor file/url', async () => {
await expect(parseMessage(
[{ type: 'file', data: {} } as any],
false,
)).rejects.toMatchObject({ code: 'MISSING_FIELD', elementType: 'file' });
});
it('accepts fileId / filename / fileName / md5 / sha1 aliases', async () => {
const result = await parseMessage(
[{
type: 'file',
data: { fileId: 'fid-2', filename: 'b.zip', fileSize: 456, md5: 'AB', sha1: 'CD' },
data: {
fileId: 'fid-2',
filename: 'b.zip',
fileSize: 456,
md5: 'ab'.repeat(16),
sha1: 'cd'.repeat(20),
},
} as any],
false,
);
expect(result).toEqual([
{ type: 'file', fileId: 'fid-2', fileName: 'b.zip', fileSize: 456, md5Hex: 'AB', sha1Hex: 'CD' },
{
type: 'file',
fileId: 'fid-2',
fileName: 'b.zip',
fileSize: 456,
md5Hex: 'ab'.repeat(16),
sha1Hex: 'cd'.repeat(20),
},
]);
});
});
@@ -104,7 +104,7 @@ describe('send_group_msg with {type:"file"} segment', () => {
expect(fileFileId).toBe('gfid-xyz');
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
it('rejects the whole message when a file segment has neither file_id nor url', async () => {
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn();
const upload = vi.fn();
@@ -117,12 +117,15 @@ describe('send_group_msg with {type:"file"} segment', () => {
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
await expect(sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id and no url
] as any, false);
] as any, false)).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'file',
});
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
expect(publish).not.toHaveBeenCalled();
expect(upload).not.toHaveBeenCalled();
});
@@ -3,8 +3,7 @@
// Symptom in the wild: bot called `send_private_msg` with a
// `{type:'file', file_id}` segment; the OneBot module passed it
// straight to `bridge.sendPrivateMessage(userId, [fileElement])`;
// `buildSendElems` warned ("file send via elems[] is group-only")
// and dropped it; the resulting wire send had 0 elems and the chat
// `buildSendElems` used to warn and drop it; the resulting wire send had 0 elems and the chat
// rendered "[空消息]".
//
// Fix: c2c file segments are split out at the OneBot layer in
@@ -60,7 +59,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
await sendPrivateMessage(ctx, 67890, [{
type: 'file',
data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233' },
data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233445566778899aabbccddeeff' },
}] as any, false);
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
@@ -74,8 +73,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
fileName: 'doc.txt',
fileSize: 123,
});
// md5 decoded from hex (4 bytes for '00112233')
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
expect(info.fileMd5).toEqual(Buffer.from('00112233445566778899aabbccddeeff', 'hex'));
});
it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => {
@@ -142,7 +140,13 @@ describe('send_private_msg with {type:"file"} segment', () => {
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' },
type: 'file', data: {
file_id: 'uuid-x',
name: 'inline.txt',
size: 200,
md5: '11223344556677889900aabbccddeeff',
file_hash: 'inline-hash',
},
}] as any, false);
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
@@ -151,7 +155,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
fileSize: 200,
fileHash: 'inline-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex'));
expect(info.fileMd5).toEqual(Buffer.from('11223344556677889900aabbccddeeff', 'hex'));
});
it('mixed file + text splits across two sends (text first, file second)', async () => {
@@ -185,10 +189,7 @@ describe('send_private_msg with {type:"file"} segment', () => {
expect(fileInfo).toMatchObject({ fileId: 'uuid-xyz', fileName: 'pkg.zip' });
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// OneBot11 file segments are upload-by-reference — without a
// file_id there's nothing to send. Previously these slipped
// through to the elems[] path and shipped empty messages.
it('rejects the whole message when a file segment has neither file_id nor url', async () => {
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
@@ -198,13 +199,15 @@ describe('send_private_msg with {type:"file"} segment', () => {
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
] as any, false);
] as any, false)).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'file',
});
// Text still went out, file dropped (no c2c file call).
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
expect(sendPrivateMessage_bridge).not.toHaveBeenCalled();
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
@@ -228,6 +231,25 @@ describe('send_private_msg with {type:"file"} segment', () => {
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
it('does not send preceding text when a mixed file message cannot resolve uid', async () => {
const sendPrivateMessage_bridge = vi.fn(async () => goodReceipt);
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid: vi.fn(async () => ''),
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'must remain unsent' } },
{ type: 'file', data: { file_id: 'uuid-orphan', name: 'x.txt' } },
] as any, false)).rejects.toThrow(/could not resolve uid/);
expect(sendPrivateMessage_bridge).not.toHaveBeenCalled();
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
it('file segment with url (no file_id) auto-uploads via groupFile.uploadPrivate (not sendC2cFile)', async () => {
// uploadPrivate() internally calls sendC2cFile() — must NOT call it again.
const uploadPrivate = vi.fn(async (_uid: number, _src: string, _name: string, _doUpload: boolean) =>
@@ -7,11 +7,7 @@
// broken-looking wire message (the recipient sees a phantom "@QQ号"
// that can't be clicked).
//
// Fix: `sendPrivateMessage` now strips all `at` elements before
// handing the array to the protocol layer. When the message also
// contains a `reply` segment the strip is silent (it's the normal
// OneBot convention and the caller didn't do anything wrong); without
// a `reply` the strip still happens but a warn is logged.
// Fix: every private at is rejected before anything reaches the bridge.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
@@ -47,34 +43,26 @@ function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
} as unknown as OneBotInstanceContext;
}
describe('send_private_msg strips at segments', () => {
it('reply + at + text → only reply + text reach the wire', async () => {
const sendPrivate = vi.fn(async (_uin: number, elements: any[]) => {
// Verify no `at` element reaches the bridge
const types = elements.map((e: any) => e.type);
expect(types).not.toContain('at');
return goodReceipt;
});
describe('send_private_msg rejects at segments', () => {
it('reply + at + text rejects the whole message', async () => {
const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'reply', data: { id: '-2050237785' } },
{ type: 'at', data: { qq: '67890' } },
{ type: 'text', data: { text: ' ' } },
{ type: 'text', data: { text: 'quoted reply text' } },
] as any, false);
] as any, false)).rejects.toMatchObject({ code: 'UNSENDABLE_TYPE', elementType: 'at' });
expect(sendPrivate).toHaveBeenCalledOnce();
const sentElements = sendPrivate.mock.calls[0]![1] as any[];
const sentTypes = sentElements.map(e => e.type);
expect(sentTypes).toEqual(['reply', 'text', 'text']);
expect(sendPrivate).not.toHaveBeenCalled();
});
it('at-only message (no reply) is also stripped, throws "message is empty"', async () => {
it('at-only message (no reply) is rejected as unsendable', async () => {
const sendPrivate = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
@@ -84,12 +72,15 @@ describe('send_private_msg strips at segments', () => {
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'at', data: { qq: '67890' } },
] as any, false)).rejects.toThrow('message is empty');
] as any, false)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'at',
});
expect(sendPrivate).not.toHaveBeenCalled();
});
it('text + at (without reply) strips at and sends remaining text', async () => {
it('text + at (without reply) rejects the whole message', async () => {
const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
@@ -97,17 +88,15 @@ describe('send_private_msg strips at segments', () => {
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'hello' } },
{ type: 'at', data: { qq: '67890' } },
] as any, false);
] as any, false)).rejects.toMatchObject({ code: 'UNSENDABLE_TYPE', elementType: 'at' });
expect(sendPrivate).toHaveBeenCalledOnce();
const sentElements = sendPrivate.mock.calls[0]![1] as any[];
expect(sentElements).toEqual([{ type: 'text', text: 'hello' }]);
expect(sendPrivate).not.toHaveBeenCalled();
});
it('multiple at segments are all stripped', async () => {
it('multiple at segments reject the whole message', async () => {
const sendPrivate = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
apis: { message: { sendPrivate } } as any,
@@ -115,26 +104,21 @@ describe('send_private_msg strips at segments', () => {
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'reply', data: { id: '123' } },
{ type: 'at', data: { qq: '67890' } },
{ type: 'at', data: { qq: '12345' } },
{ type: 'text', data: { text: 'hi' } },
] as any, false);
] as any, false)).rejects.toMatchObject({ code: 'UNSENDABLE_TYPE', elementType: 'at' });
expect(sendPrivate).toHaveBeenCalledOnce();
const sentElements = sendPrivate.mock.calls[0]![1] as any[];
const sentTypes = sentElements.map((e: any) => e.type);
expect(sentTypes).not.toContain('at');
expect(sentTypes).toContain('reply');
expect(sentTypes).toContain('text');
expect(sendPrivate).not.toHaveBeenCalled();
});
it('group messages are NOT affected (at segments preserved)', async () => {
// Sanity: import sendGroupMessage and verify at segments pass through
const { sendGroupMessage } = await import('../src/modules/message-actions');
const sendGroup = vi.fn(async (_groupId: number, elements: any[]) => {
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => {
return goodReceipt;
});
const bridge = fakeBridge({
@@ -40,4 +40,21 @@ describe('sendPrivateMessage temp-session gate (passive-only)', () => {
sendPrivateMessage(ref, 1001, [{ type: 'text', data: { text: 'hi' } }], false, 700),
).rejects.toThrow(/passive-only|temp session/i);
});
it('rejects text + file before sending a partial temp-session message', async () => {
const store = new TempSessionStore();
store.record(1001, 700);
const ref = refWith(store);
await expect(sendPrivateMessage(ref, 1001, [
{ type: 'text', data: { text: 'must not be sent' } },
{ type: 'file', data: { file_id: 'friend-file-id' } },
], false, 700)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'file',
});
expect((ref.bridge.apis.message as { sendGroupTempMessage: ReturnType<typeof vi.fn> }).sendGroupTempMessage)
.not.toHaveBeenCalled();
});
});
+52 -40
View File
@@ -9,6 +9,10 @@ import { deflateSync } from 'zlib';
import type { BridgeContext } from './bridge-context';
import { sysFaceStore } from './sys-face-store';
import type { MessageElement } from './events';
import {
assertValidMessageElements,
MessageElementValidationError,
} from './element-manifest';
import { uploadImageMsgInfo } from './highway/image-upload';
import { hexToBytes } from './highway/pipeline';
import { uploadPttMsgInfo } from './highway/ptt-upload';
@@ -435,6 +439,27 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
*/
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
// Validate the whole message before the first upload or packet build. This
// preserves all-or-nothing semantics: a malformed later segment cannot make
// an earlier media segment perform side effects before the send is rejected.
assertValidMessageElements(elements, 'W');
for (const element of elements) {
if ((element.type === 'image' || element.type === 'record' || element.type === 'video') && !ctx) {
throw new MessageElementValidationError(
'MISSING_FIELD',
`message element "${element.type}" requires SendContext`,
element.type,
);
}
if (element.type === 'file' && !ctx?.forwardFake) {
throw new MessageElementValidationError(
'UNSENDABLE_TYPE',
'message element "file" must use the group/private file upload pipeline',
element.type,
);
}
}
const result: ProtoElem[] = [];
// A user-supplied @ that lands immediately after a reply's srcMsg isn't
// honored by the QQ NT group server (the @ shows but never notifies, #129).
@@ -446,15 +471,15 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
for (const elem of elements) {
switch (elem.type) {
case 'text':
if (elem.text) result.push(makeTextElem(elem.text));
result.push(makeTextElem(elem.text));
break;
case 'face':
if (elem.faceId !== undefined) result.push(makeFaceElem(elem.faceId, ctx));
result.push(makeFaceElem(elem.faceId, ctx));
break;
case 'mface':
if (elem.emojiId) result.push(makeMarketFaceElem(elem));
result.push(makeMarketFaceElem(elem));
break;
case 'at':
@@ -462,53 +487,39 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
break;
case 'reply':
if (elem.replySeq) {
result.push(makeReplyElem(elem));
if (hasUserAt && ctx?.groupId !== undefined && elem.replySenderUin) {
const replyMention = await makeReplyMentionElem(ctx, elem.replySenderUin);
if (replyMention) result.push(replyMention);
}
result.push(makeReplyElem(elem));
if (hasUserAt && ctx?.groupId !== undefined && elem.replySenderUin) {
const replyMention = await makeReplyMentionElem(ctx, elem.replySenderUin);
if (replyMention) result.push(replyMention);
}
break;
case 'json':
if (elem.text) result.push(makeJsonElem(elem));
result.push(makeJsonElem(elem));
break;
case 'xml':
if (elem.text) result.push(makeXmlElem(elem));
result.push(makeXmlElem(elem));
break;
case 'markdown':
if (elem.text) result.push(makeMarkdownElem(elem));
result.push(makeMarkdownElem(elem));
break;
case 'image':
if (ctx) {
result.push(await makeImageElem(ctx, elem));
} else {
console.warn('[ElemBuilder] image send requires SendContext');
}
result.push(await makeImageElem(ctx!, elem));
break;
case 'forward':
if (elem.resId) result.push(makeForwardElem(elem));
result.push(makeForwardElem(elem));
break;
case 'record':
if (ctx) {
result.push(await makePttElem(ctx, elem));
} else {
console.warn('[ElemBuilder] record send requires SendContext');
}
result.push(await makePttElem(ctx!, elem));
break;
case 'video':
if (ctx) {
result.push(await makeVideoElem(ctx, elem));
} else {
console.warn('[ElemBuilder] video send requires SendContext');
}
result.push(await makeVideoElem(ctx!, elem));
break;
case 'file':
@@ -523,8 +534,8 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
// * group: split → `bridge.sendGroupFileMessage`
// (OIDB 0x6d9_4 publish).
// The QQ-NT server REJECTS outgoing PbSendMsg with a
// transElem(24) (result=79), so an element reaching here
// in live-send mode is a routing bug — drop with a warn.
// transElem(24) (result=79), so the all-message preflight above
// raises a typed validation error when a live file reaches here.
//
// 2. FORWARD-FAKE upload (long-msg) — `ctx.forwardFake===true`.
// The long-msg service stores the gzipped protobuf verbatim
@@ -536,20 +547,21 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
// the file segment off and writes msgContent
// separately (because RichText.notOnlineFile +
// FileExtra both live outside elems[]).
if (ctx && ctx.forwardFake) {
if (ctx.groupId !== undefined) {
result.push(makeGroupFileElem(elem, ctx));
}
// c2c forwardFake intentionally falls through — handled by
// the forward-builder at the msgContent level.
} else {
console.warn('[ElemBuilder] BUG: {type:"file"} reached element-builder — must be split out at the OneBot layer (see modules/message-actions.ts::sendPrivateMessage / ::sendGroupMessage)');
if (!ctx?.forwardFake) {
throw new Error('element-builder file routing invariant failed after preflight');
}
if (ctx.groupId !== undefined) {
result.push(makeGroupFileElem(elem, ctx));
}
// c2c forwardFake intentionally emits no Elem — handled by the
// forward-builder at the msgContent level.
break;
default:
console.warn(`[ElemBuilder] unsupported element type for send: ${elem.type}`);
break;
// assertValidMessageElements above rejects every non-W type before any
// side effect. Reaching this branch means the manifest and dispatcher
// drifted despite their reconciliation test.
throw new Error(`element-builder dispatch invariant failed: ${elem.type}`);
}
}
+378 -26
View File
@@ -26,100 +26,452 @@
* 'by-design-no' 该方向按设计不支持(QQ 协议限制),缺席是正确的。
*/
import type {
MessageElement,
MessageElementOf,
MessageElementType,
} from './events';
export const ELEMENT_DIRECTIONS = ['D', 'S', 'P', 'W'] as const;
export type ElementDirection = (typeof ELEMENT_DIRECTIONS)[number];
export type DirectionSupport = 'yes' | 'no' | 'by-design-no';
export interface ElementSpec {
type ElementField<T extends MessageElementType> = Exclude<keyof MessageElementOf<T>, 'type'> & string;
export interface ElementSpec<T extends MessageElementType> {
/** 每个方向的支持状态。 */
readonly directions: Readonly<Record<ElementDirection, DirectionSupport>>;
/**
* 该元素类型在 `MessageElement` 上「属于自己」的字段 —— 字段契约的文档基准,
* 供各方向读写时对齐(例如 poke 统一用 `subType`,不再收侧 `subType` / 发侧
* `faceId` 打架)。当前为文档性声明,字段级强制留待后续阶段。
* 该元素类型允许的全部字段。`fieldsFor` 在编译期要求它与判别联合完全一致,
* `validateMessageElement` 在运行时据此拒绝越界字段。
*/
readonly fields: readonly string[];
readonly fields: readonly ElementField<T>[];
/** 运行时必须存在(不能为 undefined/null)的字段。 */
readonly requiredFields: readonly ElementField<T>[];
/** 备注:媒体上传、三角映射、协议限制等需要跨方向知道的事。 */
readonly note?: string;
}
type ManifestShape = { readonly [T in MessageElementType]: ElementSpec<T> };
/**
* Compile-time exact-field guard: an unknown field is rejected by the tuple's
* element type; omitting a legal field makes the synthetic __missingFields
* property unsatisfied. The returned tuple remains available at runtime.
*/
function fieldsFor<T extends MessageElementType>() {
return <const F extends readonly ElementField<T>[]>(
fields: F & (Exclude<ElementField<T>, F[number]> extends never
? unknown
: { readonly __missingFields: Exclude<ElementField<T>, F[number]> }),
): F => fields;
}
/**
* 全部规范元素类型 × 四向支持。此表须与那 4 处派发代码逐字一致,否则对账测试报红。
*/
export const ELEMENT_MANIFEST = {
text: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['text'],
fields: fieldsFor<'text'>()(['text']),
requiredFields: ['text'],
},
at: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['targetUin', 'uid', 'text'],
fields: fieldsFor<'at'>()(['targetUin', 'uid', 'text']),
requiredFields: ['targetUin'],
},
face: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['faceId'],
fields: fieldsFor<'face'>()(['faceId']),
requiredFields: ['faceId'],
},
reply: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['replySeq', 'replyMessageId', 'replySenderUin', 'replyTime', 'replyRandom', 'replyElements'],
fields: fieldsFor<'reply'>()(['replySeq', 'replyMessageId', 'replySenderUin', 'replyTime', 'replyRandom', 'replyElements']),
requiredFields: ['replySeq'],
},
json: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['text'],
fields: fieldsFor<'json'>()(['text']),
requiredFields: ['text'],
},
xml: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['text', 'subType'],
fields: fieldsFor<'xml'>()(['text', 'subType']),
requiredFields: ['text'],
},
forward: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['resId', 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardNews', 'forwardTSum', 'forwardUuid'],
fields: fieldsFor<'forward'>()(['resId', 'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardNews', 'forwardTSum', 'forwardUuid']),
requiredFields: ['resId'],
},
image: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['imageUrl', 'fileId', 'fileName', 'fileSize', 'url', 'subType', 'summary', 'width', 'height', 'flash', 'md5Hex', 'sha1Hex', 'picFormat', 'noByteFallback', 'mediaNode'],
fields: fieldsFor<'image'>()(['imageUrl', 'fileId', 'fileName', 'fileSize', 'url', 'subType', 'summary', 'width', 'height', 'flash', 'md5Hex', 'sha1Hex', 'picFormat', 'noByteFallback']),
requiredFields: [],
note: 'media:W(打包)经 highway 上传、异步,需 SendContext',
},
record: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['fileName', 'fileId', 'url', 'duration', 'fileSize', 'md5Hex', 'sha1Hex', 'voiceFormat', 'noByteFallback', 'mediaNode'],
fields: fieldsFor<'record'>()(['fileName', 'fileId', 'fileSize', 'fileHash', 'url', 'duration', 'md5Hex', 'sha1Hex', 'voiceFormat', 'noByteFallback', 'mediaNode']),
requiredFields: [],
note: 'media',
},
video: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['fileName', 'fileId', 'url', 'thumbUrl', 'thumbFileId', 'duration', 'width', 'height', 'fileSize', 'md5Hex', 'sha1Hex', 'videoFormat', 'noByteFallback', 'mediaNode'],
fields: fieldsFor<'video'>()(['fileName', 'fileId', 'fileSize', 'fileHash', 'url', 'thumbUrl', 'duration', 'width', 'height', 'md5Hex', 'sha1Hex', 'videoFormat', 'noByteFallback', 'mediaNode']),
requiredFields: [],
note: 'media',
},
mface: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['emojiId', 'emojiPackageId', 'emojiKey', 'text', 'summary'],
fields: fieldsFor<'mface'>()(['emojiId', 'emojiPackageId', 'emojiKey', 'text']),
requiredFields: ['emojiId'],
note: '商城表情三角:S(转 OneBot)输出 image 段并挂 emoji_id/emoji_package_id/key 标记,P(解)再从该 image 段认回',
},
file: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
fields: ['fileId', 'thumbFileId', 'fileName', 'fileSize', 'url', 'fileHash', 'md5Hex', 'sha1Hex', 'resId'],
fields: fieldsFor<'file'>()(['fileId', 'fileName', 'fileSize', 'fileHash', 'url', 'md5Hex', 'sha1Hex']),
requiredFields: [],
note: 'W 特殊:live-send 在 OneBot 层被拆走走独立上传管线,仅 forwardFake 时落 transElem(24)',
},
poke: {
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'by-design-no' },
fields: ['subType'],
note: 'QQ 不允许戳一戳当消息段发送,故 W(打包)按设计不支持;戳一戳作为独立动作走 OIDB send-poke,与本表无关。字段契约以收侧既有 subType 为准',
fields: fieldsFor<'poke'>()(['subType']),
requiredFields: ['subType'],
note: 'P 仅负责把 OneBot 段规范化为 subType;W 会明确拒绝,因为 QQ 不允许戳一戳作为消息元素发送。请使用独立 poke Action',
},
markdown: {
directions: { D: 'no', S: 'no', P: 'yes', W: 'yes' },
fields: ['text'],
fields: fieldsFor<'markdown'>()(['text']),
requiredFields: ['text'],
note: '收侧(D/S)无对应,仅发送方向存在',
},
flash_file: {
directions: { D: 'yes', S: 'yes', P: 'by-design-no', W: 'by-design-no' },
fields: ['filesetId', 'sceneType', 'fileName'],
fields: fieldsFor<'flash_file'>()(['filesetId', 'sceneType', 'fileName']),
requiredFields: ['filesetId'],
note: '闪传文件(#199/#200):旧客户端(≤9.9.30)的 richui markdown 卡片才有;仅收侧解码上报,发送走 send_flash_msg 动作,故 P/W 按设计不支持',
},
} as const satisfies Record<string, ElementSpec>;
} as const satisfies ManifestShape;
export type ElementType = keyof typeof ELEMENT_MANIFEST;
export type MessageElementValidationCode =
| 'UNKNOWN_TYPE'
| 'UNSENDABLE_TYPE'
| 'MISSING_FIELD'
| 'UNEXPECTED_FIELD'
| 'INVALID_FIELD';
/** Stable typed error for callers that map invalid messages to BAD_REQUEST. */
export class MessageElementValidationError extends Error {
override readonly name = 'MessageElementValidationError';
constructor(
readonly code: MessageElementValidationCode,
message: string,
readonly elementType?: string,
readonly field?: string,
) {
super(message);
}
}
export type MessageElementValidationResult =
| { readonly ok: true; readonly element: MessageElement }
| { readonly ok: false; readonly error: MessageElementValidationError };
const STRING_FIELDS: ReadonlySet<string> = new Set([
'text', 'uid', 'imageUrl', 'fileId', 'fileName', 'fileHash', 'url',
'thumbUrl', 'summary', 'emojiId', 'emojiKey', 'resId', 'filesetId',
'forwardSource', 'forwardSummary', 'forwardPrompt', 'forwardUuid',
'md5Hex', 'sha1Hex',
]);
const NUMBER_FIELDS: ReadonlySet<string> = new Set([
'faceId', 'targetUin', 'fileSize', 'replySeq', 'replyMessageId',
'replySenderUin', 'replyTime', 'replyRandom', 'subType', 'duration',
'width', 'height', 'emojiPackageId', 'sceneType', 'forwardTSum',
'picFormat', 'videoFormat', 'voiceFormat',
]);
const BOOLEAN_FIELDS: ReadonlySet<string> = new Set(['flash', 'noByteFallback']);
function throwValidation(
code: MessageElementValidationCode,
message: string,
elementType?: string,
field?: string,
): never {
throw new MessageElementValidationError(code, message, elementType, field);
}
function validateFieldValue(type: ElementType, field: string, value: unknown): void {
if (value === undefined) return;
if (STRING_FIELDS.has(field)) {
if (typeof value !== 'string') {
throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must be a string`, type, field);
}
return;
}
if (NUMBER_FIELDS.has(field)) {
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must be a safe integer`, type, field);
}
return;
}
if (BOOLEAN_FIELDS.has(field)) {
if (typeof value !== 'boolean') {
throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must be a boolean`, type, field);
}
return;
}
if (field === 'replyElements') {
if (!Array.isArray(value)) {
throwValidation('INVALID_FIELD', 'message element "reply" field "replyElements" must be an array', type, field);
}
for (const quoted of value) assertValidMessageElement(quoted);
return;
}
if (field === 'forwardNews') {
if (!Array.isArray(value) || value.some((item) => (
typeof item !== 'object' || item === null || Array.isArray(item)
|| typeof (item as { text?: unknown }).text !== 'string'
|| Object.keys(item).some((key) => key !== 'text')
))) {
throwValidation('INVALID_FIELD', 'message element "forward" field "forwardNews" must contain only { text: string } entries', type, field);
}
return;
}
if (field === 'mediaNode') {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throwValidation('INVALID_FIELD', `message element "${type}" field "mediaNode" must be an object`, type, field);
}
return;
}
// This is an invariant failure in the executable contract, not bad user
// input: adding a manifest field without a runtime validator must be loud.
throw new Error(`element manifest field has no runtime validator: ${type}.${field}`);
}
function requireNonEmptyString(element: Record<string, unknown>, type: ElementType, field: string): void {
const value = element[field];
if (typeof value !== 'string' || value.length === 0) {
throwValidation('INVALID_FIELD', `message element "${type}" field "${field}" must not be empty`, type, field);
}
}
function validateSemantics(
element: MessageElement,
direction: ElementDirection | undefined,
): void {
const nonNegativeFields = [
'targetUin', 'faceId', 'fileSize', 'replySeq',
'replySenderUin', 'replyTime', 'subType', 'duration', 'width', 'height',
'emojiPackageId', 'sceneType', 'forwardTSum', 'picFormat', 'videoFormat',
'voiceFormat',
] as const;
const record = element as unknown as Record<string, unknown>;
for (const field of nonNegativeFields) {
const value = record[field];
if (typeof value === 'number' && value < 0) {
throwValidation(
'INVALID_FIELD',
`message element "${element.type}" field "${field}" must be non-negative`,
element.type,
field,
);
}
}
if (element.md5Hex !== undefined && !/^[0-9a-fA-F]{32}$/.test(element.md5Hex)) {
throwValidation(
'INVALID_FIELD',
`message element "${element.type}" field "md5Hex" must be exactly 32 hexadecimal characters`,
element.type,
'md5Hex',
);
}
if (element.sha1Hex !== undefined && !/^[0-9a-fA-F]{40}$/.test(element.sha1Hex)) {
throwValidation(
'INVALID_FIELD',
`message element "${element.type}" field "sha1Hex" must be exactly 40 hexadecimal characters`,
element.type,
'sha1Hex',
);
}
switch (element.type) {
case 'text':
case 'xml':
case 'markdown':
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'text');
return;
case 'json': {
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'text');
if (direction !== 'P' && direction !== 'W') return;
try {
const parsed = JSON.parse(element.text) as unknown;
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('not an object');
} catch {
throwValidation(
'INVALID_FIELD',
'message element "json" field "text" must contain a JSON object',
element.type,
'text',
);
}
return;
}
case 'at':
if (!Number.isInteger(element.targetUin) || element.targetUin < 0) {
throwValidation('INVALID_FIELD', 'message element "at" field "targetUin" must be a non-negative integer', element.type, 'targetUin');
}
return;
case 'face':
if (!Number.isInteger(element.faceId) || element.faceId < 0) {
throwValidation('INVALID_FIELD', 'message element "face" field "faceId" must be a non-negative integer', element.type, 'faceId');
}
return;
case 'reply':
if (!Number.isInteger(element.replySeq) || element.replySeq <= 0) {
throwValidation('INVALID_FIELD', 'message element "reply" field "replySeq" must be a positive integer', element.type, 'replySeq');
}
return;
case 'mface':
if (!/^[0-9a-fA-F]{32}$/.test(element.emojiId)) {
throwValidation(
'INVALID_FIELD',
'message element "mface" field "emojiId" must be exactly 32 hexadecimal characters',
element.type,
'emojiId',
);
}
return;
case 'forward':
requireNonEmptyString(element as unknown as Record<string, unknown>, element.type, 'resId');
return;
case 'image': {
if (direction !== 'P' && direction !== 'W') return;
if (element.noByteFallback === true && (!element.md5Hex?.trim() || !element.sha1Hex?.trim())) {
throwValidation(
'MISSING_FIELD',
`message element "${element.type}" with noByteFallback requires md5Hex + sha1Hex`,
element.type,
'md5Hex',
);
}
const hasSource = Boolean(element.url?.trim() || element.imageUrl?.trim() || element.fileId?.trim());
const hasFingerprint = element.noByteFallback === true
&& Boolean(element.md5Hex?.trim() && element.sha1Hex?.trim());
if (!hasSource && !hasFingerprint) {
throwValidation(
'MISSING_FIELD',
`message element "${element.type}" requires a file/url source or a complete fast-upload fingerprint`,
element.type,
'url',
);
}
return;
}
case 'record':
case 'video': {
if (direction !== 'P' && direction !== 'W') return;
if (element.noByteFallback === true && (!element.md5Hex?.trim() || !element.sha1Hex?.trim())) {
throwValidation(
'MISSING_FIELD',
`message element "${element.type}" with noByteFallback requires md5Hex + sha1Hex`,
element.type,
'md5Hex',
);
}
const hasSource = Boolean(element.url?.trim() || element.fileId?.trim());
const hasFingerprint = element.noByteFallback === true
&& Boolean(element.md5Hex?.trim() && element.sha1Hex?.trim());
if (!hasSource && !hasFingerprint) {
throwValidation(
'MISSING_FIELD',
`message element "${element.type}" requires a file/url source or a complete fast-upload fingerprint`,
element.type,
'url',
);
}
return;
}
case 'file':
if ((direction === 'P' || direction === 'W') && !element.url?.trim() && !element.fileId?.trim()) {
throwValidation('MISSING_FIELD', 'message element "file" requires file_id or file/url', element.type, 'fileId');
}
return;
case 'poke':
case 'flash_file':
return;
}
}
/**
* Validate a runtime value against the same field table checked by TypeScript.
* P/W additionally enforce sendability and source requirements.
*/
export function assertValidMessageElement(
value: unknown,
direction?: ElementDirection,
): asserts value is MessageElement {
if (typeof value !== 'object' || value === null || Array.isArray(value)) {
throwValidation('INVALID_FIELD', 'message element must be an object');
}
const element = value as Record<string, unknown>;
const rawType = element.type;
if (typeof rawType !== 'string' || !Object.hasOwn(ELEMENT_MANIFEST, rawType)) {
throwValidation('UNKNOWN_TYPE', `unknown message element type: ${String(rawType)}`, String(rawType));
}
const type = rawType as ElementType;
const spec = ELEMENT_MANIFEST[type];
if (direction && spec.directions[direction] !== 'yes') {
const hint = type === 'poke'
? 'use the dedicated poke Action instead'
: type === 'flash_file'
? 'use the send_flash_msg Action instead'
: `direction ${direction} is not supported`;
throwValidation('UNSENDABLE_TYPE', `message element "${type}" cannot be sent; ${hint}`, type);
}
const allowed = new Set<string>(['type', ...spec.fields]);
for (const key of Object.keys(element)) {
if (!allowed.has(key)) {
throwValidation('UNEXPECTED_FIELD', `message element "${type}" does not allow field "${key}"`, type, key);
}
}
for (const field of spec.requiredFields) {
if (element[field] === undefined || element[field] === null) {
throwValidation('MISSING_FIELD', `message element "${type}" requires field "${field}"`, type, field);
}
}
for (const field of spec.fields) validateFieldValue(type, field, element[field]);
validateSemantics(element as unknown as MessageElement, direction);
}
export function validateMessageElement(
value: unknown,
direction?: ElementDirection,
): MessageElementValidationResult {
try {
assertValidMessageElement(value, direction);
return { ok: true, element: value };
} catch (error) {
if (error instanceof MessageElementValidationError) return { ok: false, error };
throw error;
}
}
export function assertValidMessageElements(
values: readonly unknown[],
direction?: ElementDirection,
): asserts values is readonly MessageElement[] {
for (const value of values) assertValidMessageElement(value, direction);
}
/**
* 某方向应被处理的元素类型集合(`directions[dir] === 'yes'`)—— 对账测试的基准。
*/
@@ -132,10 +484,10 @@ export function typesForDirection(dir: ElementDirection): Set<string> {
}
/**
* 发·解(P)侧还接收一批「纯 OneBot 输入糖」:它们不是某种真实消息元素,只是被
* 塌缩成 json / face / poke 的输入便利(如骰子、猜拳、位置/音乐/名片分享、转发
* node、匿名标记),没有收侧对应,也没有专属的 wire 形态,故不进本清单。对账 P
* 时须先从代码里剔除这些类型。
* 发·解(P)侧还识别一批「纯 OneBot 输入词」:可执行的会塌缩成 json / face,
* node 仅允许在 forward node list 的专用解析器中使用,shake / anonymous 因没有
* 合法消息元素语义而返回 typed validation error。它们没有收侧对应,也没有专属
* wire 形态,故不进本清单;对账 P 时须先从代码里剔除这些类型。
*/
export const INPUT_SUGAR_SEGMENTS: ReadonlySet<string> = new Set([
'node', 'share', 'music', 'location', 'contact', 'rps', 'dice', 'shake', 'anonymous',
+184 -80
View File
@@ -1,95 +1,199 @@
export interface MessageElement {
type: string; // 'text'|'at'|'face'|'mface'|'image'|'video'|'record'|'file'|'json'|'xml'|'reply'|'poke'|'forward'
text?: string;
faceId?: number;
targetUin?: number;
uid?: string;
imageUrl?: string;
fileId?: string;
thumbFileId?: string;
fileName?: string;
fileSize?: number;
replySeq?: number;
replyMessageId?: number; // For reply: original message ID (for logging)
replySenderUin?: number; // For reply: original sender's UIN
replyTime?: number; // For reply: original message timestamp
replyRandom?: number; // For reply: original message random/msgId
replyElements?: MessageElement[]; // Decoded elements of the quoted message (SrcMsg.elems) — lets a backfill reconstruct it for get_msg without a server round-trip
url?: string;
thumbUrl?: string;
/** Re-upload metadata carried by received record/video elements. */
export interface MediaNode {
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
duration?: number;
width?: number;
height?: number;
summary?: string;
// Market face (商城表情). Decoded from the wire `marketFace` element; the
// OneBot layer surfaces it as an `image` segment carrying these as markers,
// and the send path rebuilds the wire `marketFace` from them.
// emojiId = hex(MarketFace.faceId) → also builds the gxh gif URL
// emojiPackageId = MarketFace.tabId
// emojiKey = MarketFace.key
emojiId?: string;
emojiPackageId?: number;
emojiKey?: string;
flash?: boolean;
resId?: string;
fileHash?: string;
// 闪传文件 (flash transfer) — decoded from an older-client richui markdown
// commonElem (svc=45, busId=FlashTransfer). #199/#200. title reuses fileName.
filesetId?: string;
sceneType?: number;
// Preview-bubble metadata for the `forward` element. Drives the
// `com.tencent.multimsg` LightApp JSON the recipient renders before
// they tap to expand. When unset, the element builder falls back to
// generic defaults so old call sites keep working.
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
}
export interface TextElement {
type: 'text';
text: string;
}
export interface AtElement {
type: 'at';
/** 0 denotes @all. */
targetUin: number;
uid?: string;
text?: string;
}
export interface FaceElement {
type: 'face';
faceId: number;
}
export interface ReplyElement {
type: 'reply';
replySeq: number;
replyMessageId?: number;
replySenderUin?: number;
replyTime?: number;
replyRandom?: number;
/** Decoded quoted elements, used to backfill get_msg locally. */
replyElements?: MessageElement[];
}
export interface JsonElement {
type: 'json';
text: string;
}
export interface XmlElement {
type: 'xml';
text: string;
subType?: number;
}
export interface MarkdownElement {
type: 'markdown';
text: string;
}
export interface ForwardElement {
type: 'forward';
resId: string;
forwardSource?: string;
forwardSummary?: string;
forwardPrompt?: string;
forwardNews?: Array<{ text: string }>;
forwardTSum?: number;
/** `uniseq` baked into the preview's LightApp JSON. For a nested
* forward, the *outer* upload uses this same uuid as the
* `actionCommand` for the piggyback entry carrying the inner
* layer's msgBody — so receivers (Mobile QQ / QQ-NT clients) can
* resolve the inner layer from the outer's single fetch instead of
* hitting the server again. Defaults to a fresh UUID on send when
* omitted (i.e. for non-nested forwards). */
/** Links a nested preview to its piggybacked actionCommand. */
forwardUuid?: string;
// Server-side fingerprints carried from receive side so a forward can do a
// pure md5/sha1 fast-upload without re-downloading the original bytes.
// Set together with `noByteFallback: true` to make the upload modules throw
// instead of falling back to fetch(url).
}
interface FingerprintFields {
md5Hex?: string;
sha1Hex?: string;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
/** Disallow falling back to source bytes when a fast upload misses. */
noByteFallback?: boolean;
mediaNode?: {
fileUuid?: string;
storeId?: number;
uploadTime?: number;
ttl?: number;
subType?: number;
info?: {
fileSize?: number;
fileHash?: string;
fileSha1?: string;
fileName?: string;
width?: number;
height?: number;
time?: number;
original?: number;
type?: {
type?: number;
picFormat?: number;
videoFormat?: number;
voiceFormat?: number;
};
};
};
}
export interface ImageElement extends FingerprintFields {
type: 'image';
imageUrl?: string;
fileId?: string;
fileName?: string;
fileSize?: number;
url?: string;
subType?: number;
summary?: string;
width?: number;
height?: number;
flash?: boolean;
picFormat?: number;
}
export interface RecordElement extends FingerprintFields {
type: 'record';
fileName?: string;
fileId?: string;
fileSize?: number;
fileHash?: string;
url?: string;
duration?: number;
voiceFormat?: number;
mediaNode?: MediaNode;
}
export interface VideoElement extends FingerprintFields {
type: 'video';
fileName?: string;
fileId?: string;
fileSize?: number;
fileHash?: string;
url?: string;
thumbUrl?: string;
duration?: number;
width?: number;
height?: number;
videoFormat?: number;
mediaNode?: MediaNode;
}
/** Market face (商城表情); emojiId is the hex wire face GUID. */
export interface MarketFaceElement {
type: 'mface';
emojiId: string;
emojiPackageId?: number;
emojiKey?: string;
text?: string;
}
export interface FileElement {
type: 'file';
fileId?: string;
fileName?: string;
fileSize?: number;
fileHash?: string;
url?: string;
md5Hex?: string;
sha1Hex?: string;
}
/** Receive-side representation only; sending uses the dedicated poke Action. */
export interface PokeElement {
type: 'poke';
subType: number;
}
/** Receive-side flash-transfer card; sending uses send_flash_msg. */
export interface FlashFileElement {
type: 'flash_file';
filesetId: string;
sceneType?: number;
fileName?: string;
}
type MessageElementVariant =
| TextElement
| AtElement
| FaceElement
| ReplyElement
| JsonElement
| XmlElement
| MarkdownElement
| ForwardElement
| ImageElement
| RecordElement
| VideoElement
| MarketFaceElement
| FileElement
| PokeElement
| FlashFileElement;
type UnionKeys<T> = T extends T ? keyof T : never;
type StrictUnionMember<T, All> = T extends T
? T & Partial<Record<Exclude<UnionKeys<All>, keyof T>, never>>
: never;
/**
* Closed message-element vocabulary. The optional-never fields make excess
* fields fail at compile time even when assigning an object to the union
* directly (for example, `{ type: 'poke', faceId: 1 }` is illegal).
*/
export type MessageElement = StrictUnionMember<MessageElementVariant, MessageElementVariant>;
export type MessageElementType = MessageElementVariant['type'];
export type MessageElementOf<T extends MessageElementType> = Extract<MessageElementVariant, { type: T }>;
export interface ForwardNodePayload {
userUin: number;
nickname: string;
@@ -70,7 +70,7 @@ function loadImage(element: MessageElement): Promise<ImageData> {
return Promise.resolve(imageDataFromFingerprint(element));
}
return loadImageFromSource(
element.url || element.fileId || '',
element.url || element.imageUrl || element.fileId || '',
element.fileName ?? '',
element.subType ?? 0,
element.summary ?? '',
@@ -1,7 +1,12 @@
import { describe, it, expect } from 'vitest';
import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { typesForDirection } from '../src/element-manifest';
import {
ELEMENT_MANIFEST,
MessageElementValidationError,
assertValidMessageElement,
typesForDirection,
} from '../src/element-manifest';
// 对账测试(protocol 侧)—— 拿 element-manifest 核对「按 element.type 收敛」的
// 两个 protocol 方向:
@@ -47,4 +52,76 @@ describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)
expect(handled).not.toContain('poke');
expect(handled).toEqual(sorted(typesForDirection('W')));
});
it('fields 是可执行封闭契约:每个声明字段都有 validator,越界字段会拒绝', () => {
const sampleValue = (field: string): unknown => {
if (field === 'replyElements') return [];
if (field === 'forwardNews') return [{ text: 'preview' }];
if (field === 'mediaNode') return {};
if (field === 'emojiId' || field === 'md5Hex') return 'ab'.repeat(16);
if (field === 'sha1Hex') return 'cd'.repeat(20);
if (field === 'flash' || field === 'noByteFallback') return true;
if (field === 'targetUin' || field === 'faceId' || field === 'fileSize'
|| field.startsWith('reply') || field === 'subType' || field === 'duration'
|| field === 'width' || field === 'height' || field === 'emojiPackageId'
|| field === 'sceneType' || field === 'forwardTSum' || field.endsWith('Format')) return 1;
return 'value';
};
for (const [type, spec] of Object.entries(ELEMENT_MANIFEST)) {
expect(new Set(spec.fields).size, `${type} has duplicate fields`).toBe(spec.fields.length);
for (const required of spec.requiredFields) expect(spec.fields).toContain(required);
const element: Record<string, unknown> = { type };
for (const field of spec.fields) element[field] = sampleValue(field);
expect(() => assertValidMessageElement(element), type).not.toThrow();
}
expect(() => assertValidMessageElement({ type: 'poke', subType: 1, faceId: 1 }))
.toThrowError(expect.objectContaining({
name: 'MessageElementValidationError',
code: 'UNEXPECTED_FIELD',
elementType: 'poke',
field: 'faceId',
}));
expect(() => assertValidMessageElement({ type: 'reply' }))
.toThrowError(expect.objectContaining({ code: 'MISSING_FIELD', field: 'replySeq' }));
expect(() => assertValidMessageElement({ type: 'toString' }))
.toThrowError(expect.objectContaining({ code: 'UNKNOWN_TYPE', elementType: 'toString' }));
expect(() => assertValidMessageElement({ type: 'mface', emojiId: 'zz' }, 'W'))
.toThrowError(expect.objectContaining({ code: 'INVALID_FIELD', field: 'emojiId' }));
expect(() => assertValidMessageElement({
type: 'image',
url: 'https://example.com/a.png',
md5Hex: 'not-md5',
}, 'W')).toThrowError(expect.objectContaining({ code: 'INVALID_FIELD', field: 'md5Hex' }));
});
it('returns a stable typed validation error for BAD_REQUEST mapping', () => {
try {
assertValidMessageElement({ type: 'unknown-segment' }, 'W');
expect.unreachable('validation should throw');
} catch (error) {
expect(error).toBeInstanceOf(MessageElementValidationError);
expect(error).toMatchObject({ code: 'UNKNOWN_TYPE', elementType: 'unknown-segment' });
}
});
it('rejects invalid wire ranges and incomplete fast-upload fingerprints', () => {
expect(() => assertValidMessageElement({
type: 'file',
fileId: 'fid',
fileSize: -1,
}, 'P')).toThrowError(expect.objectContaining({
code: 'INVALID_FIELD',
field: 'fileSize',
}));
expect(() => assertValidMessageElement({
type: 'image',
url: 'https://example.com/fallback-must-not-be-used.png',
noByteFallback: true,
}, 'W')).toThrowError(expect.objectContaining({
code: 'MISSING_FIELD',
field: 'md5Hex',
}));
});
});