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
@@ -10,7 +10,8 @@ import type {
|
||||
} from '@snowluma/proto-defs/longmsg';
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement } from '@snowluma/protocol/events';
|
||||
import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
import { parseMsgPush } from '@snowluma/protocol/msg-push';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
@@ -242,8 +243,8 @@ function cloneNodeWithElements(node: ForwardNodePayload, elements: MessageElemen
|
||||
};
|
||||
}
|
||||
|
||||
function stripFileSource(element: MessageElement): MessageElement {
|
||||
const next: MessageElement = { ...element };
|
||||
function stripFileSource(element: MessageElementOf<'file'>): MessageElementOf<'file'> {
|
||||
const next: MessageElementOf<'file'> = { ...element };
|
||||
delete next.url;
|
||||
return next;
|
||||
}
|
||||
@@ -267,10 +268,28 @@ function fileNameForUpload(element: MessageElement, cached?: UploadedFileMeta):
|
||||
return (element.fileName ?? cached?.fileName ?? '').trim();
|
||||
}
|
||||
|
||||
function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
|
||||
for (const node of nodes) {
|
||||
const fileCount = node.elements.filter((element) => element.type === 'file').length;
|
||||
if (fileCount > 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'a private forward node can contain at most one file element',
|
||||
'file',
|
||||
);
|
||||
}
|
||||
if (node.innerForward) assertPrivateForwardFileCapacity(node.innerForward);
|
||||
}
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||
// A c2c RichText owns exactly one msgContent/FileExtra payload. Validate
|
||||
// the entire recursive tree before any file/media/long-message upload so a
|
||||
// second file cannot be uploaded and then silently discarded.
|
||||
if (groupId === undefined) assertPrivateForwardFileCapacity(nodes);
|
||||
const { resId } = await this.uploadRecursive(nodes, groupId, userId);
|
||||
return resId;
|
||||
}
|
||||
@@ -290,7 +309,7 @@ export class ForwardApi {
|
||||
name: string,
|
||||
groupId?: number,
|
||||
userId?: number,
|
||||
): Promise<MessageElement> {
|
||||
): Promise<MessageElementOf<'file'>> {
|
||||
if (groupId !== undefined) {
|
||||
const uploaded = await this.ctx.apis.groupFile.upload(groupId, source, name, '/', true, false);
|
||||
if (!uploaded.fileId) throw new Error('forward group file upload returned no file_id');
|
||||
|
||||
@@ -267,6 +267,38 @@ describe('actions/forward — file segment inside forward node', () => {
|
||||
})]);
|
||||
});
|
||||
|
||||
it('rejects two files in one private forward node before uploading either file', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const uploadPrivate = vi.fn();
|
||||
const sendRawPacket = vi.fn();
|
||||
const bridge = mockBridge({
|
||||
sendRawPacket: sendRawPacket as any,
|
||||
apis: {
|
||||
...mockBridge().apis,
|
||||
groupFile: {
|
||||
...mockBridge().apis.groupFile,
|
||||
uploadPrivate,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
await expect(new ForwardApi(bridge as any).upload([{
|
||||
userUin: 10001,
|
||||
nickname: 'alice',
|
||||
elements: [
|
||||
{ type: 'file', url: 'base64://AQID', fileName: 'one.txt' },
|
||||
{ type: 'file', url: 'base64://BAUG', fileName: 'two.txt' },
|
||||
] as any,
|
||||
}], undefined, 67890)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'file',
|
||||
});
|
||||
|
||||
expect(uploadPrivate).not.toHaveBeenCalled();
|
||||
expect(buildSendElemsMock).not.toHaveBeenCalled();
|
||||
expect(sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('private file forward keeps the long-msg upload under the self uid namespace', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
let captured: Uint8Array | undefined;
|
||||
|
||||
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user