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

@@ -267,6 +267,38 @@ describe('actions/forward — file segment inside forward node', () => {
})]);
});
it('rejects two files in one private forward node before uploading either file', async () => {
buildSendElemsMock.mockClear();
const uploadPrivate = vi.fn();
const sendRawPacket = vi.fn();
const bridge = mockBridge({
sendRawPacket: sendRawPacket as any,
apis: {
...mockBridge().apis,
groupFile: {
...mockBridge().apis.groupFile,
uploadPrivate,
},
},
});
await expect(new ForwardApi(bridge as any).upload([{
userUin: 10001,
nickname: 'alice',
elements: [
{ type: 'file', url: 'base64://AQID', fileName: 'one.txt' },
{ type: 'file', url: 'base64://BAUG', fileName: 'two.txt' },
] as any,
}], undefined, 67890)).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'file',
});
expect(uploadPrivate).not.toHaveBeenCalled();
expect(buildSendElemsMock).not.toHaveBeenCalled();
expect(sendRawPacket).not.toHaveBeenCalled();
});
it('private file forward keeps the long-msg upload under the self uid namespace', async () => {
buildSendElemsMock.mockClear();
let captured: Uint8Array | undefined;
+61 -12
View File
@@ -28,6 +28,8 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({
}));
import { buildSendElems } from '@snowluma/protocol/element-builder';
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
const fakeBridge = {} as any;
@@ -131,6 +133,55 @@ describe('element-builder / commonElem.businessType per scene', () => {
});
});
describe('element-builder / all-message validation preflight', () => {
it('does not upload an early image when a later segment is unsendable', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await expect(buildSendElems([
{ type: 'image', url: 'file:///tmp/valid-before-invalid.png' },
{ type: 'poke', subType: 1 },
] as any, { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
code: 'UNSENDABLE_TYPE',
elementType: 'poke',
});
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
});
it('accepts a received imageUrl-only element for re-send', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await buildSendElems(
[{ type: 'image', imageUrl: 'https://gchat.qpic.cn/received.jpg' }],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(uploadImageMsgInfo).toHaveBeenCalledWith(
fakeBridge,
true,
12345,
expect.objectContaining({ imageUrl: 'https://gchat.qpic.cn/received.jpg' }),
);
});
it('does not upload an early image when a later fast-only media element lacks hashes', async () => {
vi.mocked(uploadImageMsgInfo).mockClear();
await expect(buildSendElems([
{ type: 'image', url: 'file:///tmp/valid-before-invalid.png' },
{
type: 'image',
url: 'file:///tmp/must-not-fallback.png',
noByteFallback: true,
},
] as any, { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
code: 'MISSING_FIELD',
elementType: 'image',
field: 'md5Hex',
});
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
});
});
describe('element-builder / file element is no longer carried in elems[]', () => {
// Regression for the `result=79` class: previously the element-builder
// emitted a `transElem(elemType=24, ...)` for `{type:'file'}` segments
@@ -141,8 +192,8 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
// segment is split off. The element-builder therefore must NOT emit
// any element for `{type:'file'}` anymore — if it does, the message
// ships with a transElem(24) payload and result=79 returns.
it('produces an empty elems[] for a {type:"file"} segment (must be split out at OneBot layer)', async () => {
const result = await buildSendElems(
it('fails fast when a live {type:"file"} reaches the element builder', async () => {
await expect(buildSendElems(
[{
type: 'file',
fileId: 'fid-abc',
@@ -152,8 +203,11 @@ describe('element-builder / file element is no longer carried in elems[]', () =>
sha1Hex: '0102030405060708090a0b0c0d0e0f1011121314',
} as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(result).toEqual([]);
)).rejects.toMatchObject({
name: 'MessageElementValidationError',
code: 'UNSENDABLE_TYPE',
elementType: 'file',
});
});
});
@@ -228,15 +282,10 @@ describe('element-builder / forward preview (com.tencent.multimsg LightApp)', ()
expect(JSON.parse(json.extra).tsum).toBe(3);
});
it('drops the forward element when resId is missing (preview unrenderable, fail open)', async () => {
// The dispatcher's `case 'forward': if (elem.resId) ...` short-
// circuits when resId is empty so a malformed segment from the
// OneBot client doesn't blow up the whole send. Receiver sees
// no forward bubble — same outcome as omitting the segment.
const out = await buildSendElems(
it('rejects a forward element when resId is missing', async () => {
await expect(buildSendElems(
[{ type: 'forward' } as any],
{ bridge: fakeBridge, groupId: 12345 },
);
expect(out).toEqual([]);
)).rejects.toBeInstanceOf(MessageElementValidationError);
});
});
@@ -23,6 +23,7 @@ vi.mock('@snowluma/protocol/highway/utils', () => ({
}));
import * as pipeline from '@snowluma/protocol/highway/pipeline';
import * as utils from '@snowluma/protocol/highway/utils';
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from '@snowluma/protocol/highway';
@@ -30,6 +31,7 @@ describe('image-upload', () => {
beforeEach(() => {
vi.mocked(pipeline.runNtv2Upload).mockClear();
vi.mocked(pipeline.finalizeMediaMsgInfo).mockClear();
vi.mocked(utils.loadBinarySource).mockClear();
});
it('group: uses 0x11C4_100 + GROUP_IMAGE_CMD_ID and tags scene as group', async () => {
@@ -58,6 +60,19 @@ describe('image-upload', () => {
expect((args.extBizInfo as any).pic.reserveTroop).toBeUndefined();
});
it('uses receive-side imageUrl when url/fileId are absent', async () => {
await uploadImageMsgInfo(
{} as any,
true,
12345,
{ type: 'image', imageUrl: 'https://gchat.qpic.cn/received.jpg' },
);
expect(utils.loadBinarySource).toHaveBeenCalledWith(
'https://gchat.qpic.cn/received.jpg',
'image',
);
});
it('encodes the detected picFormat and image dimensions into fileInfo', async () => {
await uploadImageMsgInfo({} as any, true, 12345, { url: 'http://x' } as any);
const fileInfo = (vi.mocked(pipeline.runNtv2Upload).mock.calls[0]![0].uploadInfo[0] as any).fileInfo;