feat(onebot): reply into group temp sessions (临时会话) (#212)
send_private_msg / send_msg can now reply to a group temp-session message by passing the source group_id. Inbound temp messages surface their source group on sender.group_id; a reply is only made into a temp session the bot has an inbound record of. Group temp replies route through RoutingHead.grpTmp (field 3).
This commit is contained in:
19 files changed
+311
-15
No files matched your search
@@ -219,6 +219,54 @@ export class MessageApi {
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reply into an existing group temp session (临时会话). Wire primitive only —
|
||||
* it does NOT gate; the caller verifies the session before calling. Routes
|
||||
* through `grpTmp` (RoutingHead field 3) with { groupUin, toUid } and a normal
|
||||
* c2c content head.
|
||||
*/
|
||||
async sendGroupTempMessage(
|
||||
userUin: number,
|
||||
groupUin: number,
|
||||
elements: MessageElement[],
|
||||
): Promise<SendMessageReceipt> {
|
||||
if (elements.length === 0) throw new Error('message is empty');
|
||||
|
||||
const userUid = await this.ctx.resolveUserUid(userUin);
|
||||
const protoElems = await buildSendElems(elements, { bridge: this.ctx as unknown as Bridge, userUid });
|
||||
const random = this.ctx.nextMessageRandom();
|
||||
const clientSeq = this.ctx.nextClientSequence();
|
||||
|
||||
const request = protobuf_encode<SendMessageRequest>({
|
||||
routingHead: {
|
||||
grpTmp: { groupUin: BigInt(groupUin), toUid: userUid },
|
||||
},
|
||||
contentHead: { type: 1, subType: 0, c2cCmd: 11 },
|
||||
messageBody: { richText: { elems: protoElems } },
|
||||
clientSequence: clientSeq,
|
||||
random,
|
||||
syncCookie: new Uint8Array(0),
|
||||
via: 0,
|
||||
dataStatist: 0,
|
||||
ctrl: { msgFlag: Math.floor(Date.now() / 1000) },
|
||||
multiSendSeq: 0,
|
||||
});
|
||||
|
||||
const result = await this.ctx.sendRawPacket(SEND_MSG_CMD, request);
|
||||
if (!result.success || !result.gotResponse || !result.responseData) {
|
||||
throw new Error(`send temp message failed: ${result.errorMessage || 'no response'}`);
|
||||
}
|
||||
const response = protobuf_decode<SendMessageResponse>(result.responseData);
|
||||
if (!response) throw new Error('failed to decode SendMessageResponse');
|
||||
if (response.result != null && response.result !== 0) {
|
||||
throw new Error(`send temp message rejected: result=${response.result} err=${response.errMsg ?? ''}`);
|
||||
}
|
||||
const seq = response.privateSequence ?? 0;
|
||||
const messageId = (random & 0x7FFFFFFF) || seq;
|
||||
const timestamp = response.timestamp1 ?? Math.floor(Date.now() / 1000);
|
||||
return { messageId, sequence: seq, clientSequence: clientSeq, random, timestamp };
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a c2c file as a chat message.
|
||||
*
|
||||
|
||||
@@ -7202,6 +7202,15 @@
|
||||
"description": "OneBot message: string | segment[] | object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "int",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "auto_escape",
|
||||
"type": "bool",
|
||||
@@ -7224,6 +7233,10 @@
|
||||
"message": {
|
||||
"description": "OneBot message: string | segment[] | object"
|
||||
},
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"auto_escape": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
|
||||
@@ -7205,6 +7205,15 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"description": "OneBot message: string | segment[] | object"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "group_id",
|
||||
"type": "int",
|
||||
"required": false,
|
||||
"schema": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "auto_escape",
|
||||
"type": "bool",
|
||||
@@ -7227,6 +7236,10 @@ export const ACTIONS: CatalogAction[] = [
|
||||
"message": {
|
||||
"description": "OneBot message: string | segment[] | object"
|
||||
},
|
||||
"group_id": {
|
||||
"type": "integer",
|
||||
"minimum": 0
|
||||
},
|
||||
"auto_escape": {
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
|
||||
@@ -52,13 +52,17 @@ export const actions = [
|
||||
auto_escape: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
if (p.message_type === 'group' || p.group_id !== undefined) {
|
||||
// Group temp-session reply: message_type=private with BOTH a user_id and
|
||||
// a group_id (the source group). Detect it first so a group_id here
|
||||
// doesn't get misrouted to a group message.
|
||||
const isTempReply = p.message_type === 'private' && p.user_id !== undefined && p.group_id !== undefined;
|
||||
if (!isTempReply && (p.message_type === 'group' || p.group_id !== undefined)) {
|
||||
if (p.group_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
|
||||
const result = await ctx.sendGroupMessage(p.group_id, p.message, p.auto_escape);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
}
|
||||
if (p.user_id === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, isTempReply ? p.group_id : undefined);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
@@ -67,9 +71,19 @@ export const actions = [
|
||||
name: 'send_private_msg',
|
||||
summary: '发送私聊消息',
|
||||
returns: '{ message_id: number }',
|
||||
params: { user_id: f.userId(), message: f.message(), auto_escape: f.bool().default(false) },
|
||||
params: {
|
||||
user_id: f.userId(),
|
||||
message: f.message(),
|
||||
// Optional source group: reply into that group's temp session (临时会话)
|
||||
// instead of a friend chat. int({min:0}) rather than groupId (which
|
||||
// rejects 0): a client that fills every field with group_id:0 must keep
|
||||
// working as a plain private send, so 0/absent means "no temp session".
|
||||
group_id: f.int({ min: 0 }).optional(),
|
||||
auto_escape: f.bool().default(false),
|
||||
},
|
||||
run: async (p, ctx) => {
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape);
|
||||
const tempGroupId = p.group_id && p.group_id > 0 ? p.group_id : undefined;
|
||||
const result = await ctx.sendPrivateMessage(p.user_id, p.message, p.auto_escape, tempGroupId);
|
||||
return okResponse({ message_id: result.messageId });
|
||||
},
|
||||
}),
|
||||
|
||||
@@ -32,7 +32,7 @@ export interface ApiActionContext {
|
||||
isOnline: () => boolean;
|
||||
getMessage: (messageId: number) => JsonObject | null;
|
||||
getMessageMeta: (messageId: number) => MessageMeta | null;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean, tempGroupId?: number) => Promise<MessageSendResult>;
|
||||
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
|
||||
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
|
||||
canSendImage: () => boolean;
|
||||
|
||||
@@ -34,6 +34,18 @@ async function convertPrivateMessage(
|
||||
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
|
||||
);
|
||||
const segments = await toSegments(ctx, event.elements, false, event.senderUin);
|
||||
const sender: JsonObject = {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
};
|
||||
// A temp (group-originated) message carries its source group so a client can
|
||||
// reply via send_private_msg(user_id, group_id=sender.group_id). Mirrors
|
||||
// go-cqhttp / NapCat, which expose it on sender.group_id.
|
||||
if (subType === 'group' && 'groupId' in event && event.groupId > 0) {
|
||||
sender.group_id = event.groupId;
|
||||
}
|
||||
return message(ctx, event, postType, {
|
||||
message_type: 'private',
|
||||
sub_type: subType,
|
||||
@@ -43,12 +55,7 @@ async function convertPrivateMessage(
|
||||
message: segments,
|
||||
raw_message: segmentsToRawMessage(segments),
|
||||
font: 0,
|
||||
sender: {
|
||||
user_id: event.senderUin,
|
||||
nickname: event.senderNick,
|
||||
sex: 'unknown',
|
||||
age: 0,
|
||||
},
|
||||
sender,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
|
||||
disposers.push(
|
||||
ctx.bridge.events.on('temp_message', async (event) => {
|
||||
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
|
||||
// Record this group temp session so a later reply is limited to sessions
|
||||
// the peer opened.
|
||||
ctx.tempSessions.record(event.senderUin, event.groupId);
|
||||
await convertAndDispatch(ctx, log, event);
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ApiActionContext } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import type { MediaStore } from './media-store';
|
||||
import type { MessageStore } from './message-store';
|
||||
import type { TempSessionStore } from './temp-session-store';
|
||||
import {
|
||||
getDownloadRKeys,
|
||||
getFriendList,
|
||||
@@ -46,6 +47,8 @@ export interface OneBotInstanceContext {
|
||||
messageStore: MessageStore;
|
||||
mediaStore: MediaStore;
|
||||
reactionStore: ReactionStore;
|
||||
/** Group temp-session records — see {@link TempSessionStore}. */
|
||||
tempSessions: TempSessionStore;
|
||||
converterCtx: ConverterContext;
|
||||
config: OneBotConfig;
|
||||
musicSignUrl?: string;
|
||||
@@ -65,7 +68,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
|
||||
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
|
||||
canSendImage: () => true,
|
||||
canSendRecord: () => true,
|
||||
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
|
||||
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
|
||||
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
|
||||
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
|
||||
getFriendList: () => getFriendList(bridge),
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ApiHandler, type ActionObserver } from './api-handler';
|
||||
import type { ConverterContext } from './event-converter';
|
||||
import { registerEventPipeline } from './event-pipeline';
|
||||
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
|
||||
import { TempSessionStore } from './temp-session-store';
|
||||
import { RKeyCache } from './instance-rkey';
|
||||
import type { GlobalSettings } from './global-config';
|
||||
import { MediaIndexer } from './media-indexer';
|
||||
@@ -116,6 +117,7 @@ export class OneBotInstance {
|
||||
messageStore: this.messageStore,
|
||||
mediaStore: this.mediaStore,
|
||||
reactionStore: this.reactionStore,
|
||||
tempSessions: new TempSessionStore(),
|
||||
converterCtx: this.converterCtx,
|
||||
config,
|
||||
musicSignUrl: globalSettings.musicSignUrl,
|
||||
|
||||
@@ -546,7 +546,14 @@ export async function sendPrivateMessage(
|
||||
userId: number,
|
||||
message: JsonValue,
|
||||
autoEscape: boolean,
|
||||
/** When set, reply into this group's temp session instead of friend c2c. */
|
||||
tempGroupId?: number,
|
||||
): Promise<MessageSendResult> {
|
||||
// A temp-session reply is only allowed into a session the peer opened.
|
||||
const isTempReply = tempGroupId !== undefined && ref.tempSessions.has(userId, tempGroupId);
|
||||
if (tempGroupId !== undefined && !isTempReply) {
|
||||
throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`);
|
||||
}
|
||||
const elements = await parseMessage(message, autoEscape, {
|
||||
resolveReplySequence: (replyMessageId) => {
|
||||
return ref.messageStore.resolveReplySequence(false, userId, replyMessageId);
|
||||
@@ -639,12 +646,22 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
}
|
||||
|
||||
// Route text/media batches through the temp-session primitive when replying
|
||||
// passively, else the normal friend c2c path.
|
||||
const sendText = (elems: MessageElement[]) =>
|
||||
isTempReply && tempGroupId !== undefined
|
||||
? ref.bridge.apis.message.sendGroupTempMessage(userId, tempGroupId, elems)
|
||||
: ref.bridge.apis.message.sendPrivate(userId, elems);
|
||||
|
||||
let lastReceipt: Awaited<ReturnType<typeof ref.bridge.apis.message.sendPrivate>> | undefined;
|
||||
if (nonFileElements.length > 0) {
|
||||
try {
|
||||
lastReceipt = await ref.bridge.apis.message.sendPrivate(userId, nonFileElements);
|
||||
lastReceipt = await sendText(nonFileElements);
|
||||
logSentMessage(false, userId, nonFileElements);
|
||||
} catch (err) {
|
||||
// A temp-session reply can't fall back to the c2c file path (friend-only)
|
||||
// — surface the original error rather than mis-routing.
|
||||
if (tempGroupId !== undefined) throw err;
|
||||
// Highway upload failed — if a large video triggered it, fall back to
|
||||
// file upload for that element (private messages cannot carry file
|
||||
// elements through the element pipeline).
|
||||
@@ -661,6 +678,9 @@ export async function sendPrivateMessage(
|
||||
}
|
||||
}
|
||||
if (allFileElements.length > 0) {
|
||||
if (tempGroupId !== undefined) {
|
||||
throw new Error('temp-session reply does not support file or oversized-video segments');
|
||||
}
|
||||
const userUid = await ref.bridge.resolveUserUid(userId);
|
||||
if (!userUid) throw new Error(`c2c file send: could not resolve uid for user ${userId}`);
|
||||
for (const fileEl of allFileElements) {
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
/**
|
||||
* Records the group temp sessions the bot has received a message from, so a
|
||||
* reply can be limited to sessions the peer opened. Written only on the receive
|
||||
* path, read only on the send path. Keyed by `${userUin}:${groupUin}` — a user
|
||||
* may hold sessions from several groups. Entries expire after
|
||||
* {@link TEMP_SESSION_TTL_MS}.
|
||||
*/
|
||||
|
||||
/** Reply window: 7 days after the last inbound temp message. */
|
||||
export const TEMP_SESSION_TTL_MS = 7 * 24 * 60 * 60 * 1000;
|
||||
|
||||
export class TempSessionStore {
|
||||
/** key → expiry epoch ms. */
|
||||
private readonly sessions = new Map<string, number>();
|
||||
|
||||
private static key(userUin: number, groupUin: number): string {
|
||||
return `${userUin}:${groupUin}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Record (or refresh) an inbound temp session. Called from the receive path.
|
||||
* No-op without a source group (groupUin<=0) — the session stays receive-only.
|
||||
*/
|
||||
record(userUin: number, groupUin: number, now: number = Date.now()): void {
|
||||
if (userUin <= 0 || groupUin <= 0) return;
|
||||
// Opportunistically prune expired entries here — `has` only removes keys it
|
||||
// reads, so a stream of never-replied sessions would otherwise grow the map
|
||||
// unbounded.
|
||||
this.sweep(now);
|
||||
this.sessions.set(TempSessionStore.key(userUin, groupUin), now + TEMP_SESSION_TTL_MS);
|
||||
}
|
||||
|
||||
/** True iff a reply is allowed for this exact (user, group). Prunes on read. */
|
||||
has(userUin: number, groupUin: number, now: number = Date.now()): boolean {
|
||||
const key = TempSessionStore.key(userUin, groupUin);
|
||||
const expiresAt = this.sessions.get(key);
|
||||
if (expiresAt === undefined) return false;
|
||||
if (expiresAt <= now) {
|
||||
this.sessions.delete(key);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Drop all expired entries. `has` also prunes lazily. */
|
||||
sweep(now: number = Date.now()): void {
|
||||
for (const [key, expiresAt] of this.sessions) {
|
||||
if (expiresAt <= now) this.sessions.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,10 +109,13 @@ describe('convertEvent — message kinds', () => {
|
||||
expect(out!.post_type).toBe('message_sent');
|
||||
});
|
||||
|
||||
it('temp_message peer → post_type "message", sub_type "group"', async () => {
|
||||
it('temp_message peer → post_type "message", sub_type "group", sender.group_id set', async () => {
|
||||
const out = await convertEvent(bareCtx(), makeTempMessage(PEER_UIN));
|
||||
expect(out!.post_type).toBe('message');
|
||||
expect(out!.sub_type).toBe('group');
|
||||
// Source group is surfaced on sender.group_id so a client can reply via
|
||||
// send_private_msg(user_id, group_id=...).
|
||||
expect((out!.sender as { group_id?: number }).group_id).toBe(99999);
|
||||
});
|
||||
|
||||
it('temp_message self → post_type "message_sent"', async () => {
|
||||
|
||||
@@ -12,6 +12,7 @@ vi.mock('../src/event-converter', async () => {
|
||||
import { convertEvent, type ConverterContext } from '../src/event-converter';
|
||||
import { registerEventPipeline } from '../src/event-pipeline';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
import { TempSessionStore } from '../src/temp-session-store';
|
||||
import type {
|
||||
FriendMessage,
|
||||
GroupMessage,
|
||||
@@ -115,6 +116,7 @@ function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
|
||||
summarizeMessage: () => [],
|
||||
close: () => {},
|
||||
} as never,
|
||||
tempSessions: new TempSessionStore(),
|
||||
converterCtx,
|
||||
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
|
||||
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import { sendPrivateMessage } from '../src/modules/message-actions';
|
||||
import { TempSessionStore } from '../src/temp-session-store';
|
||||
import type { OneBotInstanceContext } from '../src/instance-context';
|
||||
|
||||
// The passive gate lives at the very top of sendPrivateMessage, before any
|
||||
// message parsing or network call. These tests exercise that gate directly:
|
||||
// a temp reply (tempGroupId set) into a session the peer never opened MUST be
|
||||
// refused, without ever reaching the send path. This is the structural
|
||||
// guarantee that the public build cannot initiate a temp session.
|
||||
|
||||
function refWith(store: TempSessionStore): OneBotInstanceContext {
|
||||
const sendGroupTempMessage = vi.fn();
|
||||
const sendPrivate = vi.fn();
|
||||
return {
|
||||
tempSessions: store,
|
||||
// If the gate ever let a send through, these would be called — the tests
|
||||
// assert they are NOT for the refused case.
|
||||
bridge: { apis: { message: { sendGroupTempMessage, sendPrivate } } },
|
||||
} as unknown as OneBotInstanceContext;
|
||||
}
|
||||
|
||||
describe('sendPrivateMessage temp-session gate (passive-only)', () => {
|
||||
it('refuses a temp reply to an unrecorded (user, group) and never sends', async () => {
|
||||
const store = new TempSessionStore();
|
||||
const ref = refWith(store);
|
||||
await expect(
|
||||
sendPrivateMessage(ref, 1001, [{ type: 'text', data: { text: 'hi' } }], false, /* tempGroupId */ 700),
|
||||
).rejects.toThrow(/passive-only|temp session/i);
|
||||
// The gate threw before any wire call.
|
||||
expect((ref.bridge.apis.message as { sendGroupTempMessage: ReturnType<typeof vi.fn> }).sendGroupTempMessage)
|
||||
.not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('refuses when a DIFFERENT group is recorded (exact (user, group) match required)', async () => {
|
||||
const store = new TempSessionStore();
|
||||
store.record(1001, 701); // user opened a session from group 701, not 700
|
||||
const ref = refWith(store);
|
||||
await expect(
|
||||
sendPrivateMessage(ref, 1001, [{ type: 'text', data: { text: 'hi' } }], false, 700),
|
||||
).rejects.toThrow(/passive-only|temp session/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { TempSessionStore, TEMP_SESSION_TTL_MS } from '../src/temp-session-store';
|
||||
|
||||
const T0 = 1_700_000_000_000;
|
||||
|
||||
describe('TempSessionStore (passive temp-session gate, #212-temp)', () => {
|
||||
it('a recorded session is authorized; an unrecorded one is NOT (the core gate)', () => {
|
||||
const s = new TempSessionStore();
|
||||
s.record(1001, 700, T0);
|
||||
// Recorded (user, group) → allowed.
|
||||
expect(s.has(1001, 700, T0)).toBe(true);
|
||||
// Never recorded → refused. This is what makes send passive-only: the bot
|
||||
// cannot reply to a (user, group) that never messaged it first.
|
||||
expect(s.has(1001, 701, T0)).toBe(false); // same user, different group
|
||||
expect(s.has(1002, 700, T0)).toBe(false); // different user, same group
|
||||
expect(s.has(9999, 9999, T0)).toBe(false); // wholly unknown
|
||||
});
|
||||
|
||||
it('sessions are keyed per (user, group) — one user, many groups', () => {
|
||||
const s = new TempSessionStore();
|
||||
s.record(1001, 700, T0);
|
||||
s.record(1001, 800, T0);
|
||||
expect(s.has(1001, 700, T0)).toBe(true);
|
||||
expect(s.has(1001, 800, T0)).toBe(true);
|
||||
expect(s.has(1001, 900, T0)).toBe(false);
|
||||
});
|
||||
|
||||
it('expires exactly at TTL and prunes on read', () => {
|
||||
const s = new TempSessionStore();
|
||||
s.record(1001, 700, T0);
|
||||
// Just before expiry: still valid.
|
||||
expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS - 1)).toBe(true);
|
||||
// At/after expiry: gone.
|
||||
expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS)).toBe(false);
|
||||
// A later inbound message refreshes the window.
|
||||
s.record(1001, 700, T0 + TEMP_SESSION_TTL_MS);
|
||||
expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS + 1)).toBe(true);
|
||||
});
|
||||
|
||||
it('ignores invalid records (no group / no user) — stays receive-only', () => {
|
||||
const s = new TempSessionStore();
|
||||
s.record(1001, 0, T0); // no source group
|
||||
s.record(0, 700, T0); // no user
|
||||
s.record(-5, -5, T0);
|
||||
expect(s.has(1001, 0, T0)).toBe(false);
|
||||
expect(s.has(0, 700, T0)).toBe(false);
|
||||
});
|
||||
|
||||
it('sweep drops expired entries', () => {
|
||||
const s = new TempSessionStore();
|
||||
s.record(1001, 700, T0);
|
||||
s.record(1002, 700, T0 + TEMP_SESSION_TTL_MS); // expires later
|
||||
s.sweep(T0 + TEMP_SESSION_TTL_MS + 1);
|
||||
expect(s.has(1001, 700, T0 + TEMP_SESSION_TTL_MS + 1)).toBe(false);
|
||||
expect(s.has(1002, 700, T0 + TEMP_SESSION_TTL_MS + 1)).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -21,9 +21,17 @@ export interface RoutingTrans0x211 {
|
||||
uid?: pb<8, string>;
|
||||
}
|
||||
|
||||
// Group temp-session routing head — RoutingHead field 3. Inner shape
|
||||
// { 群号 (source group), 对端 uid }.
|
||||
export interface RoutingGrpTmp {
|
||||
groupUin?: pb<3, uint_64>;
|
||||
toUid?: pb<4, string>;
|
||||
}
|
||||
|
||||
export interface RoutingHead {
|
||||
c2c?: pb<1, RoutingC2C>;
|
||||
grp?: pb<2, RoutingGroup>;
|
||||
grpTmp?: pb<3, RoutingGrpTmp>;
|
||||
trans0x211?: pb<15, RoutingTrans0x211>;
|
||||
}
|
||||
|
||||
|
||||
@@ -18,8 +18,12 @@ export interface ResponseGrp {
|
||||
groupName?: pb<7, string>;
|
||||
}
|
||||
|
||||
// ResponseHead field 7 is multi-purpose: a forward message carries
|
||||
// `friendName` (field 6); a group temp-session push carries the source group
|
||||
// (field 4). Subfields don't collide, so one interface covers both.
|
||||
export interface ResponseForward {
|
||||
friendName?: pb<6, string>;
|
||||
tempGroupUin?: pb<4, uint_32>;
|
||||
friendName?: pb<6, string>;
|
||||
}
|
||||
|
||||
// ResponseHead
|
||||
|
||||
@@ -149,6 +149,7 @@ export interface GroupMessage extends QQEvent {
|
||||
export interface TempMessage extends QQEvent {
|
||||
kind: 'temp_message';
|
||||
senderUin: number;
|
||||
/** Source group of the temp session (from responseHead.forward), or 0. */
|
||||
groupId: number;
|
||||
senderNick: string;
|
||||
msgSeq: number;
|
||||
|
||||
@@ -17,6 +17,10 @@ export const decodeTempMessage: MsgPushDecoder = (ctx) => {
|
||||
ev.groupId = ctx.responseHead.grp.groupUin ?? 0;
|
||||
ev.senderNick = ctx.responseHead.grp.memberName ?? '';
|
||||
}
|
||||
// A group temp session carries its source group in responseHead.forward.
|
||||
if (ctx.responseHead?.forward?.tempGroupUin) {
|
||||
ev.groupId = ctx.responseHead.forward.tempGroupUin;
|
||||
}
|
||||
if (!ev.senderNick) {
|
||||
const friend = ctx.identity.findFriend(ctx.fromUin);
|
||||
if (friend) ev.senderNick = friend.nickname;
|
||||
|
||||
Reference in new issue
Block a user