fix(onebot): reject ambiguous video message combinations
Prevent ordinary messages and forwarded nodes from combining video content with visible sibling segments or additional videos. Invalid combinations now fail before parsing side effects, media work, or bridge sends, while exact empty text placeholders remain compatible with a single video. Cover group, private, temporary-session, CQ string, nested forward, cached forward, and protocol-builder paths. Preserve the existing standalone window-shake behavior and keep valid single-video messages unchanged.
This commit is contained in:
8 files changed
+371
-29
No files matched your search
@@ -30,6 +30,7 @@ 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';
|
||||
import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload';
|
||||
|
||||
const fakeBridge = {} as any;
|
||||
|
||||
@@ -168,6 +169,63 @@ describe('element-builder / commonElem.businessType per scene', () => {
|
||||
});
|
||||
|
||||
describe('element-builder / all-message validation preflight', () => {
|
||||
it('rejects hidden siblings and duplicate videos before uploading', async () => {
|
||||
vi.mocked(uploadVideoMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'video', url: 'file:///tmp/clip.mp4' },
|
||||
{ type: 'text', text: 'must not become hidden content' },
|
||||
], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
message: expect.stringContaining('only segment'),
|
||||
});
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'video', url: 'file:///tmp/first.mp4' },
|
||||
{ type: 'video', url: 'file:///tmp/second.mp4' },
|
||||
], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
message: expect.stringContaining('only once'),
|
||||
});
|
||||
|
||||
expect(uploadVideoMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps empty canonical text invalid instead of sending it beside a video', async () => {
|
||||
vi.mocked(uploadVideoMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'text', text: '' },
|
||||
{ type: 'video', url: 'file:///tmp/clip.mp4' },
|
||||
], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({
|
||||
code: 'INVALID_FIELD',
|
||||
elementType: 'text',
|
||||
});
|
||||
|
||||
expect(uploadVideoMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('applies standalone-video validation to forward nodes', async () => {
|
||||
vi.mocked(uploadVideoMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'video', url: 'file:///tmp/clip.mp4' },
|
||||
{ type: 'text', text: 'must not survive bot forwarding' },
|
||||
], {
|
||||
bridge: fakeBridge,
|
||||
groupId: 12345,
|
||||
forwardFake: true,
|
||||
scene: 'forward',
|
||||
})).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
});
|
||||
|
||||
expect(uploadVideoMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not upload an early image when a later segment is unsendable', async () => {
|
||||
vi.mocked(uploadImageMsgInfo).mockClear();
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import {
|
||||
assertVideoSendPolicy,
|
||||
assertWindowShakeSendPolicy,
|
||||
assertValidMessageElement,
|
||||
ELEMENT_MANIFEST,
|
||||
@@ -68,9 +69,22 @@ function normalizeSegmentType(type: string): string {
|
||||
return type.toLowerCase();
|
||||
}
|
||||
|
||||
function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): string[] {
|
||||
interface OutboundInputSegmentSummary {
|
||||
rawTypes: string[];
|
||||
effectiveVideoTypes: string[];
|
||||
}
|
||||
|
||||
function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean {
|
||||
return normalizeSegmentType(segment.type) === 'text'
|
||||
&& segmentPayload(segment).text === '';
|
||||
}
|
||||
|
||||
function outboundInputSegmentSummary(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): OutboundInputSegmentSummary {
|
||||
if (typeof message === 'string') {
|
||||
if (autoEscape) return ['text'];
|
||||
if (autoEscape) return { rawTypes: ['text'], effectiveVideoTypes: ['text'] };
|
||||
const types: string[] = [];
|
||||
let lastIndex = 0;
|
||||
for (const match of message.matchAll(CQ_REGEX)) {
|
||||
@@ -79,34 +93,48 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str
|
||||
lastIndex = match.index! + match[0].length;
|
||||
}
|
||||
if (lastIndex < message.length) types.push('text');
|
||||
return types;
|
||||
return { rawTypes: types, effectiveVideoTypes: types };
|
||||
}
|
||||
if (Array.isArray(message)) {
|
||||
return message.flatMap((item) => {
|
||||
if (typeof item !== 'object' || item === null || Array.isArray(item)) return [];
|
||||
const rawTypes: string[] = [];
|
||||
const effectiveVideoTypes: string[] = [];
|
||||
for (const item of message) {
|
||||
if (typeof item !== 'object' || item === null || Array.isArray(item)) continue;
|
||||
const type = (item as { type?: unknown }).type;
|
||||
return typeof type === 'string' ? [normalizeSegmentType(type)] : [];
|
||||
});
|
||||
if (typeof type !== 'string') continue;
|
||||
const normalizedType = normalizeSegmentType(type);
|
||||
rawTypes.push(normalizedType);
|
||||
if (!isExplicitEmptyTextPlaceholder(item as MessageSegment)) {
|
||||
effectiveVideoTypes.push(normalizedType);
|
||||
}
|
||||
}
|
||||
return { rawTypes, effectiveVideoTypes };
|
||||
}
|
||||
if (typeof message === 'object' && message !== null) {
|
||||
const type = (message as { type?: unknown }).type;
|
||||
return typeof type === 'string' ? [normalizeSegmentType(type)] : [];
|
||||
const types = typeof type === 'string' ? [normalizeSegmentType(type)] : [];
|
||||
return { rawTypes: types, effectiveVideoTypes: types };
|
||||
}
|
||||
return [];
|
||||
return { rawTypes: [], effectiveVideoTypes: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject unsupported window-shake inputs before parsers can resolve identities,
|
||||
* fetch cards, sign music, or perform any other externally visible work.
|
||||
* Reject unsupported message combinations before parsers can resolve
|
||||
* identities, fetch cards, sign music, or perform any other externally
|
||||
* visible work.
|
||||
*/
|
||||
export function assertWindowShakeMessageInput(
|
||||
export function assertOutboundMessageInput(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
scene: OutboundMessageScene,
|
||||
): void {
|
||||
const types = outboundInputSegmentTypes(message, autoEscape);
|
||||
const shakeCount = types.filter((type) => type === 'poke' || type === 'shake').length;
|
||||
assertWindowShakeSendPolicy(shakeCount, types.length, scene);
|
||||
const { rawTypes, effectiveVideoTypes } = outboundInputSegmentSummary(message, autoEscape);
|
||||
assertVideoSendPolicy(
|
||||
effectiveVideoTypes.filter((type) => type === 'video').length,
|
||||
effectiveVideoTypes.length,
|
||||
);
|
||||
const shakeCount = rawTypes.filter((type) => type === 'poke' || type === 'shake').length;
|
||||
assertWindowShakeSendPolicy(shakeCount, rawTypes.length, scene);
|
||||
}
|
||||
|
||||
function invalidMessageShape(message: string): MessageElementValidationError {
|
||||
@@ -415,7 +443,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti
|
||||
// Some OneBot clients insert empty text between media as a separator.
|
||||
// Only the exact empty string is a no-op; malformed and whitespace text
|
||||
// must still pass through strict element validation.
|
||||
if (normalizeSegmentType(seg.type) === 'text' && data.text === '') {
|
||||
if (isExplicitEmptyTextPlaceholder(seg)) {
|
||||
log.debug('ignored explicit empty text placeholder in message segment array');
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -13,7 +13,7 @@ import {
|
||||
privateMessageEventName,
|
||||
} from '../message-id';
|
||||
import {
|
||||
assertWindowShakeMessageInput,
|
||||
assertOutboundMessageInput,
|
||||
MessageElementValidationError,
|
||||
parseMessage,
|
||||
} from '../message-parser';
|
||||
@@ -797,7 +797,7 @@ export async function sendPrivateMessage(
|
||||
if (tempGroupId !== undefined && !isTempReply) {
|
||||
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
||||
}
|
||||
assertWindowShakeMessageInput(
|
||||
assertOutboundMessageInput(
|
||||
message,
|
||||
autoEscape,
|
||||
tempGroupId === undefined ? 'direct-private' : 'group-temp',
|
||||
@@ -1034,7 +1034,7 @@ export async function sendGroupMessage(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
assertWindowShakeMessageInput(message, autoEscape, 'group');
|
||||
assertOutboundMessageInput(message, autoEscape, 'group');
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
@@ -1232,6 +1232,7 @@ export async function forwardSingleMessage(
|
||||
if (!event) throw new Error(`message not found: ${messageId}`);
|
||||
|
||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
const parsed = await parseMessage(content, false);
|
||||
if (parsed.length === 0) throw new Error('message has no content');
|
||||
|
||||
@@ -1528,7 +1529,7 @@ function assertForwardNodeMetadataIsScalar(
|
||||
}
|
||||
}
|
||||
|
||||
function assertNoWindowShakeInForwardInput(
|
||||
function assertForwardMessageInputPolicies(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
@@ -1544,7 +1545,7 @@ function assertNoWindowShakeInForwardInput(
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
if (event) {
|
||||
assertWindowShakeMessageInput(
|
||||
assertOutboundMessageInput(
|
||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||
false,
|
||||
'forward',
|
||||
@@ -1555,9 +1556,9 @@ function assertNoWindowShakeInForwardInput(
|
||||
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
if (isNestedNodeArray(content)) {
|
||||
assertNoWindowShakeInForwardInput(ref, content, depth + 1);
|
||||
assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||
} else {
|
||||
assertWindowShakeMessageInput(content, false, 'forward');
|
||||
assertOutboundMessageInput(content, false, 'forward');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1655,9 +1656,10 @@ async function parseForwardNodes(
|
||||
});
|
||||
|
||||
// Scan the complete raw tree before parsing any earlier node. Some segment
|
||||
// codecs perform identity lookups or HTTP signing, so discovering a later
|
||||
// window-shake segment during the normal loop would already be too late.
|
||||
assertNoWindowShakeInForwardInput(ref, messages, depth);
|
||||
// codecs perform identity lookups or HTTP signing, so discovering an
|
||||
// unsupported message combination during the normal loop would already be
|
||||
// too late.
|
||||
assertForwardMessageInputPolicies(ref, messages, depth);
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
for (const { nodeData } of prepared) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import {
|
||||
forwardSingleMessage,
|
||||
sendGroupForwardMessage,
|
||||
sendPrivateForwardMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
@@ -209,6 +210,58 @@ describe('forward — nested {type:"node"} content', () => {
|
||||
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
|
||||
});
|
||||
|
||||
it('rejects video with hidden siblings before uploading a forward', 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: 111,
|
||||
nickname: 'mixed-video',
|
||||
content: [
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: 'must not survive bot forwarding' } },
|
||||
],
|
||||
},
|
||||
}] as any)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
});
|
||||
|
||||
expect(uploadForwardNodes).not.toHaveBeenCalled();
|
||||
expect(sendGroupMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects hidden siblings before forwarding a cached video message', async () => {
|
||||
const sendGroupMessage = vi.fn();
|
||||
const findVideo = vi.fn();
|
||||
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any);
|
||||
const ctx = makeCtx(bridge);
|
||||
(ctx as any).messageStore = {
|
||||
findEvent: () => ({
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'cached-video-id' } },
|
||||
{ type: 'text', data: { text: 'must not survive bot forwarding' } },
|
||||
],
|
||||
}),
|
||||
};
|
||||
(ctx as any).mediaStore = { findVideo };
|
||||
|
||||
await expect(forwardSingleMessage(ctx, 77, { groupId: 12345 }))
|
||||
.rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'video',
|
||||
});
|
||||
|
||||
expect(findVideo).not.toHaveBeenCalled();
|
||||
expect(sendGroupMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects an unknown top-level entry before uploading valid siblings', async () => {
|
||||
const uploadForwardNodes = vi.fn(async () => 'RES');
|
||||
const sendGroupMessage = vi.fn();
|
||||
|
||||
@@ -2,12 +2,20 @@ 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 { deleteMessage, sendGroupMessage, setEssenceMessage } from '../src/modules/message-actions';
|
||||
import {
|
||||
deleteMessage,
|
||||
sendGroupMessage,
|
||||
sendPrivateMessage,
|
||||
setEssenceMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
import type { MessageMeta } from '../src/types';
|
||||
|
||||
function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceContext {
|
||||
function instanceContext(
|
||||
sendGroup: ReturnType<typeof vi.fn>,
|
||||
sendPrivate: ReturnType<typeof vi.fn> = vi.fn(),
|
||||
): OneBotInstanceContext {
|
||||
const bridge = {
|
||||
apis: { message: { sendGroup } },
|
||||
apis: { message: { sendGroup, sendPrivate } },
|
||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||
} as unknown as BridgeInterface;
|
||||
|
||||
@@ -27,6 +35,14 @@ function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceCon
|
||||
}
|
||||
|
||||
describe('outbound message validation at the Action boundary', () => {
|
||||
const sendReceipt = {
|
||||
messageId: 1,
|
||||
sequence: 100,
|
||||
clientSequence: 0,
|
||||
random: 1,
|
||||
timestamp: 1700000000,
|
||||
};
|
||||
|
||||
it('returns BAD_REQUEST and performs no send when a later segment is unknown', async () => {
|
||||
const bridgeSend = vi.fn();
|
||||
const ref = instanceContext(bridgeSend);
|
||||
@@ -95,6 +111,140 @@ describe('outbound message validation at the Action boundary', () => {
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects video mixed with other visible content before sending', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
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: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: 'must not become hidden content' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('video'),
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects mixed video content before resolving a later segment', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
const getGroupRecommendArk = vi.fn(async () => '{"app":"contact"}');
|
||||
const ref = instanceContext(bridgeSend);
|
||||
(ref.bridge.apis as any).contacts = { getGroupRecommendArk };
|
||||
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: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'contact', data: { type: 'group', id: 67890 } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(getGroupRecommendArk).not.toHaveBeenCalled();
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects multiple video segments before sending', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
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: 'video', data: { file: 'https://example.com/first.mp4' } },
|
||||
{ type: 'video', data: { file: 'https://example.com/second.mp4' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('video'),
|
||||
});
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects hidden content after a video in CQ string form', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
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: '[CQ:video,file=https://example.com/video.mp4]hidden text',
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
|
||||
expect(bridgeSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects video mixed with private-chat content before sending', async () => {
|
||||
const privateSend = vi.fn(async () => sendReceipt);
|
||||
const ref = instanceContext(vi.fn(), privateSend);
|
||||
const api = new ApiHandler({
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
|
||||
sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
} as ApiActionContext);
|
||||
|
||||
const response = await api.handle('send_private_msg', {
|
||||
user_id: 67890,
|
||||
message: [
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: 'must not become hidden content' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({
|
||||
status: 'failed',
|
||||
retcode: 1400,
|
||||
wording: expect.stringContaining('only segment'),
|
||||
});
|
||||
expect(privateSend).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps exact empty text placeholders compatible with a single video', async () => {
|
||||
const bridgeSend = vi.fn(async () => sendReceipt);
|
||||
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: '' } },
|
||||
{ type: 'video', data: { file: 'https://example.com/video.mp4' } },
|
||||
{ type: 'text', data: { text: '' } },
|
||||
],
|
||||
});
|
||||
|
||||
expect(response).toMatchObject({ status: 'ok', retcode: 0 });
|
||||
expect(bridgeSend).toHaveBeenCalledOnce();
|
||||
expect(bridgeSend.mock.calls[0]?.[1]).toMatchObject([{ type: 'video' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('server-sequence action validation', () => {
|
||||
|
||||
@@ -81,6 +81,22 @@ describe('private window shake messages', () => {
|
||||
expect(sendPrivate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('keeps empty text significant for the standalone window-shake policy', async () => {
|
||||
const sendPrivate = vi.fn(async () => ({ ...receipt, clientSequence: 9 }));
|
||||
const ctx = makeContext({ sendPrivate });
|
||||
|
||||
await expect(sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'poke', data: { type: 1 } },
|
||||
{ type: 'text', data: { text: '' } },
|
||||
], false)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
message: expect.stringContaining('only segment'),
|
||||
});
|
||||
|
||||
expect(sendPrivate).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects group window shakes before resolving an earlier segment', async () => {
|
||||
const sendGroup = vi.fn(async () => receipt);
|
||||
const ctx = makeContext({ sendGroup });
|
||||
|
||||
@@ -10,6 +10,7 @@ import type { BridgeContext } from './bridge-context';
|
||||
import { sysFaceStore } from './sys-face-store';
|
||||
import type { MessageElement } from './events';
|
||||
import {
|
||||
assertVideoSendPolicy,
|
||||
assertWindowShakeSendPolicy,
|
||||
assertValidMessageElements,
|
||||
MessageElementValidationError,
|
||||
@@ -458,6 +459,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
// preserves all-or-nothing semantics: a malformed later segment cannot make
|
||||
// an earlier media segment perform side effects before the send is rejected.
|
||||
assertValidMessageElements(elements, 'W');
|
||||
// Canonical MessageElements cannot contain empty text. OneBot's explicit
|
||||
// empty-text compatibility placeholders are removed before this boundary,
|
||||
// so the array length here is the effective on-wire segment count.
|
||||
assertVideoSendPolicy(
|
||||
elements.filter((element) => element.type === 'video').length,
|
||||
elements.length,
|
||||
);
|
||||
assertWindowShakeSendPolicy(
|
||||
elements.filter((element) => element.type === 'poke').length,
|
||||
elements.length,
|
||||
|
||||
@@ -67,6 +67,33 @@ export function assertWindowShakeSendPolicy(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* QQ clients treat a video as a standalone message: sibling elements remain
|
||||
* on the wire but are not rendered, and additional videos cannot be opened.
|
||||
* Reject that ambiguous wire shape instead of reporting a successful send
|
||||
* whose visible content differs from the caller's request.
|
||||
*/
|
||||
export function assertVideoSendPolicy(
|
||||
videoCount: number,
|
||||
effectiveSegmentCount: number,
|
||||
): void {
|
||||
if (videoCount === 0) return;
|
||||
if (videoCount !== 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message element "video" may appear only once in a message',
|
||||
'video',
|
||||
);
|
||||
}
|
||||
if (effectiveSegmentCount !== 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message element "video" must be the only segment in a message',
|
||||
'video',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
type ElementField<T extends MessageElementType> = Exclude<keyof MessageElementOf<T>, 'type'> & string;
|
||||
|
||||
export interface ElementSpec<T extends MessageElementType> {
|
||||
|
||||
Reference in new issue
Block a user