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 committed 2026-07-10 13:47:06 +08:00
1 parent aff6ad9179
commit 01688c7567
24 files changed
+1883 -417

No files matched your search

+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',
);
}