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 { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||||
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
|
import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload';
|
||||||
|
import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload';
|
||||||
|
|
||||||
const fakeBridge = {} as any;
|
const fakeBridge = {} as any;
|
||||||
|
|
||||||
@@ -168,6 +169,63 @@ describe('element-builder / commonElem.businessType per scene', () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
describe('element-builder / all-message validation preflight', () => {
|
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 () => {
|
it('does not upload an early image when a later segment is unsendable', async () => {
|
||||||
vi.mocked(uploadImageMsgInfo).mockClear();
|
vi.mocked(uploadImageMsgInfo).mockClear();
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { createLogger } from '@snowluma/common/logger';
|
import { createLogger } from '@snowluma/common/logger';
|
||||||
import type { MessageElement } from '@snowluma/protocol/events';
|
import type { MessageElement } from '@snowluma/protocol/events';
|
||||||
import {
|
import {
|
||||||
|
assertVideoSendPolicy,
|
||||||
assertWindowShakeSendPolicy,
|
assertWindowShakeSendPolicy,
|
||||||
assertValidMessageElement,
|
assertValidMessageElement,
|
||||||
ELEMENT_MANIFEST,
|
ELEMENT_MANIFEST,
|
||||||
@@ -68,9 +69,22 @@ function normalizeSegmentType(type: string): string {
|
|||||||
return type.toLowerCase();
|
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 (typeof message === 'string') {
|
||||||
if (autoEscape) return ['text'];
|
if (autoEscape) return { rawTypes: ['text'], effectiveVideoTypes: ['text'] };
|
||||||
const types: string[] = [];
|
const types: string[] = [];
|
||||||
let lastIndex = 0;
|
let lastIndex = 0;
|
||||||
for (const match of message.matchAll(CQ_REGEX)) {
|
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;
|
lastIndex = match.index! + match[0].length;
|
||||||
}
|
}
|
||||||
if (lastIndex < message.length) types.push('text');
|
if (lastIndex < message.length) types.push('text');
|
||||||
return types;
|
return { rawTypes: types, effectiveVideoTypes: types };
|
||||||
}
|
}
|
||||||
if (Array.isArray(message)) {
|
if (Array.isArray(message)) {
|
||||||
return message.flatMap((item) => {
|
const rawTypes: string[] = [];
|
||||||
if (typeof item !== 'object' || item === null || Array.isArray(item)) return [];
|
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;
|
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) {
|
if (typeof message === 'object' && message !== null) {
|
||||||
const type = (message as { type?: unknown }).type;
|
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,
|
* Reject unsupported message combinations before parsers can resolve
|
||||||
* fetch cards, sign music, or perform any other externally visible work.
|
* identities, fetch cards, sign music, or perform any other externally
|
||||||
|
* visible work.
|
||||||
*/
|
*/
|
||||||
export function assertWindowShakeMessageInput(
|
export function assertOutboundMessageInput(
|
||||||
message: JsonValue,
|
message: JsonValue,
|
||||||
autoEscape: boolean,
|
autoEscape: boolean,
|
||||||
scene: OutboundMessageScene,
|
scene: OutboundMessageScene,
|
||||||
): void {
|
): void {
|
||||||
const types = outboundInputSegmentTypes(message, autoEscape);
|
const { rawTypes, effectiveVideoTypes } = outboundInputSegmentSummary(message, autoEscape);
|
||||||
const shakeCount = types.filter((type) => type === 'poke' || type === 'shake').length;
|
assertVideoSendPolicy(
|
||||||
assertWindowShakeSendPolicy(shakeCount, types.length, scene);
|
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 {
|
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.
|
// Some OneBot clients insert empty text between media as a separator.
|
||||||
// Only the exact empty string is a no-op; malformed and whitespace text
|
// Only the exact empty string is a no-op; malformed and whitespace text
|
||||||
// must still pass through strict element validation.
|
// 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');
|
log.debug('ignored explicit empty text placeholder in message segment array');
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ import {
|
|||||||
privateMessageEventName,
|
privateMessageEventName,
|
||||||
} from '../message-id';
|
} from '../message-id';
|
||||||
import {
|
import {
|
||||||
assertWindowShakeMessageInput,
|
assertOutboundMessageInput,
|
||||||
MessageElementValidationError,
|
MessageElementValidationError,
|
||||||
parseMessage,
|
parseMessage,
|
||||||
} from '../message-parser';
|
} from '../message-parser';
|
||||||
@@ -797,7 +797,7 @@ export async function sendPrivateMessage(
|
|||||||
if (tempGroupId !== undefined && !isTempReply) {
|
if (tempGroupId !== undefined && !isTempReply) {
|
||||||
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
||||||
}
|
}
|
||||||
assertWindowShakeMessageInput(
|
assertOutboundMessageInput(
|
||||||
message,
|
message,
|
||||||
autoEscape,
|
autoEscape,
|
||||||
tempGroupId === undefined ? 'direct-private' : 'group-temp',
|
tempGroupId === undefined ? 'direct-private' : 'group-temp',
|
||||||
@@ -1034,7 +1034,7 @@ export async function sendGroupMessage(
|
|||||||
message: JsonValue,
|
message: JsonValue,
|
||||||
autoEscape: boolean,
|
autoEscape: boolean,
|
||||||
): Promise<MessageSendResult> {
|
): Promise<MessageSendResult> {
|
||||||
assertWindowShakeMessageInput(message, autoEscape, 'group');
|
assertOutboundMessageInput(message, autoEscape, 'group');
|
||||||
const elements = await parseMessage(message, autoEscape, {
|
const elements = await parseMessage(message, autoEscape, {
|
||||||
resolveReplySequence: (replyMessageId) => {
|
resolveReplySequence: (replyMessageId) => {
|
||||||
return ref.messageStore.resolveReplySequence(true, groupId, 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}`);
|
if (!event) throw new Error(`message not found: ${messageId}`);
|
||||||
|
|
||||||
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
const content = (event.message ?? event.raw_message ?? '') as JsonValue;
|
||||||
|
assertOutboundMessageInput(content, false, 'forward');
|
||||||
const parsed = await parseMessage(content, false);
|
const parsed = await parseMessage(content, false);
|
||||||
if (parsed.length === 0) throw new Error('message has no content');
|
if (parsed.length === 0) throw new Error('message has no content');
|
||||||
|
|
||||||
@@ -1528,7 +1529,7 @@ function assertForwardNodeMetadataIsScalar(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function assertNoWindowShakeInForwardInput(
|
function assertForwardMessageInputPolicies(
|
||||||
ref: OneBotInstanceContext,
|
ref: OneBotInstanceContext,
|
||||||
messages: JsonValue,
|
messages: JsonValue,
|
||||||
depth = 0,
|
depth = 0,
|
||||||
@@ -1544,7 +1545,7 @@ function assertNoWindowShakeInForwardInput(
|
|||||||
if (messageId !== 0) {
|
if (messageId !== 0) {
|
||||||
const event = ref.messageStore.findEvent(messageId);
|
const event = ref.messageStore.findEvent(messageId);
|
||||||
if (event) {
|
if (event) {
|
||||||
assertWindowShakeMessageInput(
|
assertOutboundMessageInput(
|
||||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||||
false,
|
false,
|
||||||
'forward',
|
'forward',
|
||||||
@@ -1555,9 +1556,9 @@ function assertNoWindowShakeInForwardInput(
|
|||||||
|
|
||||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||||
if (isNestedNodeArray(content)) {
|
if (isNestedNodeArray(content)) {
|
||||||
assertNoWindowShakeInForwardInput(ref, content, depth + 1);
|
assertForwardMessageInputPolicies(ref, content, depth + 1);
|
||||||
} else {
|
} 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
|
// Scan the complete raw tree before parsing any earlier node. Some segment
|
||||||
// codecs perform identity lookups or HTTP signing, so discovering a later
|
// codecs perform identity lookups or HTTP signing, so discovering an
|
||||||
// window-shake segment during the normal loop would already be too late.
|
// unsupported message combination during the normal loop would already be
|
||||||
assertNoWindowShakeInForwardInput(ref, messages, depth);
|
// too late.
|
||||||
|
assertForwardMessageInputPolicies(ref, messages, depth);
|
||||||
|
|
||||||
const nodes: ForwardNodePayload[] = [];
|
const nodes: ForwardNodePayload[] = [];
|
||||||
for (const { nodeData } of prepared) {
|
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 { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||||
import {
|
import {
|
||||||
|
forwardSingleMessage,
|
||||||
sendGroupForwardMessage,
|
sendGroupForwardMessage,
|
||||||
sendPrivateForwardMessage,
|
sendPrivateForwardMessage,
|
||||||
} from '../src/modules/message-actions';
|
} 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' }]);
|
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 () => {
|
it('rejects an unknown top-level entry before uploading valid siblings', async () => {
|
||||||
const uploadForwardNodes = vi.fn(async () => 'RES');
|
const uploadForwardNodes = vi.fn(async () => 'RES');
|
||||||
const sendGroupMessage = vi.fn();
|
const sendGroupMessage = vi.fn();
|
||||||
|
|||||||
@@ -2,12 +2,20 @@ import { describe, expect, it, vi } from 'vitest';
|
|||||||
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
|
||||||
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
|
||||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
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';
|
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 = {
|
const bridge = {
|
||||||
apis: { message: { sendGroup } },
|
apis: { message: { sendGroup, sendPrivate } },
|
||||||
resolveUserUid: vi.fn(async () => 'u_peer'),
|
resolveUserUid: vi.fn(async () => 'u_peer'),
|
||||||
} as unknown as BridgeInterface;
|
} as unknown as BridgeInterface;
|
||||||
|
|
||||||
@@ -27,6 +35,14 @@ function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceCon
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('outbound message validation at the Action boundary', () => {
|
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 () => {
|
it('returns BAD_REQUEST and performs no send when a later segment is unknown', async () => {
|
||||||
const bridgeSend = vi.fn();
|
const bridgeSend = vi.fn();
|
||||||
const ref = instanceContext(bridgeSend);
|
const ref = instanceContext(bridgeSend);
|
||||||
@@ -95,6 +111,140 @@ describe('outbound message validation at the Action boundary', () => {
|
|||||||
});
|
});
|
||||||
expect(bridgeSend).not.toHaveBeenCalled();
|
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', () => {
|
describe('server-sequence action validation', () => {
|
||||||
|
|||||||
@@ -81,6 +81,22 @@ describe('private window shake messages', () => {
|
|||||||
expect(sendPrivate).not.toHaveBeenCalled();
|
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 () => {
|
it('rejects group window shakes before resolving an earlier segment', async () => {
|
||||||
const sendGroup = vi.fn(async () => receipt);
|
const sendGroup = vi.fn(async () => receipt);
|
||||||
const ctx = makeContext({ sendGroup });
|
const ctx = makeContext({ sendGroup });
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ import type { BridgeContext } from './bridge-context';
|
|||||||
import { sysFaceStore } from './sys-face-store';
|
import { sysFaceStore } from './sys-face-store';
|
||||||
import type { MessageElement } from './events';
|
import type { MessageElement } from './events';
|
||||||
import {
|
import {
|
||||||
|
assertVideoSendPolicy,
|
||||||
assertWindowShakeSendPolicy,
|
assertWindowShakeSendPolicy,
|
||||||
assertValidMessageElements,
|
assertValidMessageElements,
|
||||||
MessageElementValidationError,
|
MessageElementValidationError,
|
||||||
@@ -458,6 +459,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
|||||||
// preserves all-or-nothing semantics: a malformed later segment cannot make
|
// preserves all-or-nothing semantics: a malformed later segment cannot make
|
||||||
// an earlier media segment perform side effects before the send is rejected.
|
// an earlier media segment perform side effects before the send is rejected.
|
||||||
assertValidMessageElements(elements, 'W');
|
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(
|
assertWindowShakeSendPolicy(
|
||||||
elements.filter((element) => element.type === 'poke').length,
|
elements.filter((element) => element.type === 'poke').length,
|
||||||
elements.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;
|
type ElementField<T extends MessageElementType> = Exclude<keyof MessageElementOf<T>, 'type'> & string;
|
||||||
|
|
||||||
export interface ElementSpec<T extends MessageElementType> {
|
export interface ElementSpec<T extends MessageElementType> {
|
||||||
|
|||||||
Reference in new issue
Block a user