feat(onebot): support private window shake messages
Encode poke message segments as private window shake messages while keeping the dedicated send_poke action unchanged. Restrict window shakes to a single ordinary private-chat segment. Reject group, temporary-session, mixed-message, and forwarded usage before identity lookup, media upload, or packet transmission. Add full outbound request coverage, OneBot action regressions, and live private-chat verification for issue #259. Closes #259
This commit is contained in:
15 files changed
+529
-44
No files matched your search
@@ -11,7 +11,10 @@ import type {
|
||||
import type { FileExtra, PushMsg, PushMsgBody } from '@snowluma/proto-defs/message';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import type { ForwardNodePayload, MessageElement, MessageElementOf } from '@snowluma/protocol/events';
|
||||
import { MessageElementValidationError } from '@snowluma/protocol/element-manifest';
|
||||
import {
|
||||
assertWindowShakeSendPolicy,
|
||||
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';
|
||||
@@ -106,10 +109,10 @@ async function buildForwardPushBody(
|
||||
// long-msg upload service stores the bytes verbatim and the
|
||||
// receiver decodes them through the normal msg-push path.
|
||||
const sendCtx = groupId !== undefined
|
||||
? { bridge, groupId, forwardFake: true }
|
||||
? { bridge, groupId, forwardFake: true, scene: 'forward' as const }
|
||||
: userUid
|
||||
? { bridge, userUid, forwardFake: true }
|
||||
: { bridge, forwardFake: true };
|
||||
? { bridge, userUid, forwardFake: true, scene: 'forward' as const }
|
||||
: { bridge, forwardFake: true, scene: 'forward' as const };
|
||||
const elems = await buildSendElems(node.elements, sendCtx);
|
||||
const now = Math.floor(Date.now() / 1000);
|
||||
const random = Math.floor(Math.random() * 0x7fffffff) >>> 0;
|
||||
@@ -282,10 +285,24 @@ function assertPrivateForwardFileCapacity(nodes: ForwardNodePayload[]): void {
|
||||
}
|
||||
}
|
||||
|
||||
function assertNoWindowShakeInForward(nodes: ForwardNodePayload[]): void {
|
||||
for (const node of nodes) {
|
||||
assertWindowShakeSendPolicy(
|
||||
node.elements.filter((element) => element.type === 'poke').length,
|
||||
node.elements.length,
|
||||
'forward',
|
||||
);
|
||||
if (node.innerForward) assertNoWindowShakeInForward(node.innerForward);
|
||||
}
|
||||
}
|
||||
|
||||
export class ForwardApi {
|
||||
constructor(private readonly ctx: BridgeContext) { }
|
||||
|
||||
async upload(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> {
|
||||
// Reject the complete recursive tree before identity resolution, media
|
||||
// upload, or long-message upload. Window shake has no forward wire form.
|
||||
assertNoWindowShakeInForward(nodes);
|
||||
// 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.
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
SsoReadedReportResp,
|
||||
} from '@snowluma/proto-defs/oidb-actions/base';
|
||||
import { buildSendElems } from '@snowluma/protocol/element-builder';
|
||||
import { assertWindowShakeSendPolicy } from '@snowluma/protocol/element-manifest';
|
||||
import { FinalizeOfflineFile } from '@snowluma/protocol/oidb-services/group-file/finalize-offline-file';
|
||||
import type { MessageElement, QQEventVariant } from '@snowluma/protocol/events';
|
||||
import {
|
||||
@@ -280,7 +281,11 @@ export class MessageApi {
|
||||
async sendGroup(groupId: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, groupId });
|
||||
const protoElems = await buildSendElems(elements, {
|
||||
bridge: this.ctx as unknown as Bridge,
|
||||
groupId,
|
||||
scene: 'group',
|
||||
});
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
@@ -329,6 +334,11 @@ export class MessageApi {
|
||||
*/
|
||||
async sendPrivate(userUin: number, elements: MessageElement[]): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
assertWindowShakeSendPolicy(
|
||||
elements.filter((element) => element.type === 'poke').length,
|
||||
elements.length,
|
||||
'direct-private',
|
||||
);
|
||||
|
||||
let userUid = '';
|
||||
const hasMedia = elements.some(e => e.type === 'image' || e.type === 'record' || e.type === 'video');
|
||||
@@ -336,7 +346,11 @@ export class MessageApi {
|
||||
userUid = await this.ctx.resolveUserUid(userUin);
|
||||
}
|
||||
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
|
||||
const protoElems = await buildSendElems(elements, {
|
||||
bridge: this.ctx as unknown as Bridge,
|
||||
userUid,
|
||||
scene: 'direct-private',
|
||||
});
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
@@ -397,9 +411,18 @@ export class MessageApi {
|
||||
elements: MessageElement[],
|
||||
): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
assertWindowShakeSendPolicy(
|
||||
elements.filter((element) => element.type === 'poke').length,
|
||||
elements.length,
|
||||
'group-temp',
|
||||
);
|
||||
|
||||
const userUid = await this.ctx.resolveUserUid(userUin);
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
|
||||
const protoElems = await buildSendElems(elements, {
|
||||
bridge: this.ctx as unknown as Bridge,
|
||||
userUid,
|
||||
scene: 'group-temp',
|
||||
});
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
|
||||
@@ -70,6 +70,43 @@ function decodeLongMsgRequest(rawBytes: Uint8Array): LongMsgResult {
|
||||
}
|
||||
|
||||
describe('actions/forward — file segment inside forward node', () => {
|
||||
it('rejects a recursive window shake before identity resolution or upload', async () => {
|
||||
buildSendElemsMock.mockClear();
|
||||
const resolveUserUid = vi.fn();
|
||||
const uploadPrivate = vi.fn();
|
||||
const sendRawPacket = vi.fn();
|
||||
const bridge = mockBridge({
|
||||
resolveUserUid,
|
||||
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: 'image', url: 'base64://AQID' }],
|
||||
innerForward: [{
|
||||
userUin: 10002,
|
||||
nickname: 'bob',
|
||||
elements: [{ type: 'poke', subType: 1 }],
|
||||
}],
|
||||
}], undefined, 67890)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
});
|
||||
|
||||
expect(resolveUserUid).not.toHaveBeenCalled();
|
||||
expect(uploadPrivate).not.toHaveBeenCalled();
|
||||
expect(buildSendElemsMock).not.toHaveBeenCalled();
|
||||
expect(sendRawPacket).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('group forward sets forwardFake:true on the SendContext so transElem(24) is emitted', async () => {
|
||||
// Group case: the file element rides on elems[] as transElem(24).
|
||||
// The element-builder receives ctx.forwardFake=true so it knows to
|
||||
|
||||
@@ -75,6 +75,40 @@ describe('element-builder / rich card encoding', () => {
|
||||
});
|
||||
|
||||
describe('element-builder / commonElem.businessType per scene', () => {
|
||||
describe('private window shake', () => {
|
||||
it('encodes poke type 1 as CommonElem service 2 with the verified payload', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
[{ type: 'poke', subType: 1 }],
|
||||
{ bridge: fakeBridge, userUid: 'u_peer', scene: 'direct-private' },
|
||||
);
|
||||
|
||||
expect(commonElem(elem)).toMatchObject({
|
||||
serviceType: 2,
|
||||
businessType: 1,
|
||||
});
|
||||
expect(Array.from(commonElem(elem).pbElem)).toEqual([0x08, 0x01]);
|
||||
});
|
||||
|
||||
it('rejects mixed window-shake content before uploading an earlier media segment', async () => {
|
||||
vi.mocked(uploadImageMsgInfo).mockClear();
|
||||
|
||||
await expect(buildSendElems([
|
||||
{ type: 'image', url: 'file:///tmp/must-not-upload.png' },
|
||||
{ type: 'poke', subType: 1 },
|
||||
], {
|
||||
bridge: fakeBridge,
|
||||
userUid: 'u_peer',
|
||||
scene: 'direct-private',
|
||||
})).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
message: expect.stringContaining('only segment'),
|
||||
});
|
||||
|
||||
expect(uploadImageMsgInfo).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('image', () => {
|
||||
it('c2c → businessType 10', async () => {
|
||||
const [elem] = await buildSendElems(
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
import type { SendPacketResult } from '@snowluma/common/packet-sender';
|
||||
import type { SendMessageRequest, SendMessageResponse } from '@snowluma/proto-defs/action';
|
||||
import type { PokeExtra } from '@snowluma/proto-defs/element';
|
||||
import { IdentityService } from '@snowluma/protocol/identity-service';
|
||||
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { Bridge } from '../src/bridge/bridge';
|
||||
|
||||
describe('private window shake wire request', () => {
|
||||
it('routes poke type 1 through direct C2C with the verified CommonElem payload', async () => {
|
||||
class TestBridge extends Bridge {
|
||||
capturedBody: Uint8Array | null = null;
|
||||
|
||||
override async resolveUserUid(): Promise<string> {
|
||||
throw new Error('window shake must not resolve media identity');
|
||||
}
|
||||
|
||||
override async sendRawPacket(command: string, body: Uint8Array): Promise<SendPacketResult> {
|
||||
expect(command).toBe('MessageSvc.PbSendMsg');
|
||||
this.capturedBody = body;
|
||||
return {
|
||||
success: true,
|
||||
gotResponse: true,
|
||||
errorCode: 0,
|
||||
errorMessage: '',
|
||||
responseData: Buffer.from(protobuf_encode<SendMessageResponse>({
|
||||
result: 0,
|
||||
privateSequence: 88,
|
||||
timestamp1: 1_710_000_000,
|
||||
})),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const bridge = new TestBridge(IdentityService.memory('10000'));
|
||||
await bridge.apis.message.sendPrivate(1787882683, [{ type: 'poke', subType: 1 }]);
|
||||
|
||||
expect(bridge.capturedBody).toBeInstanceOf(Uint8Array);
|
||||
const request = protobuf_decode<SendMessageRequest>(bridge.capturedBody!);
|
||||
expect(request.routingHead?.c2c).toMatchObject({ uin: 1787882683 });
|
||||
expect(request.routingHead?.grp ?? undefined).toBeUndefined();
|
||||
expect(request.routingHead?.grpTmp ?? undefined).toBeUndefined();
|
||||
expect(request.contentHead).toMatchObject({ type: 1, c2cCmd: 11 });
|
||||
expect(request.contentHead?.subType ?? 0).toBe(0);
|
||||
|
||||
const elems = request.messageBody?.richText?.elems ?? [];
|
||||
expect(elems).toHaveLength(1);
|
||||
expect(elems[0]?.commonElem).toMatchObject({ serviceType: 2, businessType: 1 });
|
||||
const payload = elems[0]?.commonElem?.pbElem;
|
||||
expect(payload).toBeInstanceOf(Uint8Array);
|
||||
expect(Array.from(payload!)).toEqual([0x08, 0x01]);
|
||||
expect(protobuf_decode<PokeExtra>(payload!)).toEqual({ type: 1 });
|
||||
});
|
||||
|
||||
it('rejects mixed direct-private content before resolving media identity', async () => {
|
||||
const bridge = new Bridge(IdentityService.memory('10000'));
|
||||
const resolveUserUid = vi.spyOn(bridge, 'resolveUserUid').mockResolvedValue('u_peer');
|
||||
|
||||
await expect(bridge.apis.message.sendPrivate(1787882683, [
|
||||
{ type: 'image', url: 'file:///tmp/must-not-resolve.png' },
|
||||
{ type: 'poke', subType: 1 },
|
||||
])).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
});
|
||||
|
||||
expect(resolveUserUid).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects temp-session window shakes before resolving the peer UID', async () => {
|
||||
const bridge = new Bridge(IdentityService.memory('10000'));
|
||||
const resolveUserUid = vi.spyOn(bridge, 'resolveUserUid').mockResolvedValue('u_peer');
|
||||
|
||||
await expect(bridge.apis.message.sendGroupTempMessage(
|
||||
1787882683,
|
||||
941657197,
|
||||
[{ type: 'poke', subType: 1 }],
|
||||
)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
});
|
||||
|
||||
expect(resolveUserUid).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import type { MessageElement } from '@snowluma/protocol/events';
|
||||
import {
|
||||
assertWindowShakeSendPolicy,
|
||||
assertValidMessageElement,
|
||||
ELEMENT_MANIFEST,
|
||||
MessageElementValidationError,
|
||||
type OutboundMessageScene,
|
||||
} from '@snowluma/protocol/element-manifest';
|
||||
import { parseFromCQString } from './helper/cq';
|
||||
import { getElementCodec, intOr } from './event-converter/element-codecs';
|
||||
@@ -62,6 +64,47 @@ function isSegmentArray(val: unknown): val is MessageSegment[] {
|
||||
);
|
||||
}
|
||||
|
||||
function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): string[] {
|
||||
if (typeof message === 'string') {
|
||||
if (autoEscape) return ['text'];
|
||||
const types: string[] = [];
|
||||
let lastIndex = 0;
|
||||
for (const match of message.matchAll(CQ_REGEX)) {
|
||||
if (match.index! > lastIndex) types.push('text');
|
||||
types.push((match[1] ?? '').toLowerCase());
|
||||
lastIndex = match.index! + match[0].length;
|
||||
}
|
||||
if (lastIndex < message.length) types.push('text');
|
||||
return types;
|
||||
}
|
||||
if (Array.isArray(message)) {
|
||||
return message.flatMap((item) => {
|
||||
if (typeof item !== 'object' || item === null || Array.isArray(item)) return [];
|
||||
const type = (item as { type?: unknown }).type;
|
||||
return typeof type === 'string' ? [type.toLowerCase()] : [];
|
||||
});
|
||||
}
|
||||
if (typeof message === 'object' && message !== null) {
|
||||
const type = (message as { type?: unknown }).type;
|
||||
return typeof type === 'string' ? [type.toLowerCase()] : [];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reject unsupported window-shake inputs before parsers can resolve identities,
|
||||
* fetch cards, sign music, or perform any other externally visible work.
|
||||
*/
|
||||
export function assertWindowShakeMessageInput(
|
||||
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);
|
||||
}
|
||||
|
||||
function invalidMessageShape(message: string): MessageElementValidationError {
|
||||
return new MessageElementValidationError('MISSING_FIELD', message, undefined, 'message');
|
||||
}
|
||||
@@ -141,7 +184,7 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
assertScalarSegmentData(normalizedType, data);
|
||||
}
|
||||
|
||||
// 纯 OneBot 输入词:可执行的塌缩成 json/face;没有合法发送语义的 node / shake /
|
||||
// 纯 OneBot 输入词:可执行的塌缩成 json/face/poke;没有合法发送语义的 node /
|
||||
// anonymous 在这里明确拒绝。它们无收侧对应、无专属 wire 形态,故不进 codec 表。
|
||||
// 真实元素(收发同名)走下方的 ELEMENT_CODECS。
|
||||
switch (normalizedType) {
|
||||
@@ -289,8 +332,8 @@ export async function segmentToElement(type: string, data: Record<string, unknow
|
||||
return validatedOutboundElement({ type: 'face', faceId: 358 });
|
||||
}
|
||||
case 'shake': {
|
||||
// Window shake normalizes to poke, then the W-direction guard returns the
|
||||
// same explicit "use the dedicated poke Action" validation error.
|
||||
// Legacy OneBot window-shake sugar. The destination guard later limits
|
||||
// the normalized poke element to ordinary friend private messages.
|
||||
return validatedOutboundElement({ type: 'poke', subType: 1 });
|
||||
}
|
||||
case 'anonymous': {
|
||||
|
||||
@@ -11,7 +11,11 @@ import {
|
||||
hashMessageIdInt32,
|
||||
privateMessageEventName,
|
||||
} from '../message-id';
|
||||
import { MessageElementValidationError, parseMessage } from '../message-parser';
|
||||
import {
|
||||
assertWindowShakeMessageInput,
|
||||
MessageElementValidationError,
|
||||
parseMessage,
|
||||
} from '../message-parser';
|
||||
import type { MessageStore } from '../message-store';
|
||||
import { sameSelfSentMessage } from '../self-sent-event';
|
||||
import { hasAuthoritativeSequence, type JsonArray, type JsonObject, type JsonValue, type MessageMeta } from '../types';
|
||||
@@ -850,6 +854,11 @@ export async function sendPrivateMessage(
|
||||
if (tempGroupId !== undefined && !isTempReply) {
|
||||
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
||||
}
|
||||
assertWindowShakeMessageInput(
|
||||
message,
|
||||
autoEscape,
|
||||
tempGroupId === undefined ? 'direct-private' : 'group-temp',
|
||||
);
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
@@ -1045,6 +1054,7 @@ export async function sendGroupMessage(
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
): Promise<MessageSendResult> {
|
||||
assertWindowShakeMessageInput(message, autoEscape, 'group');
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
|
||||
@@ -1450,7 +1460,7 @@ function logSentMessage(isGroup: boolean, targetId: number, elements: MessageEle
|
||||
parts.push('[转发消息]');
|
||||
break;
|
||||
case 'poke':
|
||||
parts.push('[戳一戳]');
|
||||
parts.push('[窗口抖动]');
|
||||
break;
|
||||
case 'file':
|
||||
// Avoid the misleading "[空消息]" the user previously saw when
|
||||
@@ -1519,6 +1529,40 @@ function assertForwardNodeMetadataIsScalar(
|
||||
}
|
||||
}
|
||||
|
||||
function assertNoWindowShakeInForwardInput(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
depth = 0,
|
||||
): void {
|
||||
if (!Array.isArray(messages) || depth >= MAX_FORWARD_DEPTH) return;
|
||||
for (const item of messages) {
|
||||
const segment = asJsonObject(item);
|
||||
if (!segment) continue;
|
||||
const nodeData = segment.type === 'node' ? asJsonObject(segment.data) : segment;
|
||||
if (!nodeData) continue;
|
||||
|
||||
const messageId = parseForwardMessageId(nodeData.id ?? nodeData.message_id);
|
||||
if (messageId !== 0) {
|
||||
const event = ref.messageStore.findEvent(messageId);
|
||||
if (event) {
|
||||
assertWindowShakeMessageInput(
|
||||
(event.message ?? event.raw_message ?? '') as JsonValue,
|
||||
false,
|
||||
'forward',
|
||||
);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue;
|
||||
if (isNestedNodeArray(content)) {
|
||||
assertNoWindowShakeInForwardInput(ref, content, depth + 1);
|
||||
} else {
|
||||
assertWindowShakeMessageInput(content, false, 'forward');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function parseForwardNodes(
|
||||
ref: OneBotInstanceContext,
|
||||
messages: JsonValue,
|
||||
@@ -1611,6 +1655,11 @@ async function parseForwardNodes(
|
||||
return { segment, nodeData: segment };
|
||||
});
|
||||
|
||||
// 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);
|
||||
|
||||
const nodes: ForwardNodePayload[] = [];
|
||||
for (const { nodeData } of prepared) {
|
||||
|
||||
@@ -1742,7 +1791,7 @@ function elementPreview(element: MessageElement): string {
|
||||
case 'xml': return '[XML消息]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
case 'forward': return '[聊天记录]';
|
||||
case 'poke': return '[戳一戳]';
|
||||
case 'poke': return '[窗口抖动]';
|
||||
default: return '';
|
||||
}
|
||||
}
|
||||
|
||||
@@ -602,23 +602,16 @@ describe('parseMessage', () => {
|
||||
expect(result[0].faceId).toBe(358);
|
||||
});
|
||||
|
||||
it('rejects shake/poke with a dedicated-Action hint', async () => {
|
||||
it('parses poke and the legacy shake alias as window-shake elements', async () => {
|
||||
await expect(parseMessage(
|
||||
[{ type: 'poke', data: { type: 1 } }] as any,
|
||||
false,
|
||||
)).resolves.toEqual([{ type: 'poke', subType: 1 }]);
|
||||
|
||||
await expect(parseMessage(
|
||||
[{ type: 'shake', data: {} }] as any,
|
||||
false,
|
||||
)).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',
|
||||
});
|
||||
)).resolves.toEqual([{ type: 'poke', subType: 1 }]);
|
||||
});
|
||||
|
||||
it('rejects anonymous because it has no executable send semantics', async () => {
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import type { BridgeInterface } from '../../core/src/bridge/bridge-interface';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import {
|
||||
sendGroupMessage,
|
||||
sendPrivateForwardMessage,
|
||||
sendPrivateMessage,
|
||||
} from '../src/modules/message-actions';
|
||||
import { TempSessionStore } from '../src/temp-session-store';
|
||||
|
||||
const receipt = {
|
||||
messageId: 1,
|
||||
sequence: 100,
|
||||
clientSequence: 0,
|
||||
random: 1,
|
||||
timestamp: 1_700_000_000,
|
||||
};
|
||||
|
||||
function makeContext(messageApi: Record<string, ReturnType<typeof vi.fn>>): OneBotInstanceContext {
|
||||
return {
|
||||
uin: '10001',
|
||||
selfId: 10001,
|
||||
bridge: {
|
||||
identity: { nickname: 'SnowLuma' },
|
||||
resolveUserUid: vi.fn(),
|
||||
apis: { message: messageApi },
|
||||
} as unknown as BridgeInterface,
|
||||
messageStore: {
|
||||
findEvent: () => null,
|
||||
findMeta: () => null,
|
||||
storeEvent: vi.fn(),
|
||||
} as never,
|
||||
cacheMessageMeta: vi.fn(),
|
||||
mediaStore: {} as never,
|
||||
tempSessions: new TempSessionStore(),
|
||||
musicSignUrl: '',
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
describe('private window shake messages', () => {
|
||||
it('sends a poke segment through the ordinary friend private path', async () => {
|
||||
const sendPrivate = vi.fn(async () => ({ ...receipt, clientSequence: 9 }));
|
||||
const ctx = makeContext({ sendPrivate });
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'poke', data: { type: 1 } },
|
||||
], false);
|
||||
|
||||
expect(sendPrivate).toHaveBeenCalledWith(67890, [
|
||||
{ type: 'poke', subType: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('normalizes the legacy shake segment to the same private element', async () => {
|
||||
const sendPrivate = vi.fn(async () => ({ ...receipt, clientSequence: 9 }));
|
||||
const ctx = makeContext({ sendPrivate });
|
||||
|
||||
await sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'shake', data: {} },
|
||||
], false);
|
||||
|
||||
expect(sendPrivate).toHaveBeenCalledWith(67890, [
|
||||
{ type: 'poke', subType: 1 },
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects mixed private content before resolving an earlier segment', async () => {
|
||||
const sendPrivate = vi.fn(async () => ({ ...receipt, clientSequence: 9 }));
|
||||
const ctx = makeContext({ sendPrivate });
|
||||
|
||||
await expect(sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'at', data: { qq: 12345 } },
|
||||
{ type: 'poke', data: { type: 1 } },
|
||||
], false)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
message: expect.stringContaining('only segment'),
|
||||
});
|
||||
|
||||
expect(ctx.bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
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 });
|
||||
|
||||
await expect(sendGroupMessage(ctx, 12345, [
|
||||
{ type: 'at', data: { qq: 12345 } },
|
||||
{ type: 'poke', data: { type: 1 } },
|
||||
], false)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
message: expect.stringContaining('direct private chat'),
|
||||
});
|
||||
|
||||
expect(ctx.bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
expect(sendGroup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects poke segments in group temporary sessions before calling the bridge', async () => {
|
||||
const sendGroupTempMessage = vi.fn(async () => ({ ...receipt, clientSequence: 9 }));
|
||||
const ctx = makeContext({ sendGroupTempMessage });
|
||||
ctx.tempSessions.record(67890, 12345);
|
||||
|
||||
await expect(sendPrivateMessage(ctx, 67890, [
|
||||
{ type: 'poke', data: { type: 1 } },
|
||||
], false, 12345)).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
message: expect.stringContaining('direct private chat'),
|
||||
});
|
||||
|
||||
expect(sendGroupTempMessage).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('rejects a later forward window shake before parsing an earlier node', async () => {
|
||||
const upload = vi.fn();
|
||||
const sendPrivate = vi.fn();
|
||||
const ctx = makeContext({ sendPrivate });
|
||||
(ctx.bridge.apis as unknown as Record<string, unknown>).forward = { upload };
|
||||
|
||||
await expect(sendPrivateForwardMessage(ctx, 67890, [
|
||||
{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 10001,
|
||||
nickname: 'alice',
|
||||
content: [{ type: 'at', data: { qq: 12345 } }],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'node',
|
||||
data: {
|
||||
user_id: 10002,
|
||||
nickname: 'bob',
|
||||
content: [{ type: 'poke', data: { type: 1 } }],
|
||||
},
|
||||
},
|
||||
])).rejects.toMatchObject({
|
||||
code: 'UNSENDABLE_TYPE',
|
||||
elementType: 'poke',
|
||||
});
|
||||
|
||||
expect(ctx.bridge.resolveUserUid).not.toHaveBeenCalled();
|
||||
expect(upload).not.toHaveBeenCalled();
|
||||
expect(sendPrivate).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -241,6 +241,11 @@ export interface CommonElem {
|
||||
businessType?: pb<3, uint_32>;
|
||||
}
|
||||
|
||||
/** Payload carried by CommonElem serviceType=2 for private window shakes. */
|
||||
export interface PokeExtra {
|
||||
type?: pb<1, uint_32>;
|
||||
}
|
||||
|
||||
export interface GeneralFlags {
|
||||
bubbleDiyTextId?: pb<1, int_32>;
|
||||
groupFlagNew?: pb<2, int_32>;
|
||||
|
||||
@@ -2,7 +2,7 @@ import type {
|
||||
MarkdownData,
|
||||
MentionExtraSend,
|
||||
} from '@snowluma/proto-defs/action';
|
||||
import type { Elem, GroupFileExtra, MarketFacePbReserve, QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
|
||||
import type { Elem, GroupFileExtra, MarketFacePbReserve, PokeExtra, QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element';
|
||||
import { protobuf_encode } from '@snowluma/proton';
|
||||
import { randomUUID } from 'crypto';
|
||||
import { deflateSync } from 'zlib';
|
||||
@@ -10,8 +10,10 @@ import type { BridgeContext } from './bridge-context';
|
||||
import { sysFaceStore } from './sys-face-store';
|
||||
import type { MessageElement } from './events';
|
||||
import {
|
||||
assertWindowShakeSendPolicy,
|
||||
assertValidMessageElements,
|
||||
MessageElementValidationError,
|
||||
type OutboundMessageScene,
|
||||
} from './element-manifest';
|
||||
import { uploadImageMsgInfo } from './highway/image-upload';
|
||||
import { hexToBytes } from './highway/pipeline';
|
||||
@@ -24,6 +26,8 @@ export interface SendContext {
|
||||
bridge: BridgeContext;
|
||||
groupId?: number;
|
||||
userUid?: string;
|
||||
/** Explicit transport scene used by scene-limited message elements. */
|
||||
scene?: OutboundMessageScene;
|
||||
/**
|
||||
* Set by the forward-message upload path. When `true`, file segments
|
||||
* are encoded as receive-side wire shapes (group → `transElem(24)`,
|
||||
@@ -204,6 +208,17 @@ function makeMarkdownElem(element: MessageElement): ProtoElem {
|
||||
};
|
||||
}
|
||||
|
||||
function makePokeElem(element: MessageElement): ProtoElem {
|
||||
const pokeType = element.subType;
|
||||
return {
|
||||
commonElem: {
|
||||
serviceType: 2,
|
||||
pbElem: protobuf_encode<PokeExtra>({ type: pokeType }),
|
||||
businessType: pokeType,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Build a market-face (商城表情) wire element from the markers carried on the
|
||||
@@ -435,7 +450,7 @@ async function makeVideoElem(ctx: SendContext, element: MessageElement): Promise
|
||||
|
||||
/**
|
||||
* Build proto Elem objects from an array of MessageElements.
|
||||
* Supports: text, face, mface, at, reply, json, xml, markdown, image, record, video, forward.
|
||||
* Supports: text, face, mface, at, reply, json, xml, markdown, image, record, video, forward, poke.
|
||||
* Image, record and video elements trigger NTV2 highway upload via the SendContext.
|
||||
*/
|
||||
export async function buildSendElems(elements: MessageElement[], ctx?: SendContext): Promise<ProtoElem[]> {
|
||||
@@ -443,6 +458,11 @@ 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');
|
||||
assertWindowShakeSendPolicy(
|
||||
elements.filter((element) => element.type === 'poke').length,
|
||||
elements.length,
|
||||
ctx?.scene,
|
||||
);
|
||||
for (const element of elements) {
|
||||
if ((element.type === 'image' || element.type === 'record' || element.type === 'video') && !ctx) {
|
||||
throw new MessageElementValidationError(
|
||||
@@ -478,6 +498,10 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte
|
||||
result.push(makeFaceElem(elem.faceId, ctx));
|
||||
break;
|
||||
|
||||
case 'poke':
|
||||
result.push(makePokeElem(elem));
|
||||
break;
|
||||
|
||||
case 'mface':
|
||||
result.push(makeMarketFaceElem(elem));
|
||||
break;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* 消息元素「四向」对账清单 —— 单一权威。
|
||||
*
|
||||
* 一种消息元素(文字/图片/戳一戳/商城表情…)要在两个流向、共 4 处处理,散在
|
||||
* 一种消息元素(文字/图片/窗口抖动/商城表情…)要在两个流向、共 4 处处理,散在
|
||||
* 不同文件、不同包。历史上这 4 处各写各的、没人对账,导致字段名对不上、漏写
|
||||
* 方向无人知(都走运行时兜底 `default`,悄悄失败)。
|
||||
*
|
||||
@@ -37,6 +37,36 @@ export type ElementDirection = (typeof ELEMENT_DIRECTIONS)[number];
|
||||
|
||||
export type DirectionSupport = 'yes' | 'no' | 'by-design-no';
|
||||
|
||||
/** The outbound transport selected before any resolver, upload, or packet send. */
|
||||
export type OutboundMessageScene = 'direct-private' | 'group' | 'group-temp' | 'forward';
|
||||
|
||||
/**
|
||||
* Window shake is an action-like CommonElem, not ordinary message content.
|
||||
* Keep its narrow send contract in the protocol package so every caller
|
||||
* rejects unsupported destinations and mixed payloads before side effects.
|
||||
*/
|
||||
export function assertWindowShakeSendPolicy(
|
||||
windowShakeCount: number,
|
||||
segmentCount: number,
|
||||
scene?: OutboundMessageScene,
|
||||
): void {
|
||||
if (windowShakeCount === 0) return;
|
||||
if (scene !== 'direct-private') {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message element "poke" can only be sent in a direct private chat',
|
||||
'poke',
|
||||
);
|
||||
}
|
||||
if (windowShakeCount !== 1 || segmentCount !== 1) {
|
||||
throw new MessageElementValidationError(
|
||||
'UNSENDABLE_TYPE',
|
||||
'message element "poke" must be the only segment in a private window-shake request',
|
||||
'poke',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
type ElementField<T extends MessageElementType> = Exclude<keyof MessageElementOf<T>, 'type'> & string;
|
||||
|
||||
export interface ElementSpec<T extends MessageElementType> {
|
||||
@@ -138,10 +168,10 @@ export const ELEMENT_MANIFEST = {
|
||||
note: 'W 特殊:live-send 在 OneBot 层被拆走走独立上传管线,仅 forwardFake 时落 transElem(24)',
|
||||
},
|
||||
poke: {
|
||||
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'by-design-no' },
|
||||
directions: { D: 'yes', S: 'yes', P: 'yes', W: 'yes' },
|
||||
fields: fieldsFor<'poke'>()(['subType']),
|
||||
requiredFields: ['subType'],
|
||||
note: 'P 仅负责把 OneBot 段规范化为 subType;W 会明确拒绝,因为 QQ 不允许戳一戳作为消息元素发送。请使用独立 poke Action',
|
||||
note: 'W 仅支持普通好友私聊窗口抖动;send_poke Action 仍表示拍一拍',
|
||||
},
|
||||
markdown: {
|
||||
directions: { D: 'no', S: 'no', P: 'yes', W: 'yes' },
|
||||
@@ -429,11 +459,9 @@ export function assertValidMessageElement(
|
||||
const spec = ELEMENT_MANIFEST[type];
|
||||
|
||||
if (direction && spec.directions[direction] !== 'yes') {
|
||||
const hint = type === 'poke'
|
||||
? 'use the dedicated poke Action instead'
|
||||
: type === 'flash_file'
|
||||
? 'use the send_flash_msg Action instead'
|
||||
: `direction ${direction} is not supported`;
|
||||
const hint = type === 'flash_file'
|
||||
? 'use the send_flash_msg Action instead'
|
||||
: `direction ${direction} is not supported`;
|
||||
throwValidation('UNSENDABLE_TYPE', `message element "${type}" cannot be sent; ${hint}`, type);
|
||||
}
|
||||
|
||||
@@ -485,9 +513,9 @@ export function typesForDirection(dir: ElementDirection): Set<string> {
|
||||
|
||||
/**
|
||||
* 发·解(P)侧还识别一批「纯 OneBot 输入词」:可执行的会塌缩成 json / face,
|
||||
* node 仅允许在 forward node list 的专用解析器中使用,shake / anonymous 因没有
|
||||
* 合法消息元素语义而返回 typed validation error。它们没有收侧对应,也没有专属
|
||||
* wire 形态,故不进本清单;对账 P 时须先从代码里剔除这些类型。
|
||||
* node 仅允许在 forward node list 的专用解析器中使用,shake 会规范化为 poke,
|
||||
* anonymous 因没有合法消息元素语义而返回 typed validation error。它们没有收侧
|
||||
* 对应,也没有专属 wire 形态,故不进本清单;对账 P 时须先从代码里剔除这些类型。
|
||||
*/
|
||||
export const INPUT_SUGAR_SEGMENTS: ReadonlySet<string> = new Set([
|
||||
'node', 'share', 'music', 'location', 'contact', 'rps', 'dice', 'shake', 'anonymous',
|
||||
|
||||
@@ -149,7 +149,7 @@ export interface FileElement {
|
||||
sha1Hex?: string;
|
||||
}
|
||||
|
||||
/** Receive-side representation only; sending uses the dedicated poke Action. */
|
||||
/** Window-shake element; outbound use is limited to ordinary friend C2C. */
|
||||
export interface PokeElement {
|
||||
type: 'poke';
|
||||
subType: number;
|
||||
|
||||
@@ -124,7 +124,7 @@ function renderSegment(type: string, data: Record<string, unknown>): string {
|
||||
case 'xml': return '[XML]';
|
||||
case 'markdown': return '[Markdown]';
|
||||
case 'forward': return '[聊天记录]';
|
||||
case 'poke': return '[戳一戳]';
|
||||
case 'poke': return '[窗口抖动]';
|
||||
case 'flash_file': {
|
||||
const title = data.title ? String(data.title) : '';
|
||||
return title ? `[闪传文件:${truncate(title, 20)}]` : '[闪传文件]';
|
||||
|
||||
@@ -48,8 +48,6 @@ describe('element-manifest 对账(protocol 侧:D 收·解 / W 发·打包)
|
||||
it('W:element-builder 的 switch 分支 == 清单声明的 W=yes', () => {
|
||||
const src = readSrc('../src/element-builder.ts');
|
||||
const handled = extractTypes(src, /case\s*'([A-Za-z0-9_]+)'\s*:/g);
|
||||
// poke 按设计不支持发送(QQ 限制),element-builder 必须没有 poke 分支。
|
||||
expect(handled).not.toContain('poke');
|
||||
expect(handled).toEqual(sorted(typesForDirection('W')));
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user