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
@@ -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 '';
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user