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

@@ -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();
});
});