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:
24 files changed
+1883
-417
No files matched your search
@@ -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}`);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
@@ -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',
|
||||
}));
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user