Merge pull request #255 from SnowLuma/dev

chore: promote dev → main (88216ce)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-07-20 07:53:18 +00:00
commit ccd46aafb3
58 files changed
+4076 -221

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.12.6",
"version": "1.12.7",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/core",
"version": "1.12.6",
"version": "1.12.7",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -0,0 +1,28 @@
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import {
getCollectionList,
type CollectionListResult,
} from '@snowluma/protocol/web/collection';
import type { BridgeContext } from '../bridge-context';
const COLLECTION_DOMAIN = 'weiyun.com';
/** Read-only access to the account's QQ collection list. */
export class CollectionApi {
constructor(private readonly ctx: BridgeContext) {}
async list(category = 0, count = 50): Promise<CollectionListResult> {
const { domainPskeyMap } = await GetPskey.invoke(this.ctx, {
domainList: [COLLECTION_DOMAIN],
});
const pskey = domainPskeyMap.get(COLLECTION_DOMAIN);
if (!pskey) throw new Error(`QQ did not return a p_skey for ${COLLECTION_DOMAIN}`);
return getCollectionList({
uin: this.ctx.identity.uin,
pskey,
category,
count,
});
}
}
+148 -3
View File
@@ -8,6 +8,7 @@ import { GroupTodo } from '@snowluma/protocol/oidb-services/extras/group-todo';
import { convertAudioBytes } from '@snowluma/protocol/highway/ffmpeg-addon';
import { loadBinarySource } from '@snowluma/protocol/highway/utils';
import { createLogger } from '@snowluma/common/logger';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { PttTransReq, PttTransResp } from '@snowluma/proto-defs/ptt-trans';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
@@ -49,9 +50,41 @@ export interface AiVoiceItem {
voiceExampleUrl: string;
}
export interface AiVoiceSendReceipt {
sequence: number;
}
const log = createLogger('Bridge.Extras');
const AI_VOICE_RECEIPT_TIMEOUT_MS = 5_000;
const AI_VOICE_CANDIDATE_LIMIT = 64;
const AI_VOICE_CLAIM_LIMIT = 256;
type GroupMessageEvent = Extract<QQEventVariant, { kind: 'group_message' }>;
function normalizeMediaUuid(value: unknown): string {
return typeof value === 'string' ? value.trim() : '';
}
function matchesAiVoiceEvent(node: MediaIndexNode, event: GroupMessageEvent): boolean {
const expectedUuid = normalizeMediaUuid(node.fileUuid);
if (!expectedUuid) return false;
for (const element of event.elements) {
if (element.type !== 'record') continue;
const actualUuid = normalizeMediaUuid(element.mediaNode?.fileUuid || element.fileId);
if (actualUuid === expectedUuid) return true;
}
return false;
}
function describeAiVoiceFingerprint(node: MediaIndexNode): string {
const uuid = normalizeMediaUuid(node.fileUuid);
if (uuid) return `uuid:${uuid.slice(-12)}`;
return 'missing';
}
export class ExtrasApi {
private readonly claimedAiVoiceReceiptKeys = new Set<string>();
constructor(private readonly ctx: BridgeContext) { }
// ─────────────── Group todo (0xF90) ───────────────
@@ -94,9 +127,11 @@ export class ExtrasApi {
* the render is in-flight; we retry until a node materialises or the
* cap is hit. napcat uses the same 30-retry budget.
*
* The returned MediaIndexNode plugs directly into
* The returned node plugs directly into
* `apis.groupFile.getPttUrl`, which already handles every other
* download-URL fetch in SnowLuma.
* download-URL fetch in SnowLuma. The synthesis response does not contain a
* reliable message sequence; callers that need one must use `sendAiVoice`,
* which correlates the subsequent self-message receipt.
*/
async fetchAiVoice(
groupId: number,
@@ -109,11 +144,121 @@ export class ExtrasApi {
const sessionId = Math.floor(Math.random() * 0xFFFFFFFF) >>> 0;
for (let i = 0; i < maxRetries; i++) {
const node = await FetchAiVoice.invoke(this.ctx, { groupId, voiceId, text, chatType, sessionId });
if (node) return node as MediaIndexNode;
if (node) {
log.debug(
'AI voice synthesis completed group=%d media=%s polls=%d',
groupId,
describeAiVoiceFingerprint(node),
i + 1,
);
return node as MediaIndexNode;
}
}
throw new Error(`AI voice synthesis did not complete after ${maxRetries} polls`);
}
/**
* Publish an AI voice and wait for QQ's canonical self-message receipt.
*
* The 0x929B completion response carries the media node but, on live QQ,
* omits the group message sequence. Subscribe before publishing so an echo
* that wins the response race is buffered, then correlate by the exact media
* UUID. Never guess from content hashes or "the next voice in the group":
* concurrent requests can legitimately render byte-identical audio.
*/
async sendAiVoice(
groupId: number,
voiceId: string,
text: string,
chatType: AiVoiceChatType | number,
receiptTimeoutMs = AI_VOICE_RECEIPT_TIMEOUT_MS,
): Promise<AiVoiceSendReceipt> {
const candidates: GroupMessageEvent[] = [];
let candidatesOverflowed = false;
let expectedNode: MediaIndexNode | null = null;
let receiptSettled = false;
let resolveReceipt: ((event: GroupMessageEvent) => void) | null = null;
const receiptPromise = new Promise<GroupMessageEvent>((resolve) => {
resolveReceipt = resolve;
});
const claim = (event: GroupMessageEvent): boolean => {
if (receiptSettled) return false;
const key = `${event.groupId}:${event.msgSeq}:${event.msgId}`;
if (this.claimedAiVoiceReceiptKeys.has(key)) return false;
this.claimedAiVoiceReceiptKeys.add(key);
if (this.claimedAiVoiceReceiptKeys.size > AI_VOICE_CLAIM_LIMIT) {
const oldest = this.claimedAiVoiceReceiptKeys.values().next().value;
if (oldest !== undefined) this.claimedAiVoiceReceiptKeys.delete(oldest);
}
receiptSettled = true;
return true;
};
const accept = (event: GroupMessageEvent): void => {
if (event.groupId !== groupId || event.senderUin !== event.selfUin) return;
if (!event.elements.some(element => element.type === 'record')) return;
if (expectedNode && matchesAiVoiceEvent(expectedNode, event) && claim(event)) {
resolveReceipt?.(event);
return;
}
candidates.push(event);
if (candidates.length > AI_VOICE_CANDIDATE_LIMIT) {
candidates.shift();
candidatesOverflowed = true;
}
};
const unsubscribe = this.ctx.events.on('group_message', accept);
let timeout: ReturnType<typeof setTimeout> | null = null;
try {
const node = await this.fetchAiVoice(groupId, voiceId, text, chatType);
expectedNode = node;
const fingerprint = describeAiVoiceFingerprint(node);
if (fingerprint === 'missing') {
throw new Error('AI voice was published but QQ returned no exact media identifier for receipt correlation');
}
const buffered = candidates.find(event => matchesAiVoiceEvent(node, event) && claim(event));
if (!buffered && candidatesOverflowed) {
throw new Error(
`AI voice was published but receipt correlation overflowed after ${AI_VOICE_CANDIDATE_LIMIT} `
+ `unmatched self voice messages (group=${groupId} media=${fingerprint})`,
);
}
const event = buffered ?? await Promise.race([
receiptPromise,
new Promise<never>((_resolve, reject) => {
timeout = setTimeout(() => {
reject(new Error(
`AI voice was published but no matching group-message receipt arrived within ${receiptTimeoutMs}ms `
+ `(group=${groupId} media=${fingerprint})`,
));
}, receiptTimeoutMs);
timeout.unref?.();
}),
]);
if (!Number.isInteger(event.msgSeq) || event.msgSeq <= 0) {
throw new Error(`AI voice receipt carried invalid message sequence: ${event.msgSeq}`);
}
log.debug(
'AI voice receipt matched group=%d media=%s sequence=%d random=%d',
groupId,
fingerprint,
event.msgSeq,
event.msgId,
);
return {
sequence: event.msgSeq,
};
} finally {
if (timeout) clearTimeout(timeout);
unsubscribe();
}
}
// ─────────────── Voice-to-text (pttTrans.Trans{C2C,Group}PttReq) ───────────────
/**
+212 -8
View File
@@ -1,19 +1,101 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import { createLogger } from '@snowluma/common/logger';
import type {
AlbumCreator,
DeleteMediasRequest,
DeleteMediasResponse,
DoQunCommentRequest,
DoQunCommentResponse,
DoQunLikeRequest,
DoQunLikeResponse,
GetAlbumListRequest,
GetAlbumListResponse,
GroupAlbumInfo as GroupAlbumInfoWire,
GetMediaListRequest,
GetMediaListResponse,
MediaInfo,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { getGroupAlbumList, uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { uploadImageToGroupAlbum } from '@snowluma/protocol/web/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { BridgeContext } from '../bridge-context';
const log = createLogger('Bridge.GroupAlbum');
const GET_ALBUM_LIST_CMD = 'QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList';
const GET_ALBUM_LIST_SEQ = 3331;
function uint64ToString(value: bigint | undefined): string {
return (value ?? 0n).toString();
}
function uint64ToSafeNumber(value: bigint | undefined, fieldName: string): number {
const normalized = value ?? 0n;
if (normalized > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new Error(`group album ${fieldName} exceeds Number.MAX_SAFE_INTEGER: ${normalized}`);
}
return Number(normalized);
}
function normalizeAlbumCreator(creator: AlbumCreator | undefined): QunAlbumCreator | undefined {
if (!creator) return undefined;
return {
uid: creator.uid ?? '',
nick: creator.nick ?? '',
is_sweet: creator.isSweet ?? false,
is_special: creator.isSpecial ?? false,
is_super_like: creator.isSuperLike ?? false,
custom_id: creator.customId ?? '',
poly_id: creator.polyId ?? '',
portrait: creator.portrait ?? '',
can_follow: creator.canFollow ?? 0,
isfollowed: creator.isFollowed ?? 0,
uin: creator.uin ?? '',
ditto_uin: creator.dittoUin ?? '',
};
}
function normalizeQunAlbum(album: GroupAlbumInfoWire): QunAlbumInfo {
const normalized: QunAlbumInfo = {
album_id: album.albumId ?? '',
owner: album.owner ?? '',
name: album.name ?? '',
desc: album.description ?? '',
create_time: uint64ToString(album.createTime),
modify_time: uint64ToString(album.modifyTime),
last_upload_time: uint64ToString(album.lastUploadTime),
upload_number: uint64ToString(album.uploadNumber),
top_flag: uint64ToString(album.topFlag),
busi_type: album.busiType ?? 0,
status: album.status ?? 0,
allow_share: album.allowShare ?? false,
is_subscribe: album.isSubscribe ?? false,
bitmap: album.bitmap ?? '',
is_share_album: album.isShareAlbum ?? false,
qz_album_type: album.qzAlbumType ?? 0,
cover_type: album.coverType ?? 0,
default_desc: album.defaultDesc ?? '',
sort_type: album.sortType ?? 0,
};
const creator = normalizeAlbumCreator(album.creator);
if (creator) normalized.creator = creator;
return normalized;
}
function toLegacyAlbum(album: GroupAlbumInfoWire): GroupAlbumInfo {
const creator = normalizeAlbumCreator(album.creator);
return {
id: album.albumId ?? '',
name: album.name ?? '',
picNum: uint64ToSafeNumber(album.uploadNumber, 'upload_number'),
createTime: uint64ToSafeNumber(album.createTime, 'create_time'),
desc: album.description ?? '',
owner: album.owner ?? '',
createuin: creator?.uin || album.owner || creator?.uid || '',
// QQ NT's AlbumService returns this as a normal UTF-8 protobuf string.
// Unlike the legacy Qzone HTTP endpoint, it does not rewrite Unicode
// emoji into ambiguous [em]...[/em] tags.
createnickname: creator?.nick ?? '',
};
}
function convertBigIntToString(obj: unknown): JsonValue {
if (obj === null || obj === undefined) return null;
@@ -33,13 +115,73 @@ function convertBigIntToString(obj: unknown): JsonValue {
export class GroupAlbumApi {
constructor(private readonly ctx: BridgeContext) { }
// 列出群相册(基于 qzone.qq.com 的 HTTP Cookie)。
private async fetchAlbumList(groupId: number, attachInfo: string): Promise<GroupAlbumWireResult> {
const traceId = `_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
const body = protobuf_encode<GetAlbumListRequest>({
seq: GET_ALBUM_LIST_SEQ,
field2: new Uint8Array(0),
field3: new Uint8Array(0),
data: {
groupId: groupId.toString(),
attachInfo,
},
traceId,
extMap: [{ key: 'fc-appid', value: '100' }],
});
log.debug(
'get album list request: group=%d cursorChars=%d requestBytes=%d',
groupId,
attachInfo.length,
body.length,
);
const result = await this.ctx.sendRawPacket(GET_ALBUM_LIST_CMD, body, 15000);
if (!result.success || !result.gotResponse || !result.responseData) {
throw new Error(
`get group album list transport failed: ${result.errorMessage || `code ${result.errorCode}`}`,
);
}
const response = protobuf_decode<GetAlbumListResponse>(result.responseData);
const resultCode = response.result ?? 0;
if (resultCode !== 0) {
throw new Error(
`get group album list failed: result=${resultCode}, error=${response.errorText || 'unknown'}`,
);
}
const normalized: GroupAlbumWireResult = {
albumList: response.data?.albumList ?? [],
attachInfo: response.data?.attachInfo ?? '',
hasMore: response.data?.hasMore ?? false,
};
log.debug(
'get album list response: group=%d albums=%d hasMore=%s cursorChars=%d responseBytes=%d',
groupId,
normalized.albumList.length,
String(normalized.hasMore),
normalized.attachInfo.length,
result.responseData.length,
);
return normalized;
}
/** QQ NT AlbumService-backed list, including its pagination cursor. */
async listQun(groupId: number, attachInfo = ''): Promise<QunAlbumListResult> {
const result = await this.fetchAlbumList(groupId, attachInfo);
return {
albumList: result.albumList.map(normalizeQunAlbum),
attachInfo: result.attachInfo,
hasMore: result.hasMore,
};
}
// OneBot compatibility shape used by get_group_album_list.
async list(groupId: number): Promise<GroupAlbumList> {
const groupCode = groupId.toString();
const uin = this.ctx.identity.uin;
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
const albumData = await getGroupAlbumList(cookieObject, groupCode, uin);
return albumData?.album || [];
const result = await this.fetchAlbumList(groupId, '');
return result.albumList.map(toLegacyAlbum);
}
// 上传图片到现有相册(HTTP 分片上传)。
@@ -269,7 +411,69 @@ export interface GroupAlbumMediaResult {
nextAttachInfo: string;
}
export type GroupAlbumList = NonNullable<Awaited<ReturnType<typeof getGroupAlbumList>>>['album'];
interface GroupAlbumWireResult {
albumList: GroupAlbumInfoWire[];
attachInfo: string;
hasMore: boolean;
}
export interface GroupAlbumInfo {
id: string;
name: string;
picNum: number;
createTime: number;
desc: string;
owner: string;
createuin: string;
createnickname: string;
[key: string]: JsonValue;
}
export type GroupAlbumList = GroupAlbumInfo[];
export interface QunAlbumCreator {
uid: string;
nick: string;
is_sweet: boolean;
is_special: boolean;
is_super_like: boolean;
custom_id: string;
poly_id: string;
portrait: string;
can_follow: number;
isfollowed: number;
uin: string;
ditto_uin: string;
}
export interface QunAlbumInfo {
album_id: string;
owner: string;
name: string;
desc: string;
create_time: string;
modify_time: string;
last_upload_time: string;
upload_number: string;
creator?: QunAlbumCreator;
top_flag: string;
busi_type: number;
status: number;
allow_share: boolean;
is_subscribe: boolean;
bitmap: string;
is_share_album: boolean;
qz_album_type: number;
cover_type: number;
default_desc: string;
sort_type: number;
}
export interface QunAlbumListResult {
albumList: QunAlbumInfo[];
attachInfo: string;
hasMore: boolean;
}
export interface GroupAlbumCommentResult {
id: string;
+5 -1
View File
@@ -1,4 +1,5 @@
import type { BridgeContext } from '../bridge-context';
import { CollectionApi } from './collection';
import { ContactsApi } from './contacts';
import { ExtrasApi } from './extras';
import { FlashTransferApi } from './flash-transfer';
@@ -15,6 +16,8 @@ import { QzoneApi } from './qzone';
import { WebApi } from './web';
export interface ApiHub {
/** Personal QQ collections: authenticated list retrieval and pagination. */
readonly collection: CollectionApi;
/** Send/recall/markRead operations across c2c + group + c2c-file. */
readonly message: MessageApi;
/** Friend / group / member roster + user-profile + group-request-list + download-rkey. */
@@ -55,6 +58,7 @@ export interface ApiHub {
*/
export function buildApiHub(ctx: BridgeContext): ApiHub {
return {
collection: new CollectionApi(ctx),
message: new MessageApi(ctx),
contacts: new ContactsApi(ctx),
groupAdmin: new GroupAdminApi(ctx),
@@ -76,6 +80,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub {
// `import type { MessageApi } from '@snowluma/core/.../apis'` for
// signature use. Concrete instances always come from `bridge.apis.*`.
export { ContactsApi } from './contacts';
export { CollectionApi } from './collection';
export { ExtrasApi } from './extras';
export { ForwardApi } from './forward';
export { FriendApi } from './friend';
@@ -89,4 +94,3 @@ export { ProfileApi } from './profile';
export { QzoneApi } from './qzone';
export { FlashTransferApi, type FlashFileInfo } from './flash-transfer';
export { WebApi } from './web';
@@ -0,0 +1,47 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey';
import * as collectionWeb from '@snowluma/protocol/web/collection';
import { CollectionApi } from '../../src/bridge/apis/collection';
import { mockBridge } from './_helpers';
describe('apis/collection', () => {
afterEach(() => vi.restoreAllMocks());
it('obtains a Weiyun p_skey and fetches the collection list', async () => {
const bridge = mockBridge();
const expected = {
errCode: 0 as const,
errMsg: '',
collectionSearchList: {
collectionItemList: [],
hasMore: false,
bottomTimeStamp: '0',
},
};
const ticketSpy = vi.spyOn(GetPskey, 'invoke').mockResolvedValue({
domainPskeyMap: new Map([['weiyun.com', 'weiyun-ticket']]),
});
const listSpy = vi.spyOn(collectionWeb, 'getCollectionList').mockResolvedValue(expected);
const result = await new CollectionApi(bridge as never).list(4, 25);
expect(ticketSpy).toHaveBeenCalledWith(bridge, { domainList: ['weiyun.com'] });
expect(listSpy).toHaveBeenCalledWith({
uin: '10001',
pskey: 'weiyun-ticket',
category: 4,
count: 25,
});
expect(result).toBe(expected);
});
it('fails explicitly when QQ does not return a Weiyun p_skey', async () => {
const bridge = mockBridge();
vi.spyOn(GetPskey, 'invoke').mockResolvedValue({ domainPskeyMap: new Map() });
const listSpy = vi.spyOn(collectionWeb, 'getCollectionList');
await expect(new CollectionApi(bridge as never).list(0, 50))
.rejects.toThrow('QQ did not return a p_skey for weiyun.com');
expect(listSpy).not.toHaveBeenCalled();
});
});
+170 -2
View File
@@ -1,5 +1,7 @@
import { describe, it, expect } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { QQEventVariant } from '@snowluma/protocol/events';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupTodo,
@@ -115,13 +117,15 @@ describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
expect(out).toEqual([]);
});
it('fetchAiVoice retries while msgInfo is empty, returns the first IndexNode it sees', async () => {
it('fetchAiVoice retries while msgInfo is empty and returns the media node', async () => {
const bridge = mockBridge();
const node = { fileUuid: 'uuid-1', subType: 1 };
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { statusCode: 2 } } as any)))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [] } } as any })))
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({ body: { msgInfo: { msgInfoBody: [{ index: node }] } } as any })));
.mockResolvedValueOnce(packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { field2: 319, field3: 20, msgInfo: { msgInfoBody: [{ index: node }] } } as any,
})));
const out = await new ExtrasApi(bridge as any).fetchAiVoice(100, 'voice-id', 'hi', AiVoiceChatType.Sound);
expect(out).toMatchObject(node);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
@@ -159,4 +163,168 @@ describe('apis/extras / AI voice (0x929D / 0x929B)', () => {
const env2 = protobuf_decode<OidbBase<OidbAiVoiceReq>>(bridge.sendRawPacket.mock.calls[1]![1]);
expect(env1.body?.session?.sessionId).toBe(env2.body?.session?.sessionId);
});
it('sendAiVoice correlates an echo that arrives before the synthesis response', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
const node = { fileUuid: 'voice-uuid', info: { fileHash: 'AABB' } };
bridge.sendRawPacket.mockImplementationOnce(async () => {
await events.emit({
kind: 'group_message',
time: 1234,
selfUin: 10001,
groupId: 100,
groupName: 'test',
senderUin: 10001,
senderNick: 'self',
senderCard: '',
senderRole: 'member',
msgSeq: 319,
msgId: 456,
elements: [{ type: 'record', fileId: 'voice-uuid', fileHash: 'AABB' }],
});
return packResponse(protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: node }] } },
} as any));
});
const receipt = await new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 50);
expect(receipt).toEqual({ sequence: 319 });
});
it('sendAiVoice ignores unrelated self voice messages and matches the media UUID', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
const node = { fileUuid: 'expected-uuid', info: { fileHash: 'aabb' } };
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: node }] } },
} as any),
));
const pending = new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 100);
await events.emit({
kind: 'group_message', time: 0, selfUin: 10001, groupId: 999, groupName: 'other',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 10, msgId: 20,
elements: [{ type: 'record', fileId: 'expected-uuid' }],
});
await events.emit({
kind: 'group_message', time: 0, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 20002, senderNick: 'other', senderCard: '', senderRole: 'member',
msgSeq: 11, msgId: 21,
elements: [{ type: 'record', fileId: 'expected-uuid' }],
});
await events.emit({
kind: 'group_message', time: 0, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 12, msgId: 22,
elements: [{ type: 'text', text: 'not a voice' }],
});
await events.emit({
kind: 'group_message', time: 1, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 1, msgId: 2,
elements: [{ type: 'record', fileId: 'EXPECTED-UUID', fileHash: 'AABB' }],
});
await events.emit({
kind: 'group_message', time: 3, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 4, msgId: 5, elements: [{ type: 'record', mediaNode: { fileUuid: 'expected-uuid' } }],
});
await expect(pending).resolves.toEqual({ sequence: 4 });
});
it('sendAiVoice lets each self-message receipt satisfy only one concurrent request', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
const node = { fileUuid: 'shared-uuid', info: { fileHash: 'AABB' } };
bridge.sendRawPacket.mockResolvedValue(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: node }] } },
} as any),
));
const api = new ExtrasApi(bridge as any);
const first = api.sendAiVoice(100, 'v', 'same text', 1, 100);
const second = api.sendAiVoice(100, 'v', 'same text', 1, 100);
const firstReceipt: Extract<QQEventVariant, { kind: 'group_message' }> = {
kind: 'group_message', time: 1, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 10, msgId: 20, elements: [{ type: 'record', fileId: 'shared-uuid' }],
};
await events.emit(firstReceipt);
// A second QQ process can decode the same push into a different object.
await events.emit({ ...firstReceipt, elements: [...firstReceipt.elements] });
await events.emit({
kind: 'group_message', time: 2, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 11, msgId: 21, elements: [{ type: 'record', fileId: 'shared-uuid' }],
});
await expect(Promise.all([first, second])).resolves.toEqual([
{ sequence: 10 },
{ sequence: 11 },
]);
});
it('sendAiVoice fails explicitly when QQ omits every correlation key', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: { subType: 1 } }] } },
} as any),
));
await expect(new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 10)).rejects.toThrow(
/no exact media identifier/i,
);
});
it('sendAiVoice refuses hash-only correlation because concurrent audio can be identical', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: { info: { fileHash: 'AABB' } } }] } },
} as any),
));
await expect(new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 10)).rejects.toThrow(
/no exact media identifier/i,
);
});
it('sendAiVoice rejects a matched receipt with an invalid message sequence', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uuid' } }] } },
} as any),
));
const pending = new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 50);
await events.emit({
kind: 'group_message', time: 1, selfUin: 10001, groupId: 100, groupName: 'test',
senderUin: 10001, senderNick: 'self', senderCard: '', senderRole: 'member',
msgSeq: 0, msgId: 2, elements: [{ type: 'record', fileId: 'uuid' }],
});
await expect(pending).rejects.toThrow(/invalid message sequence: 0/i);
});
it('sendAiVoice fails explicitly when the canonical echo never arrives', async () => {
const events = new BridgeEventBus();
const bridge = mockBridge({ events: events as any });
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbAiVoiceResp>>({
body: { msgInfo: { msgInfoBody: [{ index: { fileUuid: 'uuid' } }] } },
} as any),
));
await expect(new ExtrasApi(bridge as any).sendAiVoice(100, 'v', 't', 1, 5)).rejects.toThrow(
/published but no matching group-message receipt/i,
);
});
});
@@ -1,4 +1,23 @@
import type { pb } from '@snowluma/proton';
import type { bytes, int_32, pb, pb_repeated } from '@snowluma/proton';
interface GroupAlbumListReqDataWireOracle {
groupId?: pb<1, string>;
cursor?: pb<2, string>;
}
interface GroupAlbumListExtWireOracle {
key?: pb<1, string>;
value?: pb<2, string>;
}
export interface GroupAlbumListRequestWireOracle {
seq?: pb<1, int_32>;
field2?: pb<2, bytes>;
field3?: pb<3, bytes>;
data?: pb<4, GroupAlbumListReqDataWireOracle>;
traceId?: pb<5, string>;
extMap?: pb_repeated<10, GroupAlbumListExtWireOracle>;
}
interface GroupAlbumMediaListReqInfoWireOracle {
reserved?: pb<4, string>;
+122 -2
View File
@@ -1,11 +1,131 @@
import { describe, expect, it } from 'vitest';
import type { GetMediaListResponse } from '@snowluma/proto-defs/oidb-actions/group-album';
import type {
GetAlbumListResponse,
GetMediaListResponse,
} from '@snowluma/proto-defs/oidb-actions/group-album';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { GroupAlbumApi } from '../../src/bridge/apis/group-album';
import { mockBridge } from './_helpers';
import type { GroupAlbumMediaListRequestWireOracle } from './group-album-wire-fixture';
import type {
GroupAlbumListRequestWireOracle,
GroupAlbumMediaListRequestWireOracle,
} from './group-album-wire-fixture';
describe('apis/group-album', () => {
it('uses QQ NT AlbumService and puts the pagination cursor in request body field 2', async () => {
const bridge = mockBridge();
const cursor = '{"IndexType":"next"}';
await new GroupAlbumApi(bridge as never).listQun(12345, cursor);
const [serviceCmd, requestBytes, timeoutMs] = bridge.sendRawPacket.mock.calls[0]!;
expect(serviceCmd).toBe('QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList');
expect(timeoutMs).toBe(15000);
const request = protobuf_decode<GroupAlbumListRequestWireOracle>(requestBytes);
expect(request.seq).toBe(3331);
expect(request.data).toEqual({ groupId: '12345', cursor });
expect(request.extMap).toEqual([{ key: 'fc-appid', value: '100' }]);
// QQ NT's codec writes the two empty common-envelope byte fields rather
// than omitting them: field1=3331, field2="", field3="".
expect(Buffer.from(requestBytes).subarray(0, 7).toString('hex'))
.toBe('08831a12001a00');
});
it('preserves Unicode emoji and literal QQ-em tags in the legacy creator nickname', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
seq: 3331,
data: {
albumList: [{
albumId: 'album-id',
owner: '10001',
name: '测试相册',
description: 'desc',
createTime: 1700000000n,
uploadNumber: 5n,
creator: {
uid: 'u_creator',
uin: '10001',
nick: '😂[em]e328514[/em]',
},
}],
},
})),
});
const result = await new GroupAlbumApi(bridge as never).list(12345);
expect(result).toEqual([{
id: 'album-id',
name: '测试相册',
picNum: 5,
createTime: 1700000000,
desc: 'desc',
owner: '10001',
createuin: '10001',
createnickname: '😂[em]e328514[/em]',
}]);
});
it('returns the native AlbumService cursor and creator fields for get_qun_album_list', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
data: {
albumList: [{
albumId: 'album-id',
name: '测试相册',
createTime: 1700000000n,
uploadNumber: 5n,
creator: { uin: '10001', nick: '😂' },
}],
attachInfo: 'next-cursor',
hasMore: true,
},
})),
});
const result = await new GroupAlbumApi(bridge as never).listQun(12345);
expect(result.attachInfo).toBe('next-cursor');
expect(result.hasMore).toBe(true);
expect(result.albumList[0]).toMatchObject({
album_id: 'album-id',
name: '测试相册',
create_time: '1700000000',
upload_number: '5',
creator: { uin: '10001', nick: '😂' },
});
});
it('surfaces AlbumService response errors instead of falling back to the lossy web endpoint', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetAlbumListResponse>({
seq: 3331,
result: 1001,
errorText: 'permission denied',
})),
});
await expect(new GroupAlbumApi(bridge as never).list(12345))
.rejects.toThrow('result=1001, error=permission denied');
});
it('encodes the next-page cursor in the page-info field', async () => {
const bridge = mockBridge();
const cursor = '{"IndexType":"next","Loc":{"batch_id":2147483650}}';
@@ -131,6 +131,15 @@ function makeGroupDecreasePacket(
};
}
function makeNestedOperatorInfoFixture(): Uint8Array {
// QQ may wrap GroupChange.operatorBytes in OperatorInfo and append metadata
// after the UID, including for GroupChange.decreaseType=131.
return Buffer.from(
'0a180a0a755f6f70657261746f7210061a060102030405062001',
'hex',
);
}
describe('parseMsgPush group member increase', () => {
it('does not fall back to the group id when a joining uid is unresolved', () => {
const [event] = parseMsgPush(makeGroupIncreasePacket('u_new_member'), makeIdentity()) as GroupMemberJoin[];
@@ -156,6 +165,20 @@ describe('parseMsgPush group member increase', () => {
expect(event.operatorUid).toBe(operator.uid);
});
it('decodes nested operator info used by member-increase pushes', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(
makeGroupIncreasePacket(member.uid, '', GROUP_ID, makeNestedOperatorInfoFixture()),
makeIdentity([member, operator]),
) as GroupMemberJoin[];
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(operator.uin);
expect(event.userUid).toBe(member.uid);
expect(event.operatorUid).toBe(operator.uid);
});
it('derives approve vs invite from the member-change operation code (#237)', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
@@ -251,6 +274,20 @@ describe('parseMsgPush group member decrease', () => {
expect(event.leaveType).toBe('kick');
});
it('decodes nested operator info for ordinary member removals (#253)', () => {
const member = makeGroupMember(22222, 'u_member');
const operator = makeGroupMember(33333, 'u_operator');
const [event] = parseMsgPush(
makeGroupDecreasePacket(member.uid, 131, makeNestedOperatorInfoFixture()),
makeIdentity([member, operator]),
) as Extract<QQEventVariant, { kind: 'group_member_leave' }>[];
expect(event.userUin).toBe(member.uin);
expect(event.operatorUin).toBe(operator.uin);
expect(event.operatorUid).toBe(operator.uid);
expect(event.leaveType).toBe('kick');
});
it('decodes nested operator info when the bot itself is kicked', () => {
const operator = makeGroupMember(33333, 'u_operator');
const operatorBytes = protobuf_encode<OperatorInfo>({
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.12.6",
"version": "1.12.7",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+279 -17
View File
@@ -2410,18 +2410,238 @@
{
"name": "get_collection_list",
"aliases": [],
"summary": "获取收藏列表(占位)",
"returns": "占位实现,恒返回空数组。",
"summary": "获取收藏列表",
"returns": "返回收藏条目、是否还有更多数据及底部时间游标。",
"returnsSchema": {
"type": "array",
"description": "收藏列表(占位,恒空)"
"type": "object",
"properties": {
"errCode": {
"type": "integer"
},
"errMsg": {
"type": "string"
},
"collectionSearchList": {
"type": "object",
"properties": {
"collectionItemList": {
"type": "array",
"items": {
"type": "object",
"properties": {
"cid": {
"type": "string"
},
"type": {
"type": "integer"
},
"status": {
"type": "integer"
},
"author": {
"type": "object",
"properties": {
"type": {
"type": "integer"
},
"numId": {
"type": "string"
},
"strId": {
"type": "string"
},
"groupId": {
"type": "string"
},
"groupName": {
"type": "string"
},
"uid": {
"type": "string"
}
},
"required": [
"type",
"numId",
"strId",
"groupId",
"groupName",
"uid"
]
},
"bid": {
"type": "integer"
},
"category": {
"type": "integer"
},
"createTime": {
"type": "string"
},
"collectTime": {
"type": "string"
},
"modifyTime": {
"type": "string"
},
"sequence": {
"type": "string"
},
"shareUrl": {
"type": "string"
},
"customGroupId": {
"type": "integer"
},
"securityBeat": {
"type": "boolean"
},
"summary": {
"type": "object",
"properties": {
"textSummary": {
"type": [
"object",
"null"
]
},
"linkSummary": {
"type": [
"object",
"null"
]
},
"gallerySummary": {
"type": [
"object",
"null"
]
},
"audioSummary": {
"type": [
"object",
"null"
]
},
"videoSummary": {
"type": [
"object",
"null"
]
},
"fileSummary": {
"type": [
"object",
"null"
]
},
"locationSummary": {
"type": [
"object",
"null"
]
},
"richMediaSummary": {
"type": [
"object",
"null"
]
}
},
"required": [
"textSummary",
"linkSummary",
"gallerySummary",
"audioSummary",
"videoSummary",
"fileSummary",
"locationSummary",
"richMediaSummary"
]
}
},
"required": [
"cid",
"type",
"status",
"author",
"bid",
"category",
"createTime",
"collectTime",
"modifyTime",
"sequence",
"shareUrl",
"customGroupId",
"securityBeat",
"summary"
]
}
},
"hasMore": {
"type": "boolean"
},
"bottomTimeStamp": {
"type": "string"
}
},
"required": [
"collectionItemList",
"hasMore",
"bottomTimeStamp"
]
}
},
"required": [
"errCode",
"errMsg",
"collectionSearchList"
]
},
"readOnly": true,
"params": [],
"params": [
{
"name": "category",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
},
"desc": "收藏分类 ID;0 表示全部分类",
"default": 0
},
{
"name": "count",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 500
},
"desc": "最多返回的收藏数量",
"default": 50
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"category": {
"type": "integer",
"minimum": 0,
"description": "收藏分类 ID;0 表示全部分类",
"default": 0
},
"count": {
"type": "integer",
"minimum": 1,
"maximum": 500,
"description": "最多返回的收藏数量",
"default": 50
}
},
"additionalProperties": true
},
"category": "扩展"
@@ -3212,13 +3432,23 @@
"createTime": {
"type": "integer",
"description": "相册创建时间(unix 秒)"
},
"createuin": {
"type": "string",
"description": "相册创建者 QQ 号"
},
"createnickname": {
"type": "string",
"description": "相册创建者昵称(原始 Unicode)"
}
},
"required": [
"id",
"name",
"picNum",
"createTime"
"createTime",
"createuin",
"createnickname"
]
}
},
@@ -5260,7 +5490,7 @@
{
"name": "get_qun_album_list",
"aliases": [],
"returns": "NapCat 风格的相册列表封套:{album_list, attach_info, has_more}(本实现 attach_info 恒为空串、has_more 恒为 false)。",
"returns": "NapCat 风格的相册列表封套:{album_list, attach_info, has_more}。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -5274,34 +5504,52 @@
"type": "string",
"description": "相册 id"
},
"album_name": {
"name": {
"type": "string",
"description": "相册名称"
},
"create_time": {
"type": "integer",
"type": "string",
"description": "相册创建时间(unix 秒)"
},
"pic_num": {
"type": "integer",
"description": "相册内照片数量"
"upload_number": {
"type": "string",
"description": "相册内媒体数量"
},
"creator": {
"type": "object",
"description": "相册创建者信息",
"properties": {
"uin": {
"type": "string",
"description": "创建者 QQ 号"
},
"uid": {
"type": "string",
"description": "创建者 UID"
},
"nick": {
"type": "string",
"description": "创建者原始 Unicode 昵称"
}
}
}
},
"required": [
"album_id",
"album_name",
"name",
"create_time",
"pic_num"
"upload_number"
]
}
},
"attach_info": {
"type": "string",
"description": "分页游标(本 web 实现一次取满,恒为空串)"
"description": "下一页分页游标"
},
"has_more": {
"type": "boolean",
"description": "是否还有更多(本 web 实现恒为 false)"
"description": "是否还有更多"
}
},
"required": [
@@ -5322,6 +5570,15 @@
"minimum": 1
},
"desc": "群号"
},
{
"name": "attach_info",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"default": ""
}
],
"invariants": [],
@@ -5333,6 +5590,10 @@
"minimum": 1,
"description": "群号",
"x-role": "group_id"
},
"attach_info": {
"type": "string",
"default": ""
}
},
"required": [
@@ -6970,6 +7231,7 @@
"name": "send_group_ai_record",
"aliases": [],
"summary": "发送 AI 语音到群",
"returns": "{ message_id }:已发送 AI 语音的 OneBot 消息 ID。",
"readOnly": false,
"params": [
{
+279 -17
View File
@@ -2413,18 +2413,238 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "get_collection_list",
"aliases": [],
"summary": "获取收藏列表(占位)",
"returns": "占位实现,恒返回空数组。",
"summary": "获取收藏列表",
"returns": "返回收藏条目、是否还有更多数据及底部时间游标。",
"returnsSchema": {
"type": "array",
"description": "收藏列表(占位,恒空)"
"type": "object",
"properties": {
"errCode": {
"type": "integer"
},
"errMsg": {
"type": "string"
},
"collectionSearchList": {
"type": "object",
"properties": {
"collectionItemList": {
"type": "array",
"items": {
"type": "object",
"properties": {
"cid": {
"type": "string"
},
"type": {
"type": "integer"
},
"status": {
"type": "integer"
},
"author": {
"type": "object",
"properties": {
"type": {
"type": "integer"
},
"numId": {
"type": "string"
},
"strId": {
"type": "string"
},
"groupId": {
"type": "string"
},
"groupName": {
"type": "string"
},
"uid": {
"type": "string"
}
},
"required": [
"type",
"numId",
"strId",
"groupId",
"groupName",
"uid"
]
},
"bid": {
"type": "integer"
},
"category": {
"type": "integer"
},
"createTime": {
"type": "string"
},
"collectTime": {
"type": "string"
},
"modifyTime": {
"type": "string"
},
"sequence": {
"type": "string"
},
"shareUrl": {
"type": "string"
},
"customGroupId": {
"type": "integer"
},
"securityBeat": {
"type": "boolean"
},
"summary": {
"type": "object",
"properties": {
"textSummary": {
"type": [
"object",
"null"
]
},
"linkSummary": {
"type": [
"object",
"null"
]
},
"gallerySummary": {
"type": [
"object",
"null"
]
},
"audioSummary": {
"type": [
"object",
"null"
]
},
"videoSummary": {
"type": [
"object",
"null"
]
},
"fileSummary": {
"type": [
"object",
"null"
]
},
"locationSummary": {
"type": [
"object",
"null"
]
},
"richMediaSummary": {
"type": [
"object",
"null"
]
}
},
"required": [
"textSummary",
"linkSummary",
"gallerySummary",
"audioSummary",
"videoSummary",
"fileSummary",
"locationSummary",
"richMediaSummary"
]
}
},
"required": [
"cid",
"type",
"status",
"author",
"bid",
"category",
"createTime",
"collectTime",
"modifyTime",
"sequence",
"shareUrl",
"customGroupId",
"securityBeat",
"summary"
]
}
},
"hasMore": {
"type": "boolean"
},
"bottomTimeStamp": {
"type": "string"
}
},
"required": [
"collectionItemList",
"hasMore",
"bottomTimeStamp"
]
}
},
"required": [
"errCode",
"errMsg",
"collectionSearchList"
]
},
"readOnly": true,
"params": [],
"params": [
{
"name": "category",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
},
"desc": "收藏分类 ID;0 表示全部分类",
"default": 0
},
{
"name": "count",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 1,
"maximum": 500
},
"desc": "最多返回的收藏数量",
"default": 50
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {},
"properties": {
"category": {
"type": "integer",
"minimum": 0,
"description": "收藏分类 ID;0 表示全部分类",
"default": 0
},
"count": {
"type": "integer",
"minimum": 1,
"maximum": 500,
"description": "最多返回的收藏数量",
"default": 50
}
},
"additionalProperties": true
},
"category": "扩展"
@@ -3215,13 +3435,23 @@ export const ACTIONS: CatalogAction[] = [
"createTime": {
"type": "integer",
"description": "相册创建时间(unix 秒)"
},
"createuin": {
"type": "string",
"description": "相册创建者 QQ 号"
},
"createnickname": {
"type": "string",
"description": "相册创建者昵称(原始 Unicode)"
}
},
"required": [
"id",
"name",
"picNum",
"createTime"
"createTime",
"createuin",
"createnickname"
]
}
},
@@ -5263,7 +5493,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "get_qun_album_list",
"aliases": [],
"returns": "NapCat 风格的相册列表封套:{album_list, attach_info, has_more}(本实现 attach_info 恒为空串、has_more 恒为 false)。",
"returns": "NapCat 风格的相册列表封套:{album_list, attach_info, has_more}。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -5277,34 +5507,52 @@ export const ACTIONS: CatalogAction[] = [
"type": "string",
"description": "相册 id"
},
"album_name": {
"name": {
"type": "string",
"description": "相册名称"
},
"create_time": {
"type": "integer",
"type": "string",
"description": "相册创建时间(unix 秒)"
},
"pic_num": {
"type": "integer",
"description": "相册内照片数量"
"upload_number": {
"type": "string",
"description": "相册内媒体数量"
},
"creator": {
"type": "object",
"description": "相册创建者信息",
"properties": {
"uin": {
"type": "string",
"description": "创建者 QQ 号"
},
"uid": {
"type": "string",
"description": "创建者 UID"
},
"nick": {
"type": "string",
"description": "创建者原始 Unicode 昵称"
}
}
}
},
"required": [
"album_id",
"album_name",
"name",
"create_time",
"pic_num"
"upload_number"
]
}
},
"attach_info": {
"type": "string",
"description": "分页游标(本 web 实现一次取满,恒为空串)"
"description": "下一页分页游标"
},
"has_more": {
"type": "boolean",
"description": "是否还有更多(本 web 实现恒为 false)"
"description": "是否还有更多"
}
},
"required": [
@@ -5325,6 +5573,15 @@ export const ACTIONS: CatalogAction[] = [
"minimum": 1
},
"desc": "群号"
},
{
"name": "attach_info",
"type": "string",
"required": false,
"schema": {
"type": "string"
},
"default": ""
}
],
"invariants": [],
@@ -5336,6 +5593,10 @@ export const ACTIONS: CatalogAction[] = [
"minimum": 1,
"description": "群号",
"x-role": "group_id"
},
"attach_info": {
"type": "string",
"default": ""
}
},
"required": [
@@ -6973,6 +7234,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "send_group_ai_record",
"aliases": [],
"summary": "发送 AI 语音到群",
"returns": "{ message_id }:已发送 AI 语音的 OneBot 消息 ID。",
"readOnly": false,
"params": [
{
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
+114 -12
View File
@@ -2,8 +2,9 @@ import { readFile } from 'node:fs/promises';
import type { ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import type { ForwardPreviewMeta } from '../modules/message-actions';
import { JsonObject, RETCODE, failedResponse, okResponse } from '../types';
import { hasAuthoritativeSequence, RETCODE, failedResponse, okResponse, type JsonObject } from '../types';
import { defineAction, groupAction, groupUserAction, f } from '../action-kit';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB
const DOWNLOAD_FILE_TIMEOUT_MS = 60_000;
@@ -110,6 +111,9 @@ async function groupTodoRun(
if (!meta.isGroup || meta.targetId !== p.group_id) {
return failedResponse(RETCODE.ACTION_FAILED, 'message does not belong to this group');
}
if (!hasAuthoritativeSequence(meta)) {
return failedResponse(RETCODE.ACTION_FAILED, 'message has no authoritative QQ sequence');
}
await op(p.group_id, BigInt(meta.sequence));
return okResponse();
}
@@ -244,6 +248,10 @@ export const actions = [
return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session');
}
if (!hasAuthoritativeSequence(meta)) {
return failedResponse(RETCODE.ACTION_FAILED, 'message has no authoritative QQ sequence');
}
await ctx.bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, p.code, p.is_set);
return okResponse();
},
@@ -1515,13 +1523,102 @@ export const actions = [
defineAction({
name: 'get_collection_list',
summary: '获取收藏列表(占位)',
summary: '获取收藏列表',
readOnly: true,
returns: '占位实现,恒返回空数组。',
returnsSchema: { type: 'array', description: '收藏列表(占位,恒空)' },
params: {},
run: async () => {
return okResponse([]);
returns: '返回收藏条目、是否还有更多数据及底部时间游标。',
returnsSchema: {
type: 'object',
properties: {
errCode: { type: 'integer' },
errMsg: { type: 'string' },
collectionSearchList: {
type: 'object',
properties: {
collectionItemList: {
type: 'array',
items: {
type: 'object',
properties: {
cid: { type: 'string' },
type: { type: 'integer' },
status: { type: 'integer' },
author: {
type: 'object',
properties: {
type: { type: 'integer' },
numId: { type: 'string' },
strId: { type: 'string' },
groupId: { type: 'string' },
groupName: { type: 'string' },
uid: { type: 'string' },
},
required: ['type', 'numId', 'strId', 'groupId', 'groupName', 'uid'],
},
bid: { type: 'integer' },
category: { type: 'integer' },
createTime: { type: 'string' },
collectTime: { type: 'string' },
modifyTime: { type: 'string' },
sequence: { type: 'string' },
shareUrl: { type: 'string' },
customGroupId: { type: 'integer' },
securityBeat: { type: 'boolean' },
summary: {
type: 'object',
properties: {
textSummary: { type: ['object', 'null'] },
linkSummary: { type: ['object', 'null'] },
gallerySummary: { type: ['object', 'null'] },
audioSummary: { type: ['object', 'null'] },
videoSummary: { type: ['object', 'null'] },
fileSummary: { type: ['object', 'null'] },
locationSummary: { type: ['object', 'null'] },
richMediaSummary: { type: ['object', 'null'] },
},
required: [
'textSummary',
'linkSummary',
'gallerySummary',
'audioSummary',
'videoSummary',
'fileSummary',
'locationSummary',
'richMediaSummary',
],
},
},
required: [
'cid',
'type',
'status',
'author',
'bid',
'category',
'createTime',
'collectTime',
'modifyTime',
'sequence',
'shareUrl',
'customGroupId',
'securityBeat',
'summary',
],
},
},
hasMore: { type: 'boolean' },
bottomTimeStamp: { type: 'string' },
},
required: ['collectionItemList', 'hasMore', 'bottomTimeStamp'],
},
},
required: ['errCode', 'errMsg', 'collectionSearchList'],
},
params: {
category: f.int({ min: 0 }).describe('收藏分类 ID;0 表示全部分类').default(0),
count: f.int({ min: 1, max: 500 }).describe('最多返回的收藏数量').default(50),
},
run: async (p, ctx) => {
return okResponse(await ctx.bridge.apis.collection.list(p.category, p.count));
},
}),
@@ -1757,20 +1854,25 @@ export const actions = [
},
}),
// NapCat 的 send_group_ai_record 是仅产生副作用的调用。
// 调用 fetchAiVoice 会把语音发布到群里。
// 返回的 message_id 始终为 0,因为 oidb 调用不会回显消息 ID。
groupAction({
name: 'send_group_ai_record',
summary: '发送 AI 语音到群',
returns: '{ message_id }:已发送 AI 语音的 OneBot 消息 ID。',
params: {
character: f.string({ allowEmpty: false }),
text: f.string({ allowEmpty: false }),
chat_type: f.int({ min: 0 }).default(1),
},
run: async (p, ctx) => {
await ctx.bridge.apis.extras.fetchAiVoice(p.group_id, p.character, p.text, p.chat_type);
return okResponse({ message_id: 0 });
const receipt = await ctx.bridge.apis.extras.sendAiVoice(
p.group_id,
p.character,
p.text,
p.chat_type,
);
return okResponse({
message_id: hashMessageIdInt32(receipt.sequence, p.group_id, GROUP_MESSAGE_EVENT),
});
},
}),
+28 -26
View File
@@ -17,8 +17,10 @@ export const actions = [
name: { type: 'string', description: '相册名称' },
picNum: { type: 'integer', description: '相册内照片数量' },
createTime: { type: 'integer', description: '相册创建时间(unix 秒)' },
createuin: { type: 'string', description: '相册创建者 QQ 号' },
createnickname: { type: 'string', description: '相册创建者昵称(原始 Unicode)' },
},
required: ['id', 'name', 'picNum', 'createTime'],
required: ['id', 'name', 'picNum', 'createTime', 'createuin', 'createnickname'],
},
},
run: async (p, ctx) => {
@@ -27,17 +29,11 @@ export const actions = [
},
}),
// get_qun_album_list — NapCat-named/shaped variant of get_group_album_list.
// NapCat's own impl calls the kernel AlbumService (trpc, not statically
// recoverable); we instead reuse the qun_list_album_v2 web API (the same one
// get_group_album_list uses) and reshape into NapCat's
// {album_list, attach_info, has_more} envelope. The web endpoint fetches up
// to 1000 albums in one shot, so attach_info/has_more are ''/false (no cursor
// pagination); cover_url isn't returned by this endpoint.
// get_qun_album_list — NapCat-compatible view of QQ NT's AlbumService.
groupAction({
name: 'get_qun_album_list',
readOnly: true,
returns: 'NapCat 风格的相册列表封套:{album_list, attach_info, has_more}(本实现 attach_info 恒为空串、has_more 恒为 false)。',
returns: 'NapCat 风格的相册列表封套:{album_list, attach_info, has_more}。',
returnsSchema: {
type: 'object',
properties: {
@@ -48,30 +44,37 @@ export const actions = [
type: 'object',
properties: {
album_id: { type: 'string', description: '相册 id' },
album_name: { type: 'string', description: '相册名称' },
create_time: { type: 'integer', description: '相册创建时间(unix 秒)' },
pic_num: { type: 'integer', description: '相册内照片数量' },
name: { type: 'string', description: '相册名称' },
create_time: { type: 'string', description: '相册创建时间(unix 秒)' },
upload_number: { type: 'string', description: '相册内媒体数量' },
creator: {
type: 'object',
description: '相册创建者信息',
properties: {
uin: { type: 'string', description: '创建者 QQ 号' },
uid: { type: 'string', description: '创建者 UID' },
nick: { type: 'string', description: '创建者原始 Unicode 昵称' },
},
},
},
required: ['album_id', 'album_name', 'create_time', 'pic_num'],
required: ['album_id', 'name', 'create_time', 'upload_number'],
},
},
attach_info: { type: 'string', description: '分页游标(本 web 实现一次取满,恒为空串)' },
has_more: { type: 'boolean', description: '是否还有更多(本 web 实现恒为 false)' },
attach_info: { type: 'string', description: '下一页分页游标' },
has_more: { type: 'boolean', description: '是否还有更多' },
},
required: ['album_list', 'attach_info', 'has_more'],
},
params: {
attach_info: f.string().default(''),
},
run: async (p, ctx) => {
const albumList = await ctx.bridge.apis.groupAlbum.list(p.group_id);
const result = await ctx.bridge.apis.groupAlbum.listQun(p.group_id, p.attach_info);
return okResponse({
album_list: albumList.map((a) => ({
album_id: a.id,
album_name: a.name,
create_time: a.createTime,
pic_num: a.picNum,
})),
attach_info: '',
has_more: false,
});
album_list: result.albumList,
attach_info: result.attachInfo,
has_more: result.hasMore,
} as unknown as JsonValue);
},
}),
@@ -166,4 +169,3 @@ export const actions = [
},
}),
];
@@ -188,6 +188,7 @@ export const ELEMENT_CODECS = {
async fromSegment(data, options) {
const id = intOr(data.id, 0);
if (id === 0) return null;
const meta = options?.resolveReplyMeta?.(id) ?? null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
@@ -199,19 +200,27 @@ export const ELEMENT_CODECS = {
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
return element;
}
}
// The id is known locally, but it came from an OIDB-only/synthetic
// message and therefore has no QQ server sequence. Treating the opaque
// OneBot id as a direct sequence would publish a malformed reply.
if (meta?.sequenceAuthoritative === false) {
throw new MessageElementValidationError(
'INVALID_FIELD',
`reply target ${id} has no authoritative QQ sequence`,
'reply',
);
}
// Backward-compatible path: allow direct seq reply IDs.
return id > 0 ? { type: 'reply', replySeq: id } : null;
},
+3 -1
View File
@@ -180,7 +180,7 @@ async function runConvertAndDispatch(ctx: OneBotInstanceContext, log: Logger, ev
error instanceof Error ? (error.stack ?? error.message) : String(error),
);
}
ctx.dispatchEvent(converted);
ctx.dispatchEvent(converted, 'bridge');
log.trace(() => [`recv ${event.kind} ⇒ ${String(converted.post_type ?? '?')} (${Date.now() - startedAt}ms)`]);
}
@@ -190,6 +190,7 @@ function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEven
isGroup: true,
targetId: event.groupId,
sequence: event.msgSeq,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
@@ -209,6 +210,7 @@ function cachePrivateMessageMeta(
isGroup: false,
targetId: sessionId,
sequence: msgSeq,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random,
+15 -4
View File
@@ -1,7 +1,7 @@
import type { Bridge } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { WebHonorType } from '@snowluma/protocol/web/group-honor';
import type { ApiActionContext } from './api-handler';
import type { ApiActionContext, MessageSendResult } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
import type { MessageStore } from './message-store';
@@ -38,7 +38,7 @@ import {
} from './modules/message-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { ReactionStore } from './reaction-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import { hasAuthoritativeSequence, type JsonObject, type MessageMeta, type OneBotConfig } from './types';
export interface OneBotInstanceContext {
uin: string;
@@ -53,12 +53,18 @@ export interface OneBotInstanceContext {
config: OneBotConfig;
musicSignUrl?: string;
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
dispatchEvent(event: JsonObject): void;
dispatchEvent(event: JsonObject, source?: 'bridge' | 'send'): void;
}
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, messageStore, mediaStore, reactionStore } = ref;
const reportSelfSent = async (result: Promise<MessageSendResult>) => {
const settled = await result;
if (settled.echoEvent) ref.dispatchEvent(settled.echoEvent, 'send');
return settled;
};
return {
bridge,
@@ -71,7 +77,10 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
),
canSendImage: () => true,
canSendRecord: () => true,
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
sendPrivateMessage: (userId, message, autoEscape, tempGroupId) =>
tempGroupId === undefined
? reportSelfSent(sendPrivateMessage(ref, userId, message, autoEscape))
: sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId),
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
getFriendList: () => getFriendList(bridge),
@@ -99,12 +108,14 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
if (!hasAuthoritativeSequence(meta)) throw new Error('message has no authoritative QQ sequence');
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
},
fetchEmojiLikeUsers: async (messageId, emojiId, count, offset = 0) => {
const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found');
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
if (!hasAuthoritativeSequence(meta)) throw new Error('message has no authoritative QQ sequence');
const raw = reactionStore.listUsers(meta.targetId, meta.sequence, emojiId, count, offset);
const users = raw.map(r => ({ uin: r.operatorUin, uid: r.operatorUid, setAt: r.setAt }));
const cachedCount = reactionStore.countUsers(meta.targetId, meta.sequence, emojiId);
+55 -7
View File
@@ -29,6 +29,11 @@ import {
type NetworkShutdownResult,
} from './network';
import { ReactionStore } from './reaction-store';
import {
sameSelfSentMessage,
selfSentEventKey,
SELF_SENT_ECHO_WINDOW_MS,
} from './self-sent-event';
import type { ApiResponse, JsonObject, JsonValue, MessageMeta, OneBotConfig } from './types';
const moduleLog = createLogger('Event');
@@ -51,6 +56,8 @@ export class OneBotInstance {
private readonly startedAt = Date.now();
/** Per-conversation last-reply timestamp for the `#sl` cooldown. */
private readonly statusCommandCooldown = new Map<string, number>();
/** Action-side events awaiting a possible canonical QQ echo. */
private readonly pendingSelfSentEchoes = new Map<string, { event: JsonObject; expiresAt: number }>();
private eventPipeline: EventPipelineHandle | null = null;
private eventPipelineDrain: Promise<void> = Promise.resolve();
private disposePromise: Promise<NetworkShutdownResult> | null = null;
@@ -137,7 +144,7 @@ export class OneBotInstance {
config,
musicSignUrl: globalSettings.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event) => this.dispatchEvent(event),
dispatchEvent: (event, source = 'bridge') => this.dispatchEvent(event, source),
};
this.ctx = ctx;
@@ -271,17 +278,58 @@ export class OneBotInstance {
return this.pids.size === 0;
}
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
// Built-in `#sl`: always cache + log first (a swallowed `#sl` is still
// observable locally); only forwarding to downstream adapters is gated.
if (this.handleStatusCommand(event)) return;
private dispatchEvent(event: JsonObject, source: 'bridge' | 'send' = 'bridge'): void {
if (source === 'bridge') {
this.cacheMessageEvent(event);
if (this.consumePendingSelfSentEcho(event)) {
this.log.trace(
'duplicate self-message echo suppressed message_id=%d message_seq=%d',
toInt(event.message_id),
toInt(event.message_seq),
);
return;
}
} else {
this.cacheMessageEvent(event);
this.rememberPendingSelfSentEcho(event);
}
// The send path already logged the real peer and payload. Logging its
// synthetic event here would produce a second, less accurate "received"
// line whose private user_id points at the bot itself.
if (source === 'bridge') this.logReceivedMessage(event);
// Built-in `#sl` only consumes events observed from QQ. Action-originated
// messages must not recursively trigger the command handler.
if (source === 'bridge' && this.handleStatusCommand(event)) return;
void this.networkManager.emitEvent(event).catch((err) => {
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
private rememberPendingSelfSentEcho(event: JsonObject): void {
const key = selfSentEventKey(event);
if (key === null) return;
const now = Date.now();
this.sweepPendingSelfSentEchoes(now);
this.pendingSelfSentEchoes.set(key, { event, expiresAt: now + SELF_SENT_ECHO_WINDOW_MS });
}
private consumePendingSelfSentEcho(event: JsonObject): boolean {
const key = selfSentEventKey(event);
if (key === null) return false;
const now = Date.now();
this.sweepPendingSelfSentEchoes(now);
const pending = this.pendingSelfSentEchoes.get(key);
if (!pending || !sameSelfSentMessage(pending.event, event)) return false;
this.pendingSelfSentEchoes.delete(key);
return true;
}
private sweepPendingSelfSentEchoes(now: number): void {
for (const [key, pending] of this.pendingSelfSentEchoes) {
if (pending.expiresAt <= now) this.pendingSelfSentEchoes.delete(key);
}
}
/**
* Built-in `#sl` status command. Returns `true` when the event matched AND
* `swallow` is configured — the caller then skips `emitEvent` so downstream
+6 -1
View File
@@ -15,7 +15,12 @@ export { MessageElementValidationError } from '@snowluma/protocol/element-manife
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
resolveReplyMeta?: (replyMessageId: number) => {
senderUin: number;
time: number;
random: number;
sequenceAuthoritative?: boolean;
} | null;
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
resolveContactArk?: (contactType: string, contactId: number) => string | null | Promise<string | null>;
musicSignUrl?: string;
+142 -11
View File
@@ -1,12 +1,20 @@
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import { createLogger } from '@snowluma/common/logger';
import type { JsonObject, MessageMeta } from './types';
import { openSqliteDb } from './sqlite-open';
const log = createLogger('OneBot.MessageStore');
export interface ReadSessionTargets {
groupIds: number[];
privateUserIds: number[];
}
export interface StoreEventOptions {
/** False for locally reconstructed events whose sequence QQ never confirmed. */
sequenceAuthoritative?: boolean;
}
export class MessageStore {
private readonly db: DatabaseSync;
private readonly stmtStoreEvent: StatementSync;
@@ -18,6 +26,7 @@ export class MessageStore {
private readonly stmtListEventsAnchored: StatementSync;
private readonly stmtListEventsAnchoredForward: StatementSync;
private readonly stmtListEventsLatest: StatementSync;
private readonly stmtFindLatestAuthoritativeSequence: StatementSync;
private readonly stmtListIncomingC2CSessions: StatementSync;
constructor(dbPath: string) {
@@ -30,12 +39,13 @@ export class MessageStore {
// Database instance — `close()` finalizes them automatically.
this.stmtStoreEvent = this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, ?, 0, 0, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
sequence_authoritative = excluded.sequence_authoritative,
event_name = excluded.event_name,
timestamp = excluded.timestamp,
data = excluded.data`,
@@ -43,12 +53,13 @@ export class MessageStore {
this.stmtStoreMeta = this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
(message_hash, is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
sequence_authoritative = excluded.sequence_authoritative,
event_name = excluded.event_name,
client_sequence = excluded.client_sequence,
random = excluded.random,
@@ -60,27 +71,28 @@ export class MessageStore {
);
this.stmtFindMeta = this.db.prepare(
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
'SELECT is_group, session_id, sequence, sequence_authoritative, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
);
this.stmtResolveReplyGroup = this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
WHERE is_group = 1 AND session_id = ? AND message_hash = ? AND sequence_authoritative = 1
LIMIT 1`,
);
this.stmtResolveReplyPrivate = this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 0 AND message_hash = ?
WHERE is_group = 0 AND message_hash = ? AND sequence_authoritative = 1
LIMIT 1`,
);
this.stmtListEventsAnchored = this.db.prepare(
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
AND sequence_authoritative = 1 AND sequence > 0 AND sequence <= ?
ORDER BY sequence DESC
LIMIT ?`,
);
@@ -88,7 +100,8 @@ export class MessageStore {
this.stmtListEventsAnchoredForward = this.db.prepare(
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence >= ?
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
AND sequence_authoritative = 1 AND sequence > 0 AND sequence >= ?
ORDER BY sequence ASC
LIMIT ?`,
);
@@ -97,10 +110,19 @@ export class MessageStore {
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
AND sequence_authoritative = 1 AND sequence > 0
ORDER BY sequence DESC
LIMIT ?`,
);
this.stmtFindLatestAuthoritativeSequence = this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = ? AND session_id = ? AND sequence_authoritative = 1 AND sequence > 0
ORDER BY sequence DESC
LIMIT 1`,
);
this.stmtListIncomingC2CSessions = this.db.prepare(
`SELECT session_id
FROM messages
@@ -124,13 +146,23 @@ export class MessageStore {
sessionId: number,
sequence: number,
eventName: string,
event: JsonObject
event: JsonObject,
options: StoreEventOptions = {},
): void {
if (!isValidMessageId(messageId)) return;
const json = JSON.stringify(event);
const timestamp = toInt(event.time);
this.stmtStoreEvent.run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
this.stmtStoreEvent.run(
messageId,
isGroup ? 1 : 0,
sessionId,
sequence,
options.sequenceAuthoritative === false ? 0 : 1,
eventName,
timestamp,
json,
);
}
storeMeta(messageId: number, meta: MessageMeta): void {
@@ -140,6 +172,7 @@ export class MessageStore {
meta.isGroup ? 1 : 0,
meta.targetId,
meta.sequence,
meta.sequenceAuthoritative === false ? 0 : 1,
meta.eventName,
meta.clientSequence,
meta.random,
@@ -166,6 +199,7 @@ export class MessageStore {
is_group: number;
session_id: number;
sequence: number;
sequence_authoritative: number;
event_name: string;
client_sequence: number;
random: number;
@@ -178,6 +212,7 @@ export class MessageStore {
isGroup: row.is_group === 1,
targetId: row.session_id,
sequence: row.sequence,
sequenceAuthoritative: row.sequence_authoritative === 1,
eventName: row.event_name,
clientSequence: row.client_sequence,
random: row.random,
@@ -240,6 +275,16 @@ export class MessageStore {
return result;
}
findLatestAuthoritativeSequence(isGroup: boolean, sessionId: number): number | null {
if (!Number.isInteger(sessionId) || sessionId <= 0) return null;
const row = this.stmtFindLatestAuthoritativeSequence.get(
isGroup ? 1 : 0,
sessionId,
) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) return null;
return row.sequence;
}
/**
* Build read-report targets from current groups plus genuine incoming C2C
* sessions. `is_group = 0` alone is insufficient: group temp sessions use
@@ -277,6 +322,7 @@ export class MessageStore {
is_group INTEGER NOT NULL,
session_id INTEGER NOT NULL,
sequence INTEGER NOT NULL,
sequence_authoritative INTEGER NOT NULL DEFAULT 1,
event_name TEXT NOT NULL,
client_sequence INTEGER NOT NULL DEFAULT 0,
random INTEGER NOT NULL DEFAULT 0,
@@ -284,7 +330,92 @@ export class MessageStore {
data TEXT
)
`);
this.migrateSequenceAuthority();
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_authoritative_seq ON messages(is_group, session_id, sequence_authoritative, sequence)');
}
private migrateSequenceAuthority(): void {
const columns = this.db.prepare('PRAGMA table_info(messages)').all() as Array<{ name: string }>;
if (columns.some((column) => column.name === 'sequence_authoritative')) return;
this.db.exec('BEGIN IMMEDIATE');
try {
this.db.exec(
'ALTER TABLE messages ADD COLUMN sequence_authoritative INTEGER NOT NULL DEFAULT 1',
);
const result = this.db.prepare(`
UPDATE messages
SET sequence_authoritative = 0
WHERE sequence > 0
AND data IS NOT NULL
AND CASE WHEN json_valid(data) THEN (
(
is_group = 1
AND (
(
json_extract(data, '$.post_type') = 'message_sent'
AND json_extract(data, '$.message_type') = 'group'
AND random = sequence
AND json_extract(data, '$.message[0].type') IN ('file', 'video')
)
OR
(
json_extract(data, '$.post_type') = 'message'
AND json_extract(data, '$.message_type') = 'group'
AND json_type(data, '$.group_name') IS NULL
AND json_type(data, '$.sender') = 'object'
AND json_extract(data, '$.sender.user_id') = json_extract(data, '$.user_id')
AND json_extract(data, '$.sender.nickname') = ''
AND json_extract(data, '$.sender.card') = ''
AND json_extract(data, '$.sender.role') = 'member'
AND json_extract(data, '$.sender.sex') = 'unknown'
AND json_extract(data, '$.sender.age') = 0
)
OR
(
json_extract(data, '$.post_type') = 'message'
AND json_extract(data, '$.message_type') = 'group'
AND json_extract(data, '$.user_id') = 0
AND json_extract(data, '$.time') = 0
)
OR
(
json_extract(data, '$.post_type') = 'message'
AND json_extract(data, '$.message_type') = 'group'
AND json_extract(data, '$.user_id') = 0
AND json_array_length(json_extract(data, '$.message')) = 1
AND json_extract(data, '$.message[0].type') = 'text'
AND json_extract(data, '$.message[0].data.text') = '[引用消息]'
)
)
)
OR
(
is_group = 0
AND random = 0
AND client_sequence = 0
AND json_extract(data, '$.post_type') = 'message'
AND json_extract(data, '$.message_type') = 'private'
AND json_extract(data, '$.sub_type') = 'friend'
AND json_type(data, '$.target_id') IS NULL
AND json_type(data, '$.sender') = 'object'
AND json_extract(data, '$.sender.user_id') = json_extract(data, '$.user_id')
AND json_extract(data, '$.sender.nickname') = ''
AND json_extract(data, '$.sender.sex') = 'unknown'
AND json_extract(data, '$.sender.age') = 0
)
) ELSE 0 END
`).run();
this.db.exec('COMMIT');
log.info(
'message-store schema migrated: sequence authority added, synthetic rows marked=%d',
Number(result.changes),
);
} catch (error) {
this.db.exec('ROLLBACK');
throw error;
}
}
}
+157 -45
View File
@@ -9,7 +9,8 @@ import type { OneBotInstanceContext } from '../instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id';
import { MessageElementValidationError, parseMessage } from '../message-parser';
import type { MessageStore } from '../message-store';
import type { JsonArray, JsonObject, JsonValue, MessageMeta } from '../types';
import { sameSelfSentMessage } from '../self-sent-event';
import { hasAuthoritativeSequence, type JsonArray, type JsonObject, type JsonValue, type MessageMeta } from '../types';
const log = createLogger('OneBot');
@@ -91,7 +92,7 @@ export async function getGroupMsgHistory(
let anchorSequence: number | undefined;
if (hasAnchor) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) return [];
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) return [];
anchorSequence = meta.sequence;
}
@@ -119,7 +120,7 @@ export async function getFriendMsgHistory(
let anchorSequence: number | undefined;
if (hasAnchor) {
const meta = messageStore.findMeta(messageId as number);
if (!meta || meta.isGroup || meta.targetId !== userId || meta.sequence <= 0) return [];
if (!hasAuthoritativeSequence(meta) || meta.isGroup || meta.targetId !== userId) return [];
anchorSequence = meta.sequence;
}
@@ -163,15 +164,20 @@ export async function getGroupHistory(
let anchorSeq = 0;
if (hasAnchor) {
const meta = ref.messageStore.findMeta(messageId as number);
if (!meta || !meta.isGroup || meta.targetId !== groupId || meta.sequence <= 0) {
if (!hasAuthoritativeSequence(meta) || !meta.isGroup || meta.targetId !== groupId) {
// Anchor we don't know — best effort from the local store.
return getGroupMsgHistory(ref.messageStore, groupId, messageId, count, reverseOrder);
}
anchorSeq = meta.sequence;
} else {
const latest = ref.messageStore.listSessionEvents(true, groupId, 1);
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(true, groupId) ?? 0;
}
log.debug(
'group history anchor selected: group=%d source=%s anchorSeq=%d',
groupId,
hasAnchor ? 'message_id' : 'latest_authoritative',
anchorSeq,
);
if (anchorSeq > 0) {
try {
@@ -190,6 +196,12 @@ export async function getGroupHistory(
out.push(sanitizeMessageEventForApi(json)); // sanitized for the API (matches the local path)
}
if (out.length > 0) return out;
log.debug(
'group history server fetch returned no usable messages: group=%d anchorSeq=%d count=%d; using local store',
groupId,
anchorSeq,
want,
);
} catch (err) {
log.warn(
'group history server fetch failed: group=%d anchorSeq=%d count=%d reverseOrder=%s error=%s; using local store',
@@ -237,7 +249,7 @@ export async function getFriendHistory(
: null;
const belongsToPeer = meta?.targetId === userId
|| (meta?.targetId === ref.selfId && toHistInt(storedEvent?.target_id) === userId);
if (!meta || meta.isGroup || meta.sequence <= 0 || !belongsToPeer) {
if (!hasAuthoritativeSequence(meta) || meta.isGroup || !belongsToPeer) {
return getFriendMsgHistory(ref.messageStore, userId, messageId, count, reverseOrder);
}
anchorSeq = meta.sequence;
@@ -245,9 +257,14 @@ export async function getFriendHistory(
// Current rows are keyed by conversation peer, so the latest local anchor
// covers both incoming and self-sent messages. Legacy sender-keyed rows are
// repaired when they are fetched through an explicit anchor.
const latest = ref.messageStore.listSessionEvents(false, userId, 1);
anchorSeq = latest.length ? toHistInt(latest[latest.length - 1].message_seq) : 0;
anchorSeq = ref.messageStore.findLatestAuthoritativeSequence(false, userId) ?? 0;
}
log.debug(
'friend history anchor selected: user=%d source=%s anchorSeq=%d',
userId,
hasAnchor ? 'message_id' : 'latest_authoritative',
anchorSeq,
);
if (anchorSeq > 0) {
try {
@@ -278,6 +295,12 @@ export async function getFriendHistory(
out.push(sanitizeMessageEventForApi(json));
}
if (out.length > 0) return out;
log.debug(
'friend history server fetch returned no usable messages: user=%d anchorSeq=%d count=%d; using local store',
userId,
anchorSeq,
want,
);
}
} catch (err) {
log.warn(
@@ -368,7 +391,18 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
) as JsonArray;
const fallback = buildBackfillEvent(targetId, replySeq, quotedSender,
reply.replyTime ?? 0, segments, ref.selfId, isGroup, session);
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, fallback);
// Inline quote metadata proves what was displayed, but not that replySeq
// still names a server-backed roam message. Keep it queryable via
// get_msg without letting it become a history/recall/reply anchor.
ref.messageStore.storeEvent(
targetId,
isGroup,
session,
replySeq,
eventName,
fallback,
{ sequenceAuthoritative: false },
);
return;
} catch (err) {
log.warn('reply-target backfill tier-2 failed (%s)', err instanceof Error ? err.message : String(err));
@@ -381,7 +415,15 @@ export async function backfillReplyTarget(ref: HistoryRef, event: QQEventVariant
const placeholder = buildBackfillEvent(targetId, replySeq, quotedSender,
reply?.replyTime ?? 0, [{ type: 'text', data: { text: '[引用消息]' } }],
ref.selfId, isGroup, session);
ref.messageStore.storeEvent(targetId, isGroup, session, replySeq, eventName, placeholder);
ref.messageStore.storeEvent(
targetId,
isGroup,
session,
replySeq,
eventName,
placeholder,
{ sequenceAuthoritative: false },
);
}
// Build a stored-message event for a backfilled reply target (Tier 2/3).
@@ -451,6 +493,9 @@ function toHistInt(value: unknown): number {
}
export async function deleteMessage(bridge: BridgeInterface, meta: MessageMeta): Promise<void> {
if (!hasAuthoritativeSequence(meta)) {
throw new Error('message has no authoritative QQ sequence and cannot be recalled');
}
if (meta.isGroup) {
await bridge.apis.message.recallGroup(meta.targetId, meta.sequence);
} else {
@@ -472,6 +517,9 @@ export async function setEssenceMessage(
): Promise<void> {
const meta = messageStore.findMeta(messageId);
if (!meta || !meta.isGroup) throw new Error('message not found or not a group message');
if (!hasAuthoritativeSequence(meta)) {
throw new Error('message has no authoritative QQ sequence and cannot be marked as essence');
}
await bridge.apis.interaction.setEssence(meta.targetId, meta.sequence, meta.random, enable);
}
@@ -497,35 +545,58 @@ export async function setEssenceMessage(
* copy. Centralizes the `isGroup ↔ eventName ↔ hashMessageIdInt32 event
* constant` coupling that was hand-paired in six send/forward paths — a
* mismatch there silently produced a wrong message_id or wrong event
* attribution. Returns the derived message id.
* attribution. Returns the derived message id and, for an eligible plain C2C
* Action send, an event for the OneBot dispatch path when QQ has not already
* supplied the canonical echo.
*/
async function finalizeSend(
ref: OneBotInstanceContext,
isGroup: boolean,
targetId: number,
receipt: { sequence: number; clientSequence: number; random: number; timestamp: number },
receipt: {
messageId?: number;
sequence: number;
clientSequence: number;
random: number;
timestamp: number;
},
elements: MessageElement[],
): Promise<number> {
reportEcho = false,
): Promise<MessageSendResult> {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const messageId = hashMessageIdInt32(receipt.sequence, targetId, eventName);
const sequenceAuthoritative = Number.isInteger(receipt.sequence) && receipt.sequence > 0;
const opaqueMessageId = receipt.messageId ?? 0;
// Ordinary sends use QQ's real sequence so receive/send paths derive the same
// OneBot id. OIDB-only sends (notably group files) have no QQ sequence: keep
// their opaque local id separate instead of feeding a file hash into protocol
// operations as if it were a server sequence (#254).
const messageId = sequenceAuthoritative
? hashMessageIdInt32(receipt.sequence, targetId, eventName)
: Number.isInteger(opaqueMessageId) && opaqueMessageId !== 0
? opaqueMessageId
: hashMessageIdInt32(0, targetId, eventName);
ref.cacheMessageMeta(messageId, {
isGroup,
targetId,
sequence: receipt.sequence,
sequenceAuthoritative,
eventName,
clientSequence: receipt.clientSequence,
random: receipt.random,
timestamp: receipt.timestamp,
});
await cacheSelfSentMessage(ref, {
const echoEvent = await cacheSelfSentMessage(ref, {
isGroup,
sessionId: targetId,
messageId,
sequence: receipt.sequence,
sequenceAuthoritative,
timestamp: receipt.timestamp,
elements,
});
return messageId;
return reportEcho && echoEvent && sequenceAuthoritative && receipt.timestamp > 0
? { messageId, echoEvent }
: { messageId };
}
async function cacheSelfSentMessage(
@@ -535,19 +606,27 @@ async function cacheSelfSentMessage(
sessionId: number; // groupId or peer userId
messageId: number;
sequence: number;
sequenceAuthoritative: boolean;
timestamp: number;
elements: MessageElement[];
},
): Promise<void> {
const { isGroup, sessionId, messageId, sequence, timestamp, elements } = options;
if (!Number.isInteger(messageId) || messageId === 0) return;
): Promise<JsonObject | null> {
const {
isGroup,
sessionId,
messageId,
sequence,
sequenceAuthoritative,
timestamp,
elements,
} = options;
if (!Number.isInteger(messageId) || messageId === 0) return null;
// Defensive: tests mock `ref.messageStore` as `{ findEvent: ... } as any`
// without the full MessageStore surface. Production always has it. Bail
// quietly when the helper isn't there — the user-visible `cacheMessageMeta`
// already covers recall/delete; only `/get_msg` lookup degrades.
// Defensive: tests may mock `ref.messageStore` without the full MessageStore
// surface. Production always has it. Without storage, recall still works via
// cacheMessageMeta, but `/get_msg` and the synthetic event are unavailable.
const storeEvent = (ref.messageStore as { storeEvent?: typeof ref.messageStore.storeEvent }).storeEvent;
if (typeof storeEvent !== 'function') return;
if (typeof storeEvent !== 'function') return null;
try {
// We deliberately pass no URL resolvers — for a synthetic self-sent
@@ -595,16 +674,32 @@ async function cacheSelfSentMessage(
event.target_id = sessionId;
}
// Store directly via messageStore (bypassing dispatchEvent — we
// don't want to broadcast this synthetic event over the WS bridge;
// the QQ server's own echo-back is the source of truth for that).
storeEvent.call(ref.messageStore, messageId, isGroup, sessionId, sequence, eventName, event);
// QQ can win the race between the send receipt and local event
// construction. Keep its richer canonical event and let the already-run
// bridge dispatch remain the single downstream notification.
const existing = ref.messageStore.findEvent(messageId);
if (existing && sameSelfSentMessage(existing, event)) return null;
// Persist before dispatch so `/get_msg` is immediately consistent for a
// client reacting to the synthetic message_sent notification.
storeEvent.call(
ref.messageStore,
messageId,
isGroup,
sessionId,
sequence,
eventName,
event,
{ sequenceAuthoritative },
);
return event;
} catch (err) {
// Never let event-cache failures sink the send call — recall + return
// value are what callers care about; /get_msg degrading to "not found"
// is the worst case here and matches the previous behaviour.
// Never turn a successful QQ send into a failed Action after the fact.
// The warning keeps the loss observable; `/get_msg` and the optional
// synthetic event degrade together while recall still uses cached meta.
log.warn('[OneBot] failed to cache self-sent message %d: %s',
messageId, err instanceof Error ? err.message : String(err));
return null;
}
}
@@ -653,6 +748,7 @@ export async function sendPrivateMessage(
senderUin,
time,
random: meta?.random ?? 0,
sequenceAuthoritative: meta?.sequenceAuthoritative,
};
}
const meta = ref.messageStore.findMeta(replyMessageId);
@@ -661,6 +757,7 @@ export async function sendPrivateMessage(
senderUin: ref.selfId,
time: meta.timestamp,
random: meta.random,
sequenceAuthoritative: meta.sequenceAuthoritative,
};
}
return null;
@@ -808,9 +905,11 @@ export async function sendPrivateMessage(
}
if (!lastReceipt) throw new Error('message is empty');
const messageId = await finalizeSend(ref, false, userId, lastReceipt, elements);
return { messageId };
// Dedicated C2C file sends may split one Action into several QQ messages.
// A single synthetic event would misrepresent that wire behaviour, so only
// report the one-batch friend path handled by sendPrivate().
const reportEcho = tempGroupId === undefined && allFileElements.length === 0;
return finalizeSend(ref, false, userId, lastReceipt, elements, reportEcho);
}
export async function sendGroupMessage(
@@ -824,6 +923,8 @@ export async function sendGroupMessage(
return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId);
},
resolveReplyMeta: (replyMessageId) => {
const meta = ref.messageStore.findMeta(replyMessageId);
if (!meta || !meta.isGroup || meta.targetId !== groupId) return null;
const event = ref.messageStore.findEvent(replyMessageId);
if (event) {
return {
@@ -833,10 +934,16 @@ export async function sendGroupMessage(
time: typeof event.time === 'number'
? event.time
: parseInt(String(event.time || '0'), 10),
random: 0,
random: meta?.random ?? 0,
sequenceAuthoritative: meta?.sequenceAuthoritative,
};
}
return null;
return {
senderUin: ref.selfId,
time: meta.timestamp,
random: meta.random,
sequenceAuthoritative: meta.sequenceAuthoritative,
};
},
resolveMentionUid: (targetUin) => ref.bridge.resolveUserUid(targetUin, groupId),
resolveContactArk: (contactType, contactId) => resolveContactArk(ref, contactType, contactId),
@@ -904,14 +1011,19 @@ export async function sendGroupMessage(
if (!lastReceipt) {
let h = 0;
for (let i = 0; i < fileId.length; i++) h = ((h << 5) - h + fileId.charCodeAt(i)) | 0;
lastReceipt = { messageId: 0, sequence: h & 0x7FFFFFFF, clientSequence: 0, random: h & 0x7FFFFFFF, timestamp: Math.floor(Date.now() / 1000) };
const localSeed = h & 0x7FFFFFFF;
lastReceipt = {
messageId: hashMessageIdInt32(localSeed, groupId, GROUP_MESSAGE_EVENT),
sequence: 0,
clientSequence: 0,
random: localSeed,
timestamp: Math.floor(Date.now() / 1000),
};
}
}
if (!lastReceipt) throw new Error('message is empty');
const messageId = await finalizeSend(ref, true, groupId, lastReceipt, elements);
return { messageId };
return finalizeSend(ref, true, groupId, lastReceipt, elements);
}
export interface ForwardPreviewMeta {
@@ -935,7 +1047,7 @@ export async function sendGroupForwardMessage(
const forwardId = await ref.bridge.apis.forward.upload(nodes, groupId);
const previewElement = buildForwardPreviewElement(forwardId, nodes, true, meta);
const receipt = await ref.bridge.apis.message.sendGroup(groupId, [previewElement]);
const messageId = await finalizeSend(ref, true, groupId, receipt, [previewElement]);
const { messageId } = await finalizeSend(ref, true, groupId, receipt, [previewElement]);
return { messageId, forwardId };
}
@@ -953,7 +1065,7 @@ export async function sendPrivateForwardMessage(
const forwardId = await ref.bridge.apis.forward.upload(nodes, undefined, userId);
const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta);
const receipt = await ref.bridge.apis.message.sendPrivate(userId, [previewElement]);
const messageId = await finalizeSend(ref, false, userId, receipt, [previewElement]);
const { messageId } = await finalizeSend(ref, false, userId, receipt, [previewElement]);
return { messageId, forwardId };
}
@@ -1002,10 +1114,10 @@ export async function forwardSingleMessage(
let messageIdOut: number;
if (target.groupId) {
receipt = await ref.bridge.apis.message.sendGroup(target.groupId, elements);
messageIdOut = await finalizeSend(ref, true, target.groupId, receipt, elements);
({ messageId: messageIdOut } = await finalizeSend(ref, true, target.groupId, receipt, elements));
} else {
receipt = await ref.bridge.apis.message.sendPrivate(target.userId!, elements);
messageIdOut = await finalizeSend(ref, false, target.userId!, receipt, elements);
({ messageId: messageIdOut } = await finalizeSend(ref, false, target.userId!, receipt, elements));
}
return { messageId: messageIdOut };
+44
View File
@@ -0,0 +1,44 @@
import type { JsonObject } from './types';
export const SELF_SENT_ECHO_WINDOW_MS = 120_000;
/**
* Match the action-side copy of a sent message with QQ's later canonical
* echo. The message hash alone is insufficient because it is a signed 32-bit
* value and can collide; sequence, conversation and a bounded time window are
* part of the identity as well.
*/
export function sameSelfSentMessage(left: JsonObject, right: JsonObject): boolean {
const leftKey = selfSentEventKey(left);
const rightKey = selfSentEventKey(right);
if (leftKey === null || leftKey !== rightKey) return false;
const leftTime = toInt(left.time);
const rightTime = toInt(right.time);
return leftTime > 0
&& rightTime > 0
&& Math.abs(leftTime - rightTime) * 1000 <= SELF_SENT_ECHO_WINDOW_MS;
}
/** Stable identity for a self-sent event, excluding its bounded timestamp. */
export function selfSentEventKey(event: JsonObject): string | null {
if (event.post_type !== 'message_sent') return null;
if (event.message_type !== 'private' && event.message_type !== 'group') return null;
const messageId = toInt(event.message_id);
const sequence = toInt(event.message_seq);
const session = event.message_type === 'group'
? toInt(event.group_id)
: (toInt(event.target_id) || toInt(event.user_id));
if (messageId === 0 || sequence <= 0 || session <= 0) return null;
return `${event.message_type}:${session}:${sequence}:${messageId}`;
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.trunc(parsed);
}
return 0;
}
+11 -1
View File
@@ -122,12 +122,23 @@ export interface MessageMeta {
isGroup: boolean;
targetId: number;
sequence: number;
/** Whether `sequence` was confirmed by QQ and is safe for protocol actions. */
sequenceAuthoritative: boolean;
eventName: string;
clientSequence: number;
random: number;
timestamp: number;
}
/** True only when a stored sequence can safely be sent back to QQ. */
export function hasAuthoritativeSequence(
meta: MessageMeta | null | undefined,
): meta is MessageMeta {
return meta?.sequenceAuthoritative === true
&& Number.isInteger(meta.sequence)
&& meta.sequence > 0;
}
export const RETCODE = {
ACTION_FAILED: 100,
INTERNAL_ERROR: 1200,
@@ -152,4 +163,3 @@ export function failedResponse(retcode: number, wording: string): ApiResponse {
};
}
export type { JsonArray, JsonObject, JsonPrimitive, JsonValue } from '@snowluma/common/json';
@@ -188,6 +188,7 @@ describe('backfillReplyTarget', () => {
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'group', user_id: 800 }),
{ sequenceAuthoritative: false },
);
});
@@ -207,6 +208,7 @@ describe('backfillReplyTarget', () => {
expect(store.storeEvent).toHaveBeenCalledWith(
targetId, true, 700, 123, GROUP_MESSAGE_EVENT,
expect.objectContaining({ message_id: targetId, message_type: 'group' }),
{ sequenceAuthoritative: false },
);
});
});
@@ -0,0 +1,60 @@
import { describe, expect, it, vi } from 'vitest';
import type { ApiActionContext } from '../src/api-handler';
import { ApiHandler } from '../src/api-handler';
import { ACTION_REGISTRY } from '../src/actions';
describe('get_collection_list action', () => {
it('validates and forwards category and count to the collection API', async () => {
const result = {
errCode: 0 as const,
errMsg: '',
collectionSearchList: {
collectionItemList: [],
hasMore: false,
bottomTimeStamp: '0',
},
};
const list = vi.fn(async () => result);
const bridge = { apis: { collection: { list } } };
const handler = new ApiHandler({ bridge } as unknown as ApiActionContext);
const response = await handler.handle('get_collection_list', {
category: '4',
count: '25',
});
expect(response).toMatchObject({ status: 'ok', retcode: 0, data: result });
expect(list).toHaveBeenCalledWith(4, 25);
const registered = ACTION_REGISTRY.resolve('get_collection_list');
if (!registered || registered.kind === 'raw') throw new Error('get_collection_list is not registered');
expect(registered.action.doc.summary).toBe('获取收藏列表');
expect(registered.action.doc.params.map((param) => param.name)).toEqual(['category', 'count']);
const itemSchema = registered.action.doc.returnsSchema?.properties
?.collectionSearchList?.properties?.collectionItemList?.items;
expect(Object.keys(itemSchema?.properties ?? {})).toEqual(expect.arrayContaining([
'cid', 'author', 'category', 'modifyTime', 'summary',
]));
expect(Object.keys(itemSchema?.properties?.summary?.properties ?? {})).toEqual([
'textSummary',
'linkSummary',
'gallerySummary',
'audioSummary',
'videoSummary',
'fileSummary',
'locationSummary',
'richMediaSummary',
]);
});
it.each([0, 501])('rejects invalid count %s before calling the collection API', async (count) => {
const list = vi.fn();
const bridge = { apis: { collection: { list } } };
const handler = new ApiHandler({ bridge } as unknown as ApiActionContext);
const response = await handler.handle('get_collection_list', { category: 0, count });
expect(response).toMatchObject({ status: 'failed', retcode: 1400 });
expect(list).not.toHaveBeenCalled();
});
});
@@ -145,6 +145,7 @@ describe('registerEventPipeline', () => {
expect(metaCalls[0].meta.isGroup).toBe(false);
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
expect(metaCalls[0].meta.sequence).toBe(11);
expect(metaCalls[0].meta.sequenceAuthoritative).toBe(true);
expect(metaCalls[0].meta.random).toBe(555);
expect(dispatchCalls).toHaveLength(1);
+86 -25
View File
@@ -9,12 +9,14 @@ import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '@snowluma/protocol/qq-info';
import type { MessageMeta } from '../src/types';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/message-id';
function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
return {
isGroup: true,
targetId: 100,
sequence: 555,
sequenceAuthoritative: true,
eventName: 'group_message',
clientSequence: 0,
random: 0,
@@ -70,6 +72,7 @@ const APIS_ROUTING: Record<string, [string, string]> = {
getStrangerStatus: ['extras', 'getStrangerStatus'],
fetchAiVoiceList: ['extras', 'fetchAiVoiceList'],
fetchAiVoice: ['extras', 'fetchAiVoice'],
sendAiVoice: ['extras', 'sendAiVoice'],
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
@@ -646,6 +649,19 @@ describe('extended-actions / set_/complete_/cancel_group_todo', () => {
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects a local-only message id without calling the group todo protocol', async () => {
const setGroupTodo = vi.fn(async () => {});
const bridge = fakeBridge({ setGroupTodo });
const ctx = fakeCtx(bridge, {
getMessageMeta: () => fakeMeta({ sequence: 0, sequenceAuthoritative: false }),
});
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
expect(setGroupTodo).not.toHaveBeenCalled();
});
it('rejects missing params', async () => {
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 });
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { group_id: 1 });
@@ -654,6 +670,26 @@ describe('extended-actions / set_/complete_/cancel_group_todo', () => {
});
});
describe('extended-actions / set_group_reaction', () => {
it('rejects a local-only message id without calling the reaction protocol', async () => {
const setGroupReaction = vi.fn(async () => {});
const bridge = fakeBridge({ setGroupReaction });
const ctx = fakeCtx(bridge, {
getMessageMeta: () => fakeMeta({ sequence: 0, sequenceAuthoritative: false }),
});
const res = await makeHandler(ctx).handle('set_group_reaction', {
group_id: 100,
message_id: 1,
code: '66',
is_set: true,
});
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
expect(setGroupReaction).not.toHaveBeenCalled();
});
});
// ─── Tier 2: nc_get_user_status ───
describe('extended-actions / nc_get_user_status', () => {
@@ -757,19 +793,37 @@ describe('extended-actions / get_ai_record', () => {
});
describe('extended-actions / send_group_ai_record', () => {
it('side-effects fetchAiVoice (no URL fetch) and returns message_id=0', async () => {
const fetchAiVoice = vi.fn(async () => ({ fileUuid: 'uuid' }));
it('returns the canonical group message id from the matched self-message receipt', async () => {
const sendAiVoice = vi.fn(async () => ({
sequence: 319,
}));
const fetchGroupPttUrlByNode = vi.fn();
const bridge = fakeBridge({
fetchAiVoice: fetchAiVoice as any,
sendAiVoice: sendAiVoice as any,
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_group_ai_record', {
group_id: 100, character: 'v', text: 'hi',
});
expect(fetchAiVoice).toHaveBeenCalledOnce();
expect(sendAiVoice).toHaveBeenCalledWith(100, 'v', 'hi', 1);
expect(fetchGroupPttUrlByNode).not.toHaveBeenCalled();
expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } });
expect(res).toMatchObject({
status: 'ok',
data: { message_id: hashMessageIdInt32(319, 100, GROUP_MESSAGE_EVENT) },
});
});
it('surfaces a missing canonical receipt instead of returning a fake id', async () => {
const bridge = fakeBridge({
sendAiVoice: (async () => {
throw new Error('AI voice was published but no matching group-message receipt arrived');
}) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_group_ai_record', {
group_id: 100, character: 'v', text: 'hi',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
expect(res.wording).toMatch(/group-message receipt/i);
});
});
@@ -1269,31 +1323,38 @@ describe('extended-actions / TierB ③ share + doubt + robot-option', () => {
});
});
// ─── napcat-parity: get_qun_album_list (NapCat-shaped envelope over existing web API) ───
// SnowLuma already exposes the qun_list_album_v2 web API as get_group_album_list
// (raw array). NapCat's get_qun_album_list wraps it as {album_list, attach_info,
// has_more} with {album_id, album_name, create_time, ...} items. We add the
// NapCat-named/shaped action reusing the same bridge call.
// ─── napcat-parity: get_qun_album_list (QQ NT AlbumService) ───
describe('extended-actions / get_qun_album_list', () => {
it('maps the album list into the napcat {album_list, attach_info, has_more} envelope', async () => {
const list = vi.fn(async () => [
{ id: 'a1', name: '相册一', picNum: 5, createTime: 1700000000 },
{ id: 'a2', name: '相册二', picNum: 0, createTime: 1700000100 },
]);
const bridge = fakeBridge({ apis: { groupAlbum: { list } } });
const res = await makeHandler(fakeCtx(bridge)).handle('get_qun_album_list', { group_id: 12345 });
expect(list).toHaveBeenCalledWith(12345);
it('forwards the pagination cursor and returns the native AlbumService envelope', async () => {
const albumList = [{
album_id: 'a1',
name: '相册一',
create_time: '1700000000',
upload_number: '5',
creator: { uin: '10001', nick: '😂[em]e328514[/em]' },
}];
const listQun = vi.fn(async () => ({
albumList,
attachInfo: 'next-cursor',
hasMore: true,
}));
const bridge = fakeBridge({ apis: { groupAlbum: { listQun } } });
const res = await makeHandler(fakeCtx(bridge)).handle('get_qun_album_list', {
group_id: 12345,
attach_info: 'current-cursor',
});
expect(listQun).toHaveBeenCalledWith(12345, 'current-cursor');
expect(res.status).toBe('ok');
expect(res.data).toMatchObject({ attach_info: '', has_more: false });
expect((res.data as any).album_list).toEqual([
{ album_id: 'a1', album_name: '相册一', create_time: 1700000000, pic_num: 5 },
{ album_id: 'a2', album_name: '相册二', create_time: 1700000100, pic_num: 0 },
]);
expect(res.data).toEqual({
album_list: albumList,
attach_info: 'next-cursor',
has_more: true,
});
});
it('surfaces failure as a failed response', async () => {
const list = vi.fn(async () => { throw new Error('no pskey'); });
const bridge = fakeBridge({ apis: { groupAlbum: { list } } });
const listQun = vi.fn(async () => { throw new Error('album service unavailable'); });
const bridge = fakeBridge({ apis: { groupAlbum: { listQun } } });
const res = await makeHandler(fakeCtx(bridge)).handle('get_qun_album_list', { group_id: 1 });
expect(res.status).toBe('failed');
});
@@ -63,6 +63,7 @@ describe('history direction plumbing', () => {
isGroup: true,
targetId: GROUP_ID,
sequence: 500,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -91,6 +92,7 @@ describe('history direction plumbing', () => {
isGroup: false,
targetId: FRIEND_ID,
sequence: 700,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -124,6 +126,15 @@ describe('history direction plumbing', () => {
message_id: 1,
message_seq: 900,
});
messageStore.storeEvent(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, {
post_type: 'message_sent',
message_type: 'group',
group_id: GROUP_ID,
message_id: 2,
message_seq: 1799283572,
user_id: SELF_ID,
message: [{ type: 'file', data: { file_id: 'gfid-local' } }],
}, { sequenceAuthoritative: false });
const ref = {
selfId: SELF_ID,
bridge: {
@@ -136,6 +147,31 @@ describe('history direction plumbing', () => {
const messages = await getGroupHistory(ref, GROUP_ID, 0, 20, false);
expect(messages.map((message) => message.message_seq)).toEqual([899, 900]);
expect(fetchHistory).toHaveBeenCalledWith(GROUP_ID, 900, 20, SELF_ID, true);
});
it('does not use an explicitly requested local-only id as a server history anchor', async () => {
const fetchHistory = vi.fn(async () => [groupMessage(1799283572)]);
messageStore.storeEvent(2, true, GROUP_ID, 1799283572, GROUP_MESSAGE_EVENT, {
post_type: 'message_sent',
message_type: 'group',
group_id: GROUP_ID,
message_id: 2,
message_seq: 1799283572,
user_id: SELF_ID,
message: [{ type: 'file', data: { file_id: 'gfid-local' } }],
}, { sequenceAuthoritative: false });
const ref = {
selfId: SELF_ID,
bridge: {
apis: { message: { getGroupHistory: fetchHistory } },
},
messageStore,
converterCtx,
} as any;
await expect(getGroupHistory(ref, GROUP_ID, 2, 20, false)).resolves.toEqual([]);
expect(fetchHistory).not.toHaveBeenCalled();
});
it('rejects a private anchor from a different friend conversation', async () => {
@@ -144,6 +180,7 @@ describe('history direction plumbing', () => {
isGroup: false,
targetId: 987654321,
sequence: 800,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -2,7 +2,8 @@ import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import type { OneBotInstanceContext } from '../src/instance-context';
import { sendGroupMessage } from '../src/modules/message-actions';
import { deleteMessage, sendGroupMessage, setEssenceMessage } from '../src/modules/message-actions';
import type { MessageMeta } from '../src/types';
function instanceContext(sendGroup: ReturnType<typeof vi.fn>): OneBotInstanceContext {
const bridge = {
@@ -95,3 +96,33 @@ describe('outbound message validation at the Action boundary', () => {
expect(bridgeSend).not.toHaveBeenCalled();
});
});
describe('server-sequence action validation', () => {
const localOnlyMeta: MessageMeta = {
isGroup: true,
targetId: 12345,
sequence: 0,
sequenceAuthoritative: false,
eventName: 'group_message',
clientSequence: 0,
random: 0,
timestamp: 0,
};
it('does not recall a message that has only a local id', async () => {
const recallGroup = vi.fn();
const bridge = { apis: { message: { recallGroup } } } as unknown as BridgeInterface;
await expect(deleteMessage(bridge, localOnlyMeta)).rejects.toThrow('no authoritative QQ sequence');
expect(recallGroup).not.toHaveBeenCalled();
});
it('does not mark a message that has only a local id as essence', async () => {
const setEssence = vi.fn();
const bridge = { apis: { interaction: { setEssence } } } as unknown as BridgeInterface;
const store = { findMeta: () => localOnlyMeta } as any;
await expect(setEssenceMessage(bridge, store, 1, true)).rejects.toThrow('no authoritative QQ sequence');
expect(setEssence).not.toHaveBeenCalled();
});
});
+159
View File
@@ -3,6 +3,7 @@ import { MessageStore } from '../src/message-store';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import fs from 'fs';
import path from 'path';
import { DatabaseSync } from 'node:sqlite';
describe('MessageStore', () => {
const testDbPath = path.join('data', 'test', 'messages-test.db');
@@ -39,6 +40,7 @@ describe('MessageStore', () => {
isGroup: true,
targetId: groupId,
sequence,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -61,6 +63,7 @@ describe('MessageStore', () => {
isGroup: false,
targetId: senderUin,
sequence,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -105,6 +108,7 @@ describe('MessageStore', () => {
isGroup: true,
targetId: sessionId,
sequence,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -117,6 +121,7 @@ describe('MessageStore', () => {
isGroup: false,
targetId: sessionId,
sequence,
sequenceAuthoritative: true,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
@@ -170,6 +175,7 @@ describe('MessageStore', () => {
isGroup: true,
targetId: 123456,
sequence: 100,
sequenceAuthoritative: true,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 1,
random: 12345,
@@ -218,6 +224,159 @@ describe('MessageStore', () => {
expect(messages.map((message) => message.message_seq)).toEqual([1, 2, 3]);
});
it('excludes unconfirmed sequences from replies and history anchors (#254)', () => {
const groupId = 123456;
store.storeEvent(1, true, groupId, 9748, GROUP_MESSAGE_EVENT, {
post_type: 'message',
message_type: 'group',
group_id: groupId,
group_name: 'Test group',
message_id: 1,
message_seq: 9748,
});
store.storeEvent(2, true, groupId, 1799283572, GROUP_MESSAGE_EVENT, {
post_type: 'message_sent',
message_type: 'group',
group_id: groupId,
message_id: 2,
message_seq: 1799283572,
message: [{ type: 'file', data: { file: 'test.bin' } }],
}, { sequenceAuthoritative: false });
expect(store.findLatestAuthoritativeSequence(true, groupId)).toBe(9748);
expect(store.listSessionEvents(true, groupId).map((message) => message.message_seq)).toEqual([9748]);
expect(store.resolveReplySequence(true, groupId, 2)).toBeNull();
expect(store.findMeta(2)).toMatchObject({
sequence: 1799283572,
sequenceAuthoritative: false,
});
});
it('migrates legacy synthetic group-file and reply-backfill sequences (#254)', () => {
const groupId = 123456;
store.close();
const legacy = new DatabaseSync(testDbPath);
legacy.exec(`
DROP TABLE messages;
CREATE TABLE messages (
message_hash INTEGER PRIMARY KEY,
is_group INTEGER NOT NULL,
session_id INTEGER NOT NULL,
sequence INTEGER NOT NULL,
event_name TEXT NOT NULL,
client_sequence INTEGER NOT NULL DEFAULT 0,
random INTEGER NOT NULL DEFAULT 0,
timestamp INTEGER NOT NULL DEFAULT 0,
data TEXT
)
`);
const insert = legacy.prepare(`
INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
VALUES (?, 1, ?, ?, ?, 0, ?, ?, ?)
`);
const insertPrivate = legacy.prepare(`
INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
VALUES (?, 0, ?, ?, ?, 0, ?, ?, ?)
`);
insert.run(1, groupId, 9748, GROUP_MESSAGE_EVENT, 0, 1700000000, JSON.stringify({
time: 1700000000,
post_type: 'message',
message_type: 'group',
group_id: groupId,
message_id: 1,
message_seq: 9748,
user_id: 222,
message: [{ type: 'text', data: { text: 'real' } }],
}));
insert.run(2, groupId, 1799283572, GROUP_MESSAGE_EVENT, 1799283572, 1700000100, JSON.stringify({
time: 1700000100,
post_type: 'message_sent',
message_type: 'group',
group_id: groupId,
message_id: 2,
message_seq: 1799283572,
user_id: 10001,
message: [{ type: 'file', data: { file: 'test.bin' } }],
}));
insert.run(3, groupId, 1813530543, GROUP_MESSAGE_EVENT, 0, 1700000200, JSON.stringify({
time: 1700000200,
post_type: 'message',
message_type: 'group',
group_id: groupId,
message_id: 3,
message_seq: 1813530543,
user_id: 0,
message: [{ type: 'text', data: { text: '[引用消息]' } }],
}));
insert.run(4, groupId, 9732, GROUP_MESSAGE_EVENT, 0, 0, JSON.stringify({
time: 0,
post_type: 'message',
message_type: 'group',
group_id: groupId,
message_id: 4,
message_seq: 9732,
user_id: 0,
message: [{ type: 'text', data: { text: '[已删除]' } }],
}));
insert.run(5, groupId, 1813530544, GROUP_MESSAGE_EVENT, 0, 1700000300, JSON.stringify({
time: 1700000300,
post_type: 'message',
message_type: 'group',
group_id: groupId,
message_id: 5,
message_seq: 1813530544,
user_id: 800,
message: [{ type: 'text', data: { text: 'quoted inline content' } }],
sender: {
user_id: 800,
nickname: '',
card: '',
role: 'member',
sex: 'unknown',
age: 0,
},
anonymous: null,
}));
insertPrivate.run(6, 555, 800, PRIVATE_MESSAGE_EVENT, 1234, 1700000400, JSON.stringify({
time: 1700000400,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 6,
message_seq: 800,
user_id: 555,
message: [{ type: 'text', data: { text: 'real private message' } }],
sender: { user_id: 555, nickname: 'Alice', sex: 'unknown', age: 0 },
}));
insertPrivate.run(7, 555, 1813530545, PRIVATE_MESSAGE_EVENT, 0, 1700000500, JSON.stringify({
time: 1700000500,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
message_seq: 1813530545,
user_id: 555,
message: [{ type: 'text', data: { text: 'quoted private content' } }],
sender: { user_id: 555, nickname: '', sex: 'unknown', age: 0 },
}));
legacy.close();
store = new MessageStore(testDbPath);
expect(store.findLatestAuthoritativeSequence(true, groupId)).toBe(9748);
expect(store.listSessionEvents(true, groupId).map((message) => message.message_seq)).toEqual([9748]);
expect(store.findMeta(2)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(3)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(4)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findMeta(5)).toMatchObject({ sequenceAuthoritative: false });
expect(store.findLatestAuthoritativeSequence(false, 555)).toBe(800);
expect(store.findMeta(6)).toMatchObject({ sequenceAuthoritative: true });
expect(store.findMeta(7)).toMatchObject({ sequenceAuthoritative: false });
});
});
describe('listReadSessions', () => {
@@ -0,0 +1,239 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../core/src/bridge/bridge-interface';
import { OneBotInstance } from '../src/instance';
import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context';
import { hashMessageIdInt32, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import { TempSessionStore } from '../src/temp-session-store';
import type { JsonObject, OneBotConfig } from '../src/types';
const SELF_ID = 10001;
const PEER_ID = 20002;
const RECEIPT = {
messageId: 123456,
sequence: 87,
clientSequence: 9,
random: 123456,
timestamp: 1_700_000_000,
};
function makeContext(receipt = RECEIPT): {
ctx: OneBotInstanceContext;
dispatchEvent: ReturnType<typeof vi.fn<(event: JsonObject) => void>>;
events: Map<number, JsonObject>;
} {
const events = new Map<number, JsonObject>();
const dispatchEvent = vi.fn<(event: JsonObject) => void>();
const bridge = {
identity: { nickname: 'SnowLuma' },
apis: {
message: {
sendPrivate: vi.fn(async () => receipt),
sendGroupTempMessage: vi.fn(async () => receipt),
},
},
resolveUserUid: vi.fn(async () => 'u_peer'),
} as unknown as BridgeInterface;
const ctx = {
uin: String(SELF_ID),
selfId: SELF_ID,
bridge,
messageStore: {
findEvent: (messageId: number) => events.get(messageId) ?? null,
findMeta: () => null,
resolveReplySequence: () => null,
storeEvent: (messageId: number, _isGroup: boolean, _sessionId: number, _sequence: number, _eventName: string, event: JsonObject) => {
events.set(messageId, event);
},
},
mediaStore: {},
reactionStore: {},
tempSessions: new TempSessionStore(),
converterCtx: {},
config: {
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
} as OneBotConfig,
cacheMessageMeta: vi.fn(),
dispatchEvent,
} as unknown as OneBotInstanceContext;
return { ctx, dispatchEvent, events };
}
interface InstanceHarness {
dispatch(event: JsonObject, source: 'send' | 'bridge'): void;
emitEvent: ReturnType<typeof vi.fn<(event: JsonObject) => Promise<void>>>;
stored: Map<number, JsonObject>;
}
function makeInstanceHarness(): InstanceHarness {
const stored = new Map<number, JsonObject>();
const emitEvent = vi.fn(async (_event: JsonObject) => {});
const instance = Object.create(OneBotInstance.prototype) as OneBotInstance;
Object.assign(instance as unknown as Record<string, unknown>, {
bridge: { identity: {} },
ctx: {
config: {
statusCommand: { enabled: false, swallow: false, cooldownSeconds: 5, trigger: '#sl' },
},
},
log: { success: vi.fn(), trace: vi.fn(), warn: vi.fn() },
messageStore: {
findEvent: (messageId: number) => stored.get(messageId) ?? null,
storeEvent: (messageId: number, _isGroup: boolean, _sessionId: number, _sequence: number, _eventName: string, event: JsonObject) => {
stored.set(messageId, event);
},
},
networkManager: { emitEvent },
statusCommandCooldown: new Map(),
pendingSelfSentEchoes: new Map(),
});
const dispatch = (instance as unknown as {
dispatchEvent(event: JsonObject, source: 'send' | 'bridge'): void;
}).dispatchEvent.bind(instance);
return { dispatch, emitEvent, stored };
}
function privateSentEvent(overrides: JsonObject = {}): JsonObject {
return {
time: RECEIPT.timestamp,
self_id: SELF_ID,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: 987654,
message_seq: RECEIPT.sequence,
user_id: SELF_ID,
target_id: PEER_ID,
message: [{ type: 'text', data: { text: 'hello' } }],
raw_message: 'hello',
sender: { user_id: SELF_ID, nickname: 'SnowLuma' },
...overrides,
};
}
describe('OneBot self-sent events', () => {
it('reports a private message sent through an action', async () => {
const { ctx, dispatchEvent } = makeContext();
const api = buildApiContext(ctx);
const result = await api.sendPrivateMessage(PEER_ID, [
{ type: 'text', data: { text: 'hello' } },
], false);
expect(result.messageId).not.toBe(0);
expect(dispatchEvent).toHaveBeenCalledOnce();
expect(dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
self_id: SELF_ID,
user_id: SELF_ID,
target_id: PEER_ID,
message_seq: RECEIPT.sequence,
}), 'send');
});
it('does not report a later QQ echo after the action event', () => {
const { dispatch, emitEvent, stored } = makeInstanceHarness();
const sentEvent = privateSentEvent();
const qqEcho: JsonObject = {
...sentEvent,
raw_message: 'canonical echo',
sender: { user_id: SELF_ID, nickname: 'Server profile' },
};
dispatch(sentEvent, 'send');
dispatch(qqEcho, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
expect(stored.get(987654)?.raw_message).toBe('canonical echo');
});
it('does not dispatch an event for a receipt without a reliable sequence', async () => {
const { ctx, dispatchEvent } = makeContext({ ...RECEIPT, sequence: 0 });
const api = buildApiContext(ctx);
await api.sendPrivateMessage(PEER_ID, [
{ type: 'text', data: { text: 'hello' } },
], false);
expect(dispatchEvent).not.toHaveBeenCalled();
});
it('keeps an earlier QQ echo and does not report the later action event', async () => {
const { ctx, dispatchEvent, events } = makeContext();
const messageId = hashMessageIdInt32(RECEIPT.sequence, PEER_ID, PRIVATE_MESSAGE_EVENT);
const qqEcho: JsonObject = {
time: RECEIPT.timestamp,
self_id: SELF_ID,
post_type: 'message_sent',
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: RECEIPT.sequence,
user_id: SELF_ID,
target_id: PEER_ID,
message: [{ type: 'text', data: { text: 'hello' } }],
raw_message: 'canonical echo',
sender: { user_id: SELF_ID, nickname: 'Server profile' },
};
events.set(messageId, qqEcho);
const api = buildApiContext(ctx);
const result = await api.sendPrivateMessage(PEER_ID, [
{ type: 'text', data: { text: 'hello' } },
], false);
expect(result.messageId).toBe(messageId);
expect(dispatchEvent).not.toHaveBeenCalled();
expect(events.get(messageId)).toBe(qqEcho);
});
it('does not invent a friend event for a group temporary-session send', async () => {
const groupId = 30003;
const { ctx, dispatchEvent } = makeContext();
ctx.tempSessions.record(PEER_ID, groupId);
const api = buildApiContext(ctx);
await api.sendPrivateMessage(PEER_ID, [
{ type: 'text', data: { text: 'hello' } },
], false, groupId);
expect(dispatchEvent).not.toHaveBeenCalled();
});
it('does not suppress a bridge echo that was cached but never reported', () => {
const { dispatch, emitEvent, stored } = makeInstanceHarness();
const cached: JsonObject = {
time: RECEIPT.timestamp,
self_id: SELF_ID,
post_type: 'message_sent',
message_type: 'group',
sub_type: 'normal',
message_id: 7654321,
message_seq: RECEIPT.sequence,
group_id: 30003,
user_id: SELF_ID,
message: [],
raw_message: '',
sender: { user_id: SELF_ID },
};
stored.set(7654321, cached);
dispatch({ ...cached, raw_message: 'canonical echo' }, 'bridge');
expect(emitEvent).toHaveBeenCalledOnce();
expect(stored.get(7654321)?.raw_message).toBe('canonical echo');
});
it('does not suppress a hash collision from another conversation', () => {
const { dispatch, emitEvent } = makeInstanceHarness();
const sentEvent = privateSentEvent();
dispatch(sentEvent, 'send');
dispatch({ ...sentEvent, target_id: PEER_ID + 1 }, 'bridge');
expect(emitEvent).toHaveBeenCalledTimes(2);
});
});
+136 -3
View File
@@ -18,6 +18,7 @@
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context';
import { MessageStore } from '../src/message-store';
import { sendGroupMessage } from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
@@ -29,12 +30,17 @@ function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
function makeCtx(bridge: BridgeInterface, messageStore?: MessageStore): OneBotInstanceContext {
const store = messageStore
?? ({ findEvent: () => null, resolveReplySequence: () => 0 } as any);
return {
uin: '10001',
selfId: 10001,
bridge,
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
cacheMessageMeta: vi.fn(),
messageStore: store,
cacheMessageMeta: messageStore
? (messageId, meta) => messageStore.storeMeta(messageId, meta)
: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
@@ -75,6 +81,133 @@ describe('send_group_msg with {type:"file"} segment', () => {
expect(fileId).toBe('gfid-abc');
});
it('keeps an OIDB-only group file id separate from a QQ server sequence (#254)', async () => {
const messageStore = new MessageStore(':memory:');
try {
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
identity: { nickname: 'Bot' },
apis: {
message: { sendGroup: vi.fn() },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge, messageStore);
const result = await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
}] as any, false);
expect(result.messageId).not.toBe(0);
expect(messageStore.findMeta(result.messageId)).toMatchObject({
sequence: 0,
sequenceAuthoritative: false,
});
expect(messageStore.findEvent(result.messageId)).toMatchObject({ message_seq: 0 });
expect(messageStore.findLatestAuthoritativeSequence(true, 12345)).toBeNull();
} finally {
messageStore.close();
}
});
it('rejects replying to an OIDB-only group file id as a QQ sequence (#254)', async () => {
const messageStore = new MessageStore(':memory:');
try {
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt);
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
identity: { nickname: 'Bot' },
apis: {
message: { sendGroup },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge, messageStore);
const file = await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
}] as any, false);
await expect(sendGroupMessage(ctx, 12345, [
{ type: 'reply', data: { id: file.messageId } },
{ type: 'text', data: { text: 'received' } },
] as any, false)).rejects.toMatchObject({
code: 'INVALID_FIELD',
elementType: 'reply',
});
expect(sendGroup).not.toHaveBeenCalled();
} finally {
messageStore.close();
}
});
it('rejects a local-only reply id even when its full event was not cached', async () => {
const messageStore = new MessageStore(':memory:');
try {
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
apis: { message: { sendGroup } } as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge, messageStore);
messageStore.storeMeta(77, {
isGroup: true,
targetId: 12345,
sequence: 0,
sequenceAuthoritative: false,
eventName: 'group_message',
clientSequence: 0,
random: 42,
timestamp: 1700000000,
});
await expect(sendGroupMessage(ctx, 12345, [
{ type: 'reply', data: { id: 77 } },
{ type: 'text', data: { text: 'received' } },
] as any, false)).rejects.toMatchObject({ code: 'INVALID_FIELD', elementType: 'reply' });
expect(sendGroup).not.toHaveBeenCalled();
} finally {
messageStore.close();
}
});
it('does not apply local-only reply metadata from another group', async () => {
const messageStore = new MessageStore(':memory:');
try {
const sendGroup = vi.fn(async (_groupId: number, _elements: any[]) => goodReceipt);
const bridge = fakeBridge({
identity: { nickname: 'Bot' },
apis: { message: { sendGroup } } as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge, messageStore);
messageStore.storeMeta(77, {
isGroup: true,
targetId: 99999,
sequence: 0,
sequenceAuthoritative: false,
eventName: 'group_message',
clientSequence: 0,
random: 42,
timestamp: 1700000000,
});
await sendGroupMessage(ctx, 12345, [
{ type: 'reply', data: { id: 77 } },
{ type: 'text', data: { text: 'direct sequence' } },
] as any, false);
expect(sendGroup).toHaveBeenCalledWith(12345, [
{ type: 'reply', replySeq: 77 },
{ type: 'text', text: 'direct sequence' },
]);
} finally {
messageStore.close();
}
});
it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => {
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
+5 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb<N, T>` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).",
@@ -16,6 +16,10 @@
"types": "./src/action.ts",
"default": "./src/action.ts"
},
"./collection": {
"types": "./src/collection.ts",
"default": "./src/collection.ts"
},
"./element": {
"types": "./src/element.ts",
"default": "./src/element.ts"
+201
View File
@@ -0,0 +1,201 @@
import type {
bool,
bytes,
double,
int_32,
pb,
pb_repeated,
uint_32,
uint_64,
} from '@snowluma/proton';
/** Weiyun collector common request header. */
export interface CollectionRequestHead {
uin?: pb<1, uint_64>;
sequence?: pb<2, uint_32>;
commandType?: pb<3, uint_32>;
operationId?: pb<4, uint_32>;
clientVersion?: pb<5, uint_64>;
platform?: pb<6, uint_32>;
ticketType?: pb<7, uint_32>;
reserved?: pb<10, uint_32>;
ticket?: pb<11, string>;
field14?: pb<14, uint_32>;
field15?: pb<15, uint_32>;
}
/** Weiyun collector common response header. */
export interface CollectionResponseHead {
retCode?: pb<101, int_32>;
retMsg?: pb<102, string>;
promptMsg?: pb<103, string>;
}
export interface GetCollectionListRequest {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
timeStamp?: pb<4, uint_64>;
orderType?: pb<5, uint_32>;
groupId?: pb<6, uint_64>;
count?: pb<7, uint_32>;
searchDown?: pb<8, uint_32>;
field9?: pb<9, uint_32>;
}
export interface CollectionRequestOperation {
getCollectionList?: pb<20000, GetCollectionListRequest>;
}
export interface CollectionRequestBody {
operation?: pb<1, CollectionRequestOperation>;
}
export interface CollectionAuthor {
type?: pb<1, uint_32>;
numId?: pb<2, uint_64>;
strId?: pb<3, string>;
groupId?: pb<4, uint_64>;
groupName?: pb<5, string>;
uid?: pb<6, string>;
}
export interface CollectionPictureInfo {
url?: pb<1, string>;
field2?: pb<2, bytes>;
field3?: pb<3, bytes>;
field4?: pb<4, string>;
field5?: pb<5, string>;
field6?: pb<6, uint_32>;
field7?: pb<7, uint_32>;
field8?: pb<8, uint_32>;
field9?: pb<9, uint_32>;
author?: pb<10, CollectionAuthor>;
field11?: pb<11, string>;
}
export interface CollectionFileInfo {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_64>;
field3?: pb<3, uint_32>;
field4?: pb<4, string>;
field5?: pb<5, string>;
field6?: pb<6, uint_64>;
field7?: pb<7, bytes>;
field8?: pb<8, bytes>;
field9?: pb<9, uint_32>;
field10?: pb<10, string>;
}
export interface CollectionTextSummary {
text?: pb<1, string>;
truncated?: pb<2, bool>;
}
export interface CollectionRichMediaSummary {
title?: pb<1, string>;
subTitle?: pb<2, string>;
brief?: pb<3, string>;
picList?: pb_repeated<4, CollectionPictureInfo>;
contentType?: pb<5, uint_32>;
originalUri?: pb<6, string>;
publisher?: pb<7, string>;
richMediaVersion?: pb<8, uint_32>;
}
export interface CollectionGallerySummary {
picList?: pb_repeated<1, CollectionPictureInfo>;
field2?: pb<2, string>;
}
export interface CollectionAudioSummary {
field1?: pb<1, uint_32>;
field2?: pb<2, string>;
field3?: pb<3, string>;
}
export interface CollectionVideoSummary {
field1?: pb<1, string>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
field10?: pb<10, uint_32>;
field20?: pb<20, uint_32>;
picture?: pb<21, CollectionPictureInfo>;
field30?: pb<30, uint_32>;
file?: pb<31, CollectionFileInfo>;
}
export interface CollectionFileSummary {
first?: pb<1, CollectionFileInfo>;
second?: pb<2, CollectionFileInfo>;
}
export interface CollectionLocationSummary {
name?: pb<1, string>;
latitude?: pb<2, double>;
longitude?: pb<3, double>;
altitude?: pb<4, double>;
field5?: pb<5, string>;
field6?: pb<6, string>;
}
export interface CollectionLinkSummary {
title?: pb<1, string>;
description?: pb<2, string>;
url?: pb<3, string>;
picList?: pb_repeated<4, CollectionPictureInfo>;
contentType?: pb<5, uint_32>;
originalUri?: pb<6, string>;
publisher?: pb<7, string>;
version?: pb<8, uint_32>;
}
export interface CollectionSummary {
textSummary?: pb<1, CollectionTextSummary>;
richMediaSummary?: pb<2, CollectionRichMediaSummary>;
gallerySummary?: pb<3, CollectionGallerySummary>;
audioSummary?: pb<4, CollectionAudioSummary>;
videoSummary?: pb<5, CollectionVideoSummary>;
fileSummary?: pb<6, CollectionFileSummary>;
locationSummary?: pb<7, CollectionLocationSummary>;
linkSummary?: pb<8, CollectionLinkSummary>;
}
export interface CollectionItem {
cid?: pb<1, string>;
type?: pb<2, uint_32>;
status?: pb<3, uint_32>;
author?: pb<4, CollectionAuthor>;
bid?: pb<5, uint_32>;
field6?: pb<6, uint_32>;
field7?: pb<7, string>;
category?: pb<8, uint_32>;
createTime?: pb<9, uint_64>;
collectTime?: pb<10, uint_64>;
modifyTime?: pb<11, uint_64>;
sequence?: pb<12, uint_64>;
field13?: pb<13, string>;
field14?: pb_repeated<14, string>;
summary?: pb<15, CollectionSummary>;
field16?: pb<16, bool>;
field17?: pb<17, uint_64>;
shareUrl?: pb<18, string>;
field19?: pb<19, uint_32>;
customGroupId?: pb<20, uint_32>;
securityBeat?: pb<21, bool>;
field506?: pb<506, string>;
}
export interface GetCollectionListResponse {
items?: pb_repeated<1, CollectionItem>;
totalCount?: pb<2, uint_32>;
reachedBottom?: pb<3, uint_32>;
}
export interface CollectionResponseOperation {
getCollectionList?: pb<20000, GetCollectionListResponse>;
}
export interface CollectionResponseBody {
operation?: pb<2, CollectionResponseOperation>;
}
+1
View File
@@ -21,6 +21,7 @@
// imports below for any NTV2-named type.
export type * from './action.js';
export type * from './collection.js';
export type * from './element.js';
// NOTE: `highway.ts` intentionally NOT re-exported here — see note above.
export type * from './longmsg.js';
@@ -1,9 +1,76 @@
import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton';
export interface ExtMapEntry {
key?: pb<1, string>;
value?: pb<2, string>;
}
// QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.GetAlbumList
//
// Recovered from QQ NT's AlbumService codec. The service uses the same
// common request/response envelope as the other QunAlbum methods in this
// file; the operation-specific request body only contains the group id and
// the pagination cursor.
export interface GetAlbumListReqData {
groupId?: pb<1, string>;
attachInfo?: pb_optional<2, string>;
}
export interface GetAlbumListRequest {
seq?: pb<1, int_32>;
field2?: pb_optional<2, bytes>;
field3?: pb_optional<3, bytes>;
data?: pb<4, GetAlbumListReqData>;
traceId?: pb<5, string>;
extMap?: pb_repeated<10, ExtMapEntry>;
}
export interface AlbumCreator {
uid?: pb<1, string>;
nick?: pb<2, string>;
isSweet?: pb<5, bool>;
isSpecial?: pb<6, bool>;
isSuperLike?: pb<7, bool>;
customId?: pb<8, string>;
polyId?: pb<9, string>;
portrait?: pb<10, string>;
canFollow?: pb<11, int_32>;
isFollowed?: pb<12, int_32>;
uin?: pb<13, string>;
dittoUin?: pb<14, string>;
}
export interface GroupAlbumInfo {
albumId?: pb<1, string>;
owner?: pb<2, string>;
name?: pb<3, string>;
description?: pb<4, string>;
createTime?: pb<5, uint_64>;
modifyTime?: pb<6, uint_64>;
lastUploadTime?: pb<7, uint_64>;
uploadNumber?: pb<8, uint_64>;
creator?: pb<10, AlbumCreator>;
topFlag?: pb<11, uint_64>;
busiType?: pb<12, int_32>;
status?: pb<13, int_32>;
allowShare?: pb<15, bool>;
isSubscribe?: pb<16, bool>;
bitmap?: pb<17, string>;
isShareAlbum?: pb<18, bool>;
qzAlbumType?: pb<20, int_32>;
coverType?: pb<23, int_32>;
defaultDesc?: pb<26, string>;
sortType?: pb<30, int_32>;
}
export interface GetAlbumListRspData {
albumList?: pb_repeated<1, GroupAlbumInfo>;
attachInfo?: pb<2, string>;
hasMore?: pb<3, bool>;
}
export interface GetAlbumListResponse {
seq?: pb<1, int_32>;
result?: pb<2, int_32>;
errorText?: pb<3, string>;
data?: pb<4, GetAlbumListRspData>;
}
export interface ReqInfo {
groupId?: pb<1, string>;
albumId?: pb<2, string>;
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
@@ -1,7 +1,11 @@
import { protobuf_decode } from '@snowluma/proton';
import type { GroupMemberJoin, GroupMemberLeave } from '../../events';
import type { GroupChange, SelfJoinInGroup } from '@snowluma/proto-defs/notify';
import { decodeNestedOperatorUid, decodeRawOperatorUid, resolveUidToUin } from '../helpers';
import {
decodeGroupChangeOperatorUid,
decodeNestedOperatorUid,
resolveUidToUin,
} from '../helpers';
import type { MsgPushDecoder } from '../registry';
function joinTypeFromOperationType(raw: number): NonNullable<GroupMemberJoin['joinType']> {
@@ -18,7 +22,7 @@ export const decodeGroupMemberJoin: MsgPushDecoder = (ctx) => {
if (!change) return [];
const groupId = change.groupUin ?? 0;
const userUid = change.memberUid ?? '';
const operatorUid = decodeRawOperatorUid(
const operatorUid = decodeGroupChangeOperatorUid(
change.operatorBytes ?? new Uint8Array(0),
'group member increase',
);
@@ -74,11 +78,11 @@ export const decodeGroupMemberLeave: MsgPushDecoder = (ctx) => {
operatorUin = userUin;
} else {
const operatorBytes = change.operatorBytes ?? new Uint8Array(0);
// QQ sends the operator as a raw UTF-8 UID for normal member changes.
// Only the bot-self-kicked variant (decreaseType=3) wraps it in OperatorInfo.
// Self-kick always uses OperatorInfo. Ordinary removals vary between a raw
// UTF-8 UID and the same envelope, so discriminate by its field-1 wire tag.
operatorUid = dt === 3
? decodeNestedOperatorUid(operatorBytes, 'group member decrease type=3')
: decodeRawOperatorUid(operatorBytes, `group member decrease type=${dt}`);
: decodeGroupChangeOperatorUid(operatorBytes, `group member decrease type=${dt}`);
operatorUin = resolveUidToUin(ctx.identity, groupId, operatorUid, 0);
}
const ev: GroupMemberLeave = {
@@ -1,4 +1,5 @@
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { createLogger } from '@snowluma/common/logger';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { SsoGetGroupMsg, SsoGetGroupMsgResponse } from '@snowluma/proto-defs/get-group-msg';
import type { QQEventVariant } from '../events';
@@ -11,6 +12,8 @@ export const SSO_GET_GROUP_MSG_CMD = 'trpc.msg.register_proxy.RegisterProxy.SsoG
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
const log = createLogger('MsgPush.GroupHistory');
interface RawSender {
sendRawPacket(serviceCmd: string, body: Uint8Array, timeoutMs?: number): Promise<SendPacketResult>;
}
@@ -48,6 +51,22 @@ export async function fetchGroupMessageRange(
for (const msg of messages) {
const ctx = buildContextFromMessage(msg, selfUin, identity);
if (!ctx) continue;
// QQ NT turns deleted/body-null roam entries into MsgType::kNull and its
// FilterBlankSeqsMsg pass removes them before exposing history to callers.
// SsoGetGroupMsg still carries a localized placeholder body for some of
// those entries (for example "[已删除]"), so the ordinary content-less
// filter below cannot recognize them. On the wire these null records have
// neither a sender nor a timestamp; require both structural absences rather
// than matching localized text so a real message is never language-filtered.
if (ctx.fromUin <= 0 && ctx.head.timestamp <= 0) {
log.debug(
'dropping QQ null roam record: group=%d seq=%d msgId=%d',
groupUin,
ctx.head.sequence,
ctx.head.msgId,
);
continue;
}
for (const ev of decodeGroupMessage(ctx)) {
if (ev.kind !== 'group_message' || ev.msgSeq <= 0) continue;
// Drop content-less control pushes (the "[空消息]" phantom, #102) just as
@@ -139,6 +139,15 @@ export function decodeNestedOperatorUid(bytes: Uint8Array, context: string): str
return assertOperatorUid(uid, context, bytes);
}
const OPERATOR_INFO_FIELD_TAG = 0x0a;
export function decodeGroupChangeOperatorUid(bytes: Uint8Array, context: string): string {
if (!bytes || bytes.length === 0) return '';
return bytes[0] === OPERATOR_INFO_FIELD_TAG
? decodeNestedOperatorUid(bytes, context)
: decodeRawOperatorUid(bytes, context);
}
export function buildTemplateMap(params: Array<{ name?: string; value?: string }>): Map<string, string> {
const map = new Map<string, string>();
for (const p of params) {
+448
View File
@@ -0,0 +1,448 @@
import type { JsonObject, JsonValue } from '@snowluma/common/json';
import type {
CollectionItem as CollectionItemWire,
CollectionRequestBody,
CollectionRequestHead,
CollectionResponseBody,
CollectionResponseHead,
GetCollectionListRequest,
} from '@snowluma/proto-defs/collection';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
const COLLECTION_ENDPOINT = 'https://collector.weiyun.com/collector.fcg';
const COLLECTION_HOST = 'collector.weiyun.com';
const COLLECTION_OPERATION_ID = 20_000;
const COLLECTION_TICKET_TYPE = 27;
const COLLECTION_APP_ID = 5_004;
const COLLECTION_PAGE_SIZE = 50;
const COLLECTION_MAX_COUNT = 500;
const COLLECTION_MAX_PAGES = 100;
const COLLECTION_TIMEOUT_MS = 10_000;
const COLLECTION_OPERATION_TIMEOUT_MS = 60_000;
const COLLECTION_RESPONSE_LIMIT = 16 * 1024 * 1024;
const INITIAL_TIMESTAMP = 0xFFFF_FFFF_FFFF_FFFFn;
const MAGIC = Uint8Array.from([0x20, 0x13, 0x03, 0x29]);
const VERSION = Uint8Array.from([0x00, 0x01]);
export interface CollectionHttpRequest {
readonly url: string;
readonly headers: Readonly<Record<string, string>>;
readonly body: Uint8Array;
readonly timeoutMs: number;
}
export type CollectionTransport = (request: CollectionHttpRequest) => Promise<Uint8Array>;
export interface GetCollectionListParams {
readonly uin: string;
readonly pskey: string;
readonly category?: number;
readonly count?: number;
readonly transport?: CollectionTransport;
}
export interface CollectionAuthor extends JsonObject {
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
}
export interface CollectionSummary extends JsonObject {
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
}
export interface CollectionItem extends JsonObject {
cid: string;
type: number;
status: number;
author: CollectionAuthor;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummary;
}
export interface CollectionSearchList extends JsonObject {
collectionItemList: CollectionItem[];
hasMore: boolean;
bottomTimeStamp: string;
}
export interface CollectionListResult extends JsonObject {
errCode: 0;
errMsg: string;
collectionSearchList: CollectionSearchList;
}
function positiveUin(value: string): bigint {
if (!/^[1-9]\d*$/.test(value)) throw new Error('collection uin must be a positive integer');
const uin = BigInt(value);
if (uin > INITIAL_TIMESTAMP) throw new Error('collection uin exceeds uint64 range');
return uin;
}
function positiveCount(value: number): number {
if (!Number.isSafeInteger(value) || value < 1 || value > COLLECTION_MAX_COUNT) {
throw new Error(`collection count must be between 1 and ${COLLECTION_MAX_COUNT}`);
}
return value;
}
function validCategory(value: number): number {
if (!Number.isSafeInteger(value) || value < 0) {
throw new Error('collection category must be a non-negative safe integer');
}
return value;
}
function encodeEnvelope(head: Uint8Array, body: Uint8Array): Uint8Array {
const totalLength = 16 + head.length + body.length;
const output = Buffer.allocUnsafe(totalLength);
output.set(MAGIC, 0);
output.set(VERSION, 4);
output.writeUInt32BE(totalLength, 6);
output.writeUInt32BE(body.length, 10);
output.writeUInt16BE(0, 14);
output.set(head, 16);
output.set(body, 16 + head.length);
return output;
}
function decodeEnvelope(bytes: Uint8Array): {
head: CollectionResponseHead;
body: CollectionResponseBody;
} {
const input = Buffer.from(bytes);
if (input.length <= 16) throw new Error('collection response is too short');
if (!input.subarray(0, 4).equals(Buffer.from(MAGIC))) {
throw new Error('collection response has invalid magic');
}
if (!input.subarray(4, 6).equals(Buffer.from(VERSION))) {
throw new Error('collection response has unsupported version');
}
const totalLength = input.readUInt32BE(6);
if (totalLength !== input.length) {
throw new Error(`collection response length mismatch: ${totalLength} != ${input.length}`);
}
const bodyLength = input.readUInt32BE(10);
if (input.readUInt16BE(14) !== 0) throw new Error('collection response has invalid reserved bytes');
if (bodyLength === 0 || bodyLength >= totalLength - 16) {
throw new Error('collection response has invalid body length');
}
const bodyOffset = totalLength - bodyLength;
return {
head: protobuf_decode<CollectionResponseHead>(input.subarray(16, bodyOffset)),
body: protobuf_decode<CollectionResponseBody>(input.subarray(bodyOffset)),
};
}
function jsonSafe(value: unknown): JsonValue {
if (value === null || value === undefined) return null;
if (typeof value === 'bigint') return value.toString();
if (typeof value === 'number') {
if (!Number.isFinite(value)) throw new Error('collection response contains a non-finite number');
return value;
}
if (typeof value === 'string' || typeof value === 'boolean') return value;
if (value instanceof Uint8Array) return Buffer.from(value).toString('base64');
if (Array.isArray(value)) return value.map(jsonSafe);
if (typeof value === 'object') {
const output: JsonObject = {};
for (const [key, field] of Object.entries(value)) output[key] = jsonSafe(field);
return output;
}
throw new Error(`collection response contains unsupported value type: ${typeof value}`);
}
function mapItem(item: CollectionItemWire): CollectionItem {
const author = item.author ?? {};
const summary = item.summary ?? {};
const textSummary = summary.textSummary;
const richMediaSummary = summary.richMediaSummary;
return {
cid: item.cid ?? '',
type: item.type ?? 0,
status: item.status ?? 0,
author: {
type: author.type ?? 0,
numId: (author.numId ?? 0n).toString(),
strId: author.strId ?? '',
groupId: (author.groupId ?? 0n).toString(),
groupName: author.groupName ?? '',
uid: author.uid ?? '',
},
bid: item.bid ?? 0,
category: item.category ?? 0,
createTime: (item.createTime ?? 0n).toString(),
collectTime: (item.collectTime ?? 0n).toString(),
modifyTime: (item.modifyTime ?? 0n).toString(),
sequence: (item.sequence ?? 0n).toString(),
shareUrl: item.shareUrl ?? '',
customGroupId: item.customGroupId ?? 0,
securityBeat: item.securityBeat ?? false,
summary: {
textSummary: textSummary ? {
text: textSummary.text ?? '',
truncated: textSummary.truncated ?? false,
} : null,
linkSummary: jsonSafe(summary.linkSummary),
gallerySummary: jsonSafe(summary.gallerySummary),
audioSummary: jsonSafe(summary.audioSummary),
videoSummary: jsonSafe(summary.videoSummary),
fileSummary: jsonSafe(summary.fileSummary),
locationSummary: jsonSafe(summary.locationSummary),
richMediaSummary: richMediaSummary ? {
title: richMediaSummary.title ?? '',
subTitle: richMediaSummary.subTitle ?? '',
brief: richMediaSummary.brief ?? '',
picList: jsonSafe(richMediaSummary.picList ?? []),
contentType: richMediaSummary.contentType ?? 0,
originalUri: richMediaSummary.originalUri ?? '',
publisher: richMediaSummary.publisher ?? '',
richMediaVersion: richMediaSummary.richMediaVersion ?? 0,
} : null,
},
};
}
function validateItem(item: CollectionItemWire): void {
if (!item.cid) throw new Error('collection item is missing cid');
if (!item.author) throw new Error(`collection item ${item.cid} is missing author`);
if (item.modifyTime === null || item.modifyTime === undefined || item.modifyTime <= 0n) {
throw new Error(`collection item ${item.cid} is missing modifyTime`);
}
}
async function failAfterCleanup(
primaryError: Error,
cleanup?: () => Promise<void>,
): Promise<never> {
if (cleanup) {
try {
await cleanup();
} catch (cleanupError) {
throw new AggregateError(
[primaryError, cleanupError],
`${primaryError.message}; response body cleanup also failed`,
);
}
}
throw primaryError;
}
async function defaultTransport(request: CollectionHttpRequest): Promise<Uint8Array> {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), request.timeoutMs);
try {
const response = await fetch(request.url, {
method: 'POST',
headers: request.headers,
body: Buffer.from(request.body),
signal: controller.signal,
});
if (!response.ok) {
const error = new Error(`collection HTTP request failed: ${response.status} ${response.statusText}`);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
const declaredLength = response.headers.get('content-length');
if (declaredLength !== null) {
if (!/^\d+$/.test(declaredLength)) {
const error = new Error('collection response has invalid content-length');
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
if (Number(declaredLength) > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`);
await failAfterCleanup(
error,
response.body ? () => response.body!.cancel(error) : undefined,
);
}
}
if (!response.body) throw new Error('collection HTTP response has no body');
const reader = response.body.getReader();
const chunks: Uint8Array[] = [];
let total = 0;
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
total += value.length;
if (total > COLLECTION_RESPONSE_LIMIT) {
const error = new Error(`collection response exceeds ${COLLECTION_RESPONSE_LIMIT} bytes`);
await failAfterCleanup(error, () => reader.cancel(error));
}
chunks.push(value);
}
} finally {
reader.releaseLock();
}
const output = Buffer.allocUnsafe(total);
let offset = 0;
for (const chunk of chunks) {
output.set(chunk, offset);
offset += chunk.length;
}
return output;
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
throw new Error(`collection HTTP request timed out after ${request.timeoutMs}ms`, { cause: error });
}
throw error;
} finally {
clearTimeout(timeout);
}
}
function requestBytes(uin: bigint, pskey: string, sequence: number, timeStamp: bigint): Uint8Array {
const head = protobuf_encode<CollectionRequestHead>({
uin,
sequence,
commandType: 1,
operationId: COLLECTION_OPERATION_ID,
clientVersion: 0x6105F5E164Fn,
platform: 4,
ticketType: COLLECTION_TICKET_TYPE,
reserved: 0,
ticket: pskey,
field14: 8,
field15: 9,
});
const request: GetCollectionListRequest = {
field1: 0,
field2: 0,
field3: 0,
timeStamp,
orderType: 2,
groupId: 0n,
count: COLLECTION_PAGE_SIZE,
searchDown: 1,
field9: 0,
};
const body = protobuf_encode<CollectionRequestBody>({
operation: { getCollectionList: request },
});
return encodeEnvelope(head, body);
}
export async function getCollectionList(params: GetCollectionListParams): Promise<CollectionListResult> {
const uin = positiveUin(params.uin);
if (params.pskey === '') throw new Error('collection p_skey is empty');
const category = validCategory(params.category ?? 0);
const count = positiveCount(params.count ?? COLLECTION_PAGE_SIZE);
const targetMatchCount = category === 0 ? count : count + 1;
const transport = params.transport ?? defaultTransport;
const headers = {
'Content-Type': 'application/octet-stream',
Cookie: `uin=${params.uin};vt=${COLLECTION_TICKET_TYPE};vi=${params.pskey};appid=${COLLECTION_APP_ID}`,
Host: COLLECTION_HOST,
Range: 'bytes=0-',
} as const;
const matched: CollectionItem[] = [];
const seen = new Set<string>();
let sequence = 1;
let timeStamp = INITIAL_TIMESTAMP;
let serverHasMore = true;
let errMsg = '';
let pages = 0;
const operationDeadline = Date.now() + COLLECTION_OPERATION_TIMEOUT_MS;
while (matched.length < targetMatchCount && serverHasMore) {
if (pages >= COLLECTION_MAX_PAGES) {
throw new Error(`collection pagination exceeded ${COLLECTION_MAX_PAGES} pages`);
}
const remainingMs = operationDeadline - Date.now();
if (remainingMs <= 0) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
pages += 1;
const responseBytes = await transport({
url: COLLECTION_ENDPOINT,
headers,
body: requestBytes(uin, params.pskey, sequence, timeStamp),
timeoutMs: Math.min(COLLECTION_TIMEOUT_MS, remainingMs),
});
if (Date.now() >= operationDeadline) {
throw new Error(`collection pagination exceeded ${COLLECTION_OPERATION_TIMEOUT_MS}ms`);
}
const response = decodeEnvelope(responseBytes);
const retCode = response.head.retCode ?? 0;
if (retCode !== 0) {
const message = response.head.retMsg || response.head.promptMsg || 'unknown error';
throw new Error(`collection service error ${retCode}: ${message}`);
}
errMsg = response.head.retMsg ?? '';
const page = response.body.operation?.getCollectionList;
if (!page) throw new Error('collection response is missing operation 20000');
const wireItems = page.items ?? [];
serverHasMore = (page.reachedBottom ?? 0) === 0;
let nextTimeStamp: bigint | null = null;
for (const wireItem of wireItems) {
validateItem(wireItem);
const modifyTime = wireItem.modifyTime ?? 0n;
if (nextTimeStamp === null || modifyTime < nextTimeStamp) nextTimeStamp = modifyTime;
const item = mapItem(wireItem);
const identity = `cid:${item.cid}`;
if (seen.has(identity)) continue;
seen.add(identity);
if (category === 0 || item.category === category) matched.push(item);
}
if (matched.length >= targetMatchCount || !serverHasMore) break;
if (wireItems.length === 0 || nextTimeStamp === null || nextTimeStamp === 0n) {
throw new Error('collection pagination made no progress while more data was reported');
}
if (nextTimeStamp >= timeStamp) {
throw new Error(`collection pagination cursor did not decrease: ${nextTimeStamp}`);
}
timeStamp = nextTimeStamp;
sequence += 1;
}
const collectionItemList = matched.slice(0, count);
let publicBottomTimeStamp = 0n;
for (const item of collectionItemList) {
const itemTime = BigInt(item.modifyTime);
if (publicBottomTimeStamp === 0n || itemTime < publicBottomTimeStamp) {
publicBottomTimeStamp = itemTime;
}
}
return {
errCode: 0,
errMsg,
collectionSearchList: {
collectionItemList,
hasMore: category === 0 ? serverHasMore || matched.length > count : matched.length > count,
bottomTimeStamp: publicBottomTimeStamp.toString(),
},
};
}
@@ -119,6 +119,37 @@ describe('fetchGroupMessageRange / SsoGetGroupMsg', () => {
expect(out[0]).toMatchObject({ senderUin: 222, elements: [{ type: 'text', text: 'hi' }] });
});
it('drops QQ null roam records even when they carry a deleted placeholder (#254)', async () => {
const resp = protobuf_encode<SsoGetGroupMsgResponse>({
body: {
groupUin: 9999,
messages: [
{
responseHead: { fromUin: 0, grp: { groupUin: 9999 } },
contentHead: { msgType: 82, sequence: 110, timestamp: 0, msgId: 5110 },
body: { richText: { elems: [{ text: { str: '[已删除]' } }] } },
},
{
responseHead: { fromUin: 222, grp: { groupUin: 9999, memberName: 'Bob' } },
contentHead: { msgType: 82, sequence: 120, timestamp: 1700000120, msgId: 5120 },
body: { richText: { elems: [{ text: { str: 'hi' } }] } },
},
],
},
});
const out = await fetchGroupMessageRange(
{ sendRawPacket: async () => okResult(resp) },
identity,
10001,
9999,
100,
120,
);
expect(out.map((message) => message.msgSeq)).toEqual([120]);
});
it('returns [] on a failed packet or out-of-range request', async () => {
const failSender = { sendRawPacket: async () => ({ success: false, gotResponse: false } as SendPacketResult) };
expect(await fetchGroupMessageRange(failSender, identity, 10001, 9999, 100, 120)).toEqual([]);
@@ -33,11 +33,13 @@ describe('FetchAiVoice namespace', () => {
});
describe('deserialize', () => {
it('returns the first msgInfoBody index when present', () => {
it('returns the first msgInfoBody index', () => {
const node = { fileUuid: 'uuid', subType: 1 };
expect(FetchAiVoice.deserialize({} as any, {
field2: 319,
field3: 20,
msgInfo: { msgInfoBody: [{ index: node }] },
} as any)).toMatchObject(node);
} as any)).toEqual(node);
});
it('returns null when msgInfo is empty / missing', () => {
@@ -54,9 +56,13 @@ describe('FetchAiVoice namespace', () => {
expect(sender.sendRawPacket.mock.calls[0]![0]).toBe('OidbSvcTrpcTcp.0x929b_0');
});
it('returns the parsed index node', async () => {
it('returns the parsed media node', async () => {
const node = { fileUuid: 'uuid', subType: 1 };
const sender = makeSender({ msgInfo: { msgInfoBody: [{ index: node }] } } as any);
const sender = makeSender({
field2: 319,
field3: 20,
msgInfo: { msgInfoBody: [{ index: node }] },
} as any);
const out = await FetchAiVoice.invoke(sender, { groupId: 1, voiceId: 'v', text: 't', chatType: 1, sessionId: 1 });
expect(out).toMatchObject(node);
});
@@ -0,0 +1,512 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import type { bool, int_32, pb, pb_repeated, uint_32, uint_64 } from '@snowluma/proton';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { getCollectionList } from '../../src/web/collection';
interface RequestHeadOracle {
uin?: pb<1, uint_64>;
sequence?: pb<2, uint_32>;
commandType?: pb<3, uint_32>;
operationId?: pb<4, uint_32>;
clientVersion?: pb<5, uint_64>;
platform?: pb<6, uint_32>;
ticketType?: pb<7, uint_32>;
reserved?: pb<10, uint_32>;
ticket?: pb<11, string>;
field14?: pb<14, uint_32>;
field15?: pb<15, uint_32>;
}
interface GetCollectionListRequestOracle {
field1?: pb<1, uint_32>;
field2?: pb<2, uint_32>;
field3?: pb<3, uint_32>;
timeStamp?: pb<4, uint_64>;
orderType?: pb<5, uint_32>;
groupId?: pb<6, uint_64>;
count?: pb<7, uint_32>;
searchDown?: pb<8, uint_32>;
field9?: pb<9, uint_32>;
}
interface RequestOperationOracle {
getCollectionList?: pb<20000, GetCollectionListRequestOracle>;
}
interface RequestBodyOracle {
operation?: pb<1, RequestOperationOracle>;
}
interface ResponseHeadOracle {
trace?: pb<1, string>;
retCode?: pb<101, int_32>;
retMsg?: pb<102, string>;
promptMsg?: pb<103, string>;
}
interface CollectionAuthorOracle {
type?: pb<1, uint_32>;
numId?: pb<2, uint_64>;
strId?: pb<3, string>;
groupId?: pb<4, uint_64>;
groupName?: pb<5, string>;
uid?: pb<6, string>;
}
interface CollectionTextSummaryOracle {
text?: pb<1, string>;
truncated?: pb<2, bool>;
}
interface CollectionSummaryOracle {
textSummary?: pb<1, CollectionTextSummaryOracle>;
}
interface CollectionItemOracle {
cid?: pb<1, string>;
type?: pb<2, uint_32>;
status?: pb<3, uint_32>;
author?: pb<4, CollectionAuthorOracle>;
bid?: pb<5, uint_32>;
category?: pb<8, uint_32>;
createTime?: pb<9, uint_64>;
collectTime?: pb<10, uint_64>;
modifyTime?: pb<11, uint_64>;
sequence?: pb<12, uint_64>;
summary?: pb<15, CollectionSummaryOracle>;
shareUrl?: pb<18, string>;
customGroupId?: pb<20, uint_32>;
securityBeat?: pb<21, bool>;
}
interface GetCollectionListResponseOracle {
items?: pb_repeated<1, CollectionItemOracle>;
totalCount?: pb<2, uint_32>;
reachedBottom?: pb<3, uint_32>;
}
interface ResponseOperationOracle {
getCollectionList?: pb<20000, GetCollectionListResponseOracle>;
}
interface ResponseBodyOracle {
operation?: pb<2, ResponseOperationOracle>;
}
function encodeEnvelope(head: Uint8Array, body: Uint8Array): Uint8Array {
const totalLength = 16 + head.length + body.length;
const output = Buffer.alloc(totalLength);
output.set([0x20, 0x13, 0x03, 0x29, 0x00, 0x01], 0);
output.writeUInt32BE(totalLength, 6);
output.writeUInt32BE(body.length, 10);
output.set(head, 16);
output.set(body, 16 + head.length);
return output;
}
function decodeRequestEnvelope(bytes: Uint8Array): {
head: RequestHeadOracle;
request: GetCollectionListRequestOracle;
} {
const input = Buffer.from(bytes);
expect(Array.from(input.subarray(0, 6))).toEqual([0x20, 0x13, 0x03, 0x29, 0x00, 0x01]);
expect(input.readUInt32BE(6)).toBe(input.length);
const bodyLength = input.readUInt32BE(10);
const headEnd = input.length - bodyLength;
const head = protobuf_decode<RequestHeadOracle>(input.subarray(16, headEnd));
const body = protobuf_decode<RequestBodyOracle>(input.subarray(headEnd));
const request = body.operation?.getCollectionList;
if (!request) throw new Error('missing collection request body');
return { head, request };
}
function successResponse(items: CollectionItemOracle[], reachedBottom = 1): Uint8Array {
return encodeEnvelope(
protobuf_encode<ResponseHeadOracle>({ trace: 'response' }),
protobuf_encode<ResponseBodyOracle>({
operation: {
getCollectionList: {
items,
totalCount: items.length,
reachedBottom,
},
},
}),
);
}
function errorResponse(retCode: number, retMsg: string): Uint8Array {
return encodeEnvelope(
protobuf_encode<ResponseHeadOracle>({ trace: 'response', retCode, retMsg }),
protobuf_encode<ResponseBodyOracle>({ operation: { getCollectionList: {} } }),
);
}
describe('getCollectionList', () => {
afterEach(() => vi.unstubAllGlobals());
it('uses the Weiyun collection envelope and maps the public result', async () => {
const transport = vi.fn(async (request: {
url: string;
headers: Readonly<Record<string, string>>;
body: Uint8Array;
timeoutMs: number;
}) => {
expect(request.url).toBe('https://collector.weiyun.com/collector.fcg');
expect(request.headers.Cookie).toBe('uin=10001;vt=27;vi=ticket-value;appid=5004');
expect(request.headers.Range).toBe('bytes=0-');
expect(request.timeoutMs).toBe(10_000);
const { head, request: body } = decodeRequestEnvelope(request.body);
expect(head).toMatchObject({
uin: 10001n,
sequence: 1,
commandType: 1,
operationId: 20000,
clientVersion: 0x6105F5E164Fn,
platform: 4,
ticketType: 27,
ticket: 'ticket-value',
field14: 8,
field15: 9,
});
expect(body).toMatchObject({
field1: null,
field2: null,
field3: null,
timeStamp: 0xFFFF_FFFF_FFFF_FFFFn,
orderType: 2,
groupId: null,
count: 50,
searchDown: 1,
field9: null,
});
return successResponse([{
cid: 'cid-1',
type: 1,
status: 0,
author: {
type: 2,
numId: 123n,
strId: 'author-id',
groupId: 456n,
groupName: 'group-name',
uid: 'u_author',
},
bid: 3,
category: 4,
createTime: 1_000n,
collectTime: 1_100n,
modifyTime: 1_200n,
sequence: 1_300n,
summary: { textSummary: { text: 'hello', truncated: false } },
shareUrl: 'https://example.invalid/share',
customGroupId: 5,
securityBeat: true,
}]);
});
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 0,
count: 50,
transport,
});
expect(result).toEqual({
errCode: 0,
errMsg: '',
collectionSearchList: {
collectionItemList: [{
cid: 'cid-1',
type: 1,
status: 0,
author: {
type: 2,
numId: '123',
strId: 'author-id',
groupId: '456',
groupName: 'group-name',
uid: 'u_author',
},
bid: 3,
category: 4,
createTime: '1000',
collectTime: '1100',
modifyTime: '1200',
sequence: '1300',
summary: {
textSummary: { text: 'hello', truncated: false },
linkSummary: null,
gallerySummary: null,
audioSummary: null,
videoSummary: null,
fileSummary: null,
locationSummary: null,
richMediaSummary: null,
},
shareUrl: 'https://example.invalid/share',
customGroupId: 5,
securityBeat: true,
}],
hasMore: false,
bottomTimeStamp: '1200',
},
});
expect(transport).toHaveBeenCalledTimes(1);
});
it('filters categories while following a strictly decreasing cursor', async () => {
const cursors: bigint[] = [];
const sequences: number[] = [];
const transport = vi.fn(async (request: { body: Uint8Array }) => {
const decoded = decodeRequestEnvelope(request.body);
cursors.push(decoded.request.timeStamp ?? 0n);
sequences.push(decoded.head.sequence ?? 0);
if (cursors.length === 1) {
return successResponse([{
cid: 'other',
author: { numId: 1n },
category: 2,
modifyTime: 1_200n,
}], 0);
}
return successResponse([{
cid: 'match',
author: { numId: 1n },
category: 4,
modifyTime: 900n,
}], 1);
});
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
});
expect(cursors).toEqual([0xFFFF_FFFF_FFFF_FFFFn, 1_200n]);
expect(sequences).toEqual([1, 2]);
expect(result.collectionSearchList.collectionItemList.map((item) => item.cid)).toEqual(['match']);
expect(result.collectionSearchList.hasMore).toBe(false);
expect(result.collectionSearchList.bottomTimeStamp).toBe('900');
});
it('checks later pages before reporting more filtered collection items', async () => {
const transport = vi.fn(async (request: { body: Uint8Array }) => {
const { head } = decodeRequestEnvelope(request.body);
if (head.sequence === 1) {
return successResponse([{
cid: 'only-match',
author: { numId: 1n },
category: 4,
modifyTime: 1_200n,
}], 0);
}
return successResponse([{
cid: 'different-category',
author: { numId: 2n },
category: 2,
modifyTime: 1_100n,
}], 1);
});
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
});
expect(transport).toHaveBeenCalledTimes(2);
expect(result.collectionSearchList.collectionItemList.map((item) => item.cid))
.toEqual(['only-match']);
expect(result.collectionSearchList.hasMore).toBe(false);
expect(result.collectionSearchList.bottomTimeStamp).toBe('1200');
});
it('surfaces explicit service failures instead of returning an empty list', async () => {
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
transport: async () => errorResponse(-17, 'denied'),
})).rejects.toThrow('collection service error -17: denied');
});
it('fails when the server reports more data without advancing pagination', async () => {
const response = successResponse([], 0);
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport: async () => response,
})).rejects.toThrow('collection pagination made no progress');
});
it('rejects an unbounded count before making a request', async () => {
const transport = vi.fn();
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
count: 501,
transport,
})).rejects.toThrow('collection count must be between 1 and 500');
expect(transport).not.toHaveBeenCalled();
});
it('stops after the explicit pagination budget', async () => {
let calls = 0;
const transport = vi.fn(async () => {
calls += 1;
return successResponse([{
cid: `other-${calls}`,
author: { numId: 1n },
category: 2,
modifyTime: BigInt(10_000 - calls),
}], 0);
});
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
})).rejects.toThrow('collection pagination exceeded 100 pages');
expect(transport).toHaveBeenCalledTimes(100);
});
it('bounds the total time spent paginating collection results', async () => {
vi.useFakeTimers();
try {
const timeouts: number[] = [];
let calls = 0;
const transport = vi.fn(async (request: { timeoutMs: number }) => {
calls += 1;
timeouts.push(request.timeoutMs);
vi.advanceTimersByTime(8_000);
return successResponse([{
cid: `other-${calls}`,
author: { numId: 1n },
category: 2,
modifyTime: BigInt(10_000 - calls),
}], 0);
});
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
category: 4,
count: 1,
transport,
})).rejects.toThrow('collection pagination exceeded 60000ms');
expect(transport).toHaveBeenCalledTimes(8);
expect(timeouts.slice(0, 7)).toEqual(Array(7).fill(10_000));
expect(timeouts[7]).toBe(4_000);
} finally {
vi.useRealTimers();
}
});
it.each([
[
'cid',
{ author: { numId: 1n }, modifyTime: 1n },
'collection item is missing cid',
],
[
'author',
{ cid: 'cid-1', modifyTime: 1n },
'collection item cid-1 is missing author',
],
[
'modifyTime',
{ cid: 'cid-1', author: { numId: 1n } },
'collection item cid-1 is missing modifyTime',
],
] as const)('rejects collection items missing required %s', async (_field, item, message) => {
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
transport: async () => successResponse([item], 1),
})).rejects.toThrow(message);
});
it('uses the last returned item for the public cursor when count truncates a page', async () => {
const result = await getCollectionList({
uin: '10001',
pskey: 'ticket-value',
count: 1,
transport: async () => successResponse([
{ cid: 'first', author: { numId: 1n }, modifyTime: 1_200n },
{ cid: 'not-returned', author: { numId: 2n }, modifyTime: 1_100n },
], 1),
});
expect(result.collectionSearchList.collectionItemList.map((item) => item.cid)).toEqual(['first']);
expect(result.collectionSearchList.bottomTimeStamp).toBe('1200');
expect(result.collectionSearchList.hasMore).toBe(true);
});
it('cancels a failed HTTP response body before surfacing the status', async () => {
const cancel = vi.fn();
const stream = new ReadableStream<Uint8Array>({ cancel });
vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, {
status: 503,
statusText: 'Unavailable',
})));
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
})).rejects.toThrow('collection HTTP request failed: 503 Unavailable');
expect(cancel).toHaveBeenCalledOnce();
});
it.each([
['invalid', 'collection response has invalid content-length'],
[`${16 * 1024 * 1024 + 1}`, 'collection response exceeds 16777216 bytes'],
])('cancels response bodies rejected by content-length %s', async (contentLength, message) => {
const cancel = vi.fn();
const stream = new ReadableStream<Uint8Array>({ cancel });
vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, {
headers: { 'Content-Length': contentLength },
})));
await expect(getCollectionList({
uin: '10001',
pskey: 'ticket-value',
})).rejects.toThrow(message);
expect(cancel).toHaveBeenCalledOnce();
});
it('preserves both the primary response error and cancellation failure', async () => {
const primary = new Error('collection response has invalid content-length');
const cleanup = new Error('cancel failed');
const stream = new ReadableStream<Uint8Array>({
cancel: () => { throw cleanup; },
});
vi.stubGlobal('fetch', vi.fn(async () => new Response(stream, {
headers: { 'Content-Length': 'invalid' },
})));
let thrown: unknown;
try {
await getCollectionList({ uin: '10001', pskey: 'ticket-value' });
} catch (error) {
thrown = error;
}
expect(thrown).toBeInstanceOf(AggregateError);
const aggregate = thrown as AggregateError;
expect(aggregate.errors).toHaveLength(2);
expect(aggregate.errors[0]).toMatchObject({ message: primary.message });
expect(aggregate.errors[1]).toBe(cleanup);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.12.6",
"version": "1.12.7",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+3 -1
View File
@@ -65,6 +65,7 @@ import type {
NcGetUserStatusParams,
GroupTodoParams,
GetAiCharactersParams,
GetCollectionListParams,
AiVoiceParams,
DeleteGroupFolderParams,
SendPacketParams,
@@ -97,6 +98,7 @@ import type {
AiCharacterCategory,
UserOnlineStatus,
SendGroupAiRecordResult,
CollectionListInfo,
} from './results';
export type ActionData = JsonValue;
@@ -207,7 +209,7 @@ export interface SnowLumaActionMap {
get_group_at_all_remain: { params: JsonObject; data: GroupAtAllRemainInfo };
get_unidirectional_friend_list: { params: JsonObject; data: JsonArray };
set_self_longnick: { params: JsonObject; data: EmptyData };
get_collection_list: { params: JsonObject; data: JsonArray };
get_collection_list: { params: GetCollectionListParams; data: CollectionListInfo };
create_collection: { params: JsonObject; data: JsonValue };
set_qq_avatar: { params: JsonObject; data: EmptyData };
set_input_status: { params: JsonObject; data: EmptyData };
+7
View File
@@ -297,6 +297,13 @@ export interface FetchCustomFaceParams extends JsonObject {
count?: number;
}
export interface GetCollectionListParams extends JsonObject {
/** Collection category ID; 0 returns every category. */
category?: number;
/** Maximum number of collection items to return (1-500). */
count?: number;
}
export interface GetEmojiLikesParams extends MessageIdParams {
emoji_id: string;
}
+50 -1
View File
@@ -126,6 +126,55 @@ export interface OnlineClientsInfo {
clients: OnlineClientInfo[];
}
export interface CollectionAuthorInfo extends JsonObject {
type: number;
numId: string;
strId: string;
groupId: string;
groupName: string;
uid: string;
}
export interface CollectionSummaryInfo extends JsonObject {
textSummary: JsonValue;
linkSummary: JsonValue;
gallerySummary: JsonValue;
audioSummary: JsonValue;
videoSummary: JsonValue;
fileSummary: JsonValue;
locationSummary: JsonValue;
richMediaSummary: JsonValue;
}
export interface CollectionItemInfo extends JsonObject {
cid: string;
type: number;
status: number;
author: CollectionAuthorInfo;
bid: number;
category: number;
createTime: string;
collectTime: string;
modifyTime: string;
sequence: string;
shareUrl: string;
customGroupId: number;
securityBeat: boolean;
summary: CollectionSummaryInfo;
}
export interface CollectionSearchListInfo extends JsonObject {
collectionItemList: CollectionItemInfo[];
hasMore: boolean;
bottomTimeStamp: string;
}
export interface CollectionListInfo extends JsonObject {
errCode: number;
errMsg: string;
collectionSearchList: CollectionSearchListInfo;
}
export interface UrlSafetyInfo {
level: number;
}
@@ -156,7 +205,7 @@ export interface UserOnlineStatus {
ext_status: number;
}
// — send_group_ai_record 返回(合成是异步副作用,message_id 总为 0) —
// — send_group_ai_record 返回 —
export interface SendGroupAiRecordResult {
message_id: number;
}
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.12.6",
"version": "1.12.7",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/websocket",
"version": "1.12.6",
"version": "1.12.7",
"private": true,
"type": "module",
"main": "./src/index.ts",
+1 -1
View File
@@ -2,7 +2,7 @@
"license": "SEE LICENSE IN LICENSE",
"name": "webui",
"private": true,
"version": "1.12.6",
"version": "1.12.7",
"type": "module",
"scripts": {
"dev": "vite",