feat(onebot): query group todo messages

Fixes #332
This commit is contained in:
DrSmoothl committed 2026-08-09 13:36:41 +08:00
1 parent 4aba81ec6b
commit c08150fc0c
12 files changed
+1066 -11

No files matched your search

@@ -0,0 +1,149 @@
// 0x9474_0 — query the group's current todo banners.
//
// Current QQ exposes this as a packet-backed query. Request flag 1 selects
// todos. Each active banner identifies its source message twice: msgId carries
// `sequence_random`, while commonBanner.jumpInfo.jumpParam carries JSON with
// the same pair. Both sources are checked when present so a malformed identity
// can never poison SnowLuma's message-id cache.
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbOnlineBanner,
OidbQueryGroupTopBannersReq,
OidbQueryGroupTopBannersResp,
} from '@snowluma/proto-defs/oidb-actions/base';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupTodoListItem {
sourceId: string;
sequence: number;
random: number;
text: string;
createdAt: number;
updatedAt: number;
}
interface MessageIdentity {
sequence: number;
random: number;
}
const TODO_BANNER_FLAG = 1;
const SOURCE_ID_PATTERN = /^([1-9]\d*)_(-?\d+)$/;
const utf8 = new TextDecoder('utf-8', { fatal: true });
function decodeUtf8(bytes: Uint8Array, description: string): string {
try {
return utf8.decode(bytes);
} catch {
throw new Error(`invalid group todo ${description}`);
}
}
function parseSafeInteger(value: unknown, description: string): number {
if (typeof value !== 'number' || !Number.isSafeInteger(value)) {
throw new Error(`invalid group todo ${description}`);
}
return value;
}
function parseSourceIdentity(bytes: Uint8Array | undefined): MessageIdentity & { sourceId: string } {
if (!bytes || bytes.length === 0) {
throw new Error('invalid group todo message identity');
}
const sourceId = decodeUtf8(bytes, 'message identity');
const match = SOURCE_ID_PATTERN.exec(sourceId);
if (!match) throw new Error('invalid group todo message identity');
const sequence = Number(match[1]);
const random = Number(match[2]);
if (!Number.isSafeInteger(sequence) || sequence <= 0 || !Number.isSafeInteger(random)) {
throw new Error('invalid group todo message identity');
}
return { sourceId, sequence, random };
}
function parseJumpIdentity(bytes: Uint8Array | undefined): MessageIdentity | null {
if (!bytes || bytes.length === 0) return null;
let decoded: unknown;
try {
decoded = JSON.parse(decodeUtf8(bytes, 'jump identity'));
} catch (error) {
if (error instanceof Error && error.message.startsWith('invalid group todo')) throw error;
throw new Error('invalid group todo jump identity');
}
if (!decoded || typeof decoded !== 'object' || Array.isArray(decoded)) {
throw new Error('invalid group todo jump identity');
}
const record = decoded as Record<string, unknown>;
const sequence = parseSafeInteger(record.seq, 'jump identity');
const random = parseSafeInteger(record.random, 'jump identity');
if (sequence <= 0) throw new Error('invalid group todo jump identity');
return { sequence, random };
}
function parseTimestamp(value: bigint | number | null | undefined, description: string): number {
if (value === undefined || value === null) return 0;
const timestamp = typeof value === 'bigint' ? Number(value) : value;
if (!Number.isSafeInteger(timestamp) || timestamp < 0) {
throw new Error(`invalid group todo ${description}`);
}
return timestamp;
}
function parseBanner(banner: OidbOnlineBanner): GroupTodoListItem {
const source = parseSourceIdentity(banner.msgId);
const jump = parseJumpIdentity(banner.commonBanner?.jumpInfo?.jumpParam);
if (jump && (jump.sequence !== source.sequence || jump.random !== source.random)) {
throw new Error('group todo message identity mismatch');
}
return {
sourceId: source.sourceId,
sequence: source.sequence,
random: source.random,
text: banner.commonBanner?.ui?.text ?? banner.todoBanner?.text ?? '',
createdAt: parseTimestamp(banner.commonBanner?.createTime, 'create time'),
updatedAt: parseTimestamp(banner.commonBanner?.updateTime, 'update time'),
};
}
export namespace GetGroupTodoList {
export const command = 0x9474;
export const subCommand = 0;
export interface Params {
groupId: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbQueryGroupTopBannersReq => {
if (!Number.isSafeInteger(p.groupId) || p.groupId <= 0) {
throw new Error('invalid group id');
}
return {
groupId: BigInt(p.groupId),
bannerFlag: TODO_BANNER_FLAG,
};
};
export const deserialize = (
_ctx: Deps,
body: OidbQueryGroupTopBannersResp,
): GroupTodoListItem[] => (body.banners ?? [])
.filter((banner) => banner.isDisappear !== true)
.map(parseBanner);
export const encode = (env: OidbBase<OidbQueryGroupTopBannersReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbQueryGroupTopBannersReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbQueryGroupTopBannersResp> =>
protobuf_decode<OidbBase<OidbQueryGroupTopBannersResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupTodoListItem[]> =>
invokeOidb(deps, GetGroupTodoList, params);
}
@@ -0,0 +1,112 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode } from '@snowluma/proton';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbQueryGroupTopBannersReq } from '@snowluma/proto-defs/oidb-actions/base';
import { GetGroupTodoList } from '../../../src/oidb-services/extras/get-group-todo-list';
// Fixed wire fixture shaped after a live QQ 3.2.32-51802 0x9474_0 response.
// It deliberately uses the current common-banner representation rather than
// constructing the response with the production protobuf encoder.
const ACTIVE_TODO_RESPONSE = Buffer.from(
'08f4a802100018002291010a8e01080f10021a06353633315f3040d09ba8bb06'
+ 'a2016a0a3f0a1d68747470733a2f2f6578616d706c652e746573742f746f646f'
+ '2e706e67120ce7bea4e5be85e58a9eefbd9c1a0ce6b58be8af95e5be85e58a9e'
+ '28023003121b08031a177b22736571223a353633312c2272616e646f6d223a307d'
+ '18c0ffa7bb0620c1ffa7bb06c802a29c01d002c801e80201f002012a006000',
'hex',
);
function makeSender(responseData = Buffer.alloc(0)) {
const result: SendPacketResult = {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
};
return { sendRawPacket: vi.fn(async () => result) };
}
describe('GetGroupTodoList namespace', () => {
it('queries 0x9474_0 with the todo-only banner flag', async () => {
const sender = makeSender();
await GetGroupTodoList.invoke(sender, { groupId: 941657197 });
const [wireName, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(wireName).toBe('OidbSvcTrpcTcp.0x9474_0');
expect(GetGroupTodoList.subCommand).toBe(0);
const envelope = protobuf_decode<OidbBase<OidbQueryGroupTopBannersReq>>(bytes);
expect(envelope).toMatchObject({
command: 0x9474,
body: { groupId: 941657197n, bannerFlag: 1 },
});
});
it('decodes the current common-banner todo and validates both identity sources', async () => {
const sender = makeSender(ACTIVE_TODO_RESPONSE);
await expect(GetGroupTodoList.invoke(sender, { groupId: 941657197 })).resolves.toEqual([
{
sourceId: '5631_0',
sequence: 5631,
random: 0,
text: '测试待办',
createdAt: 1735000000,
updatedAt: 1735000001,
},
]);
});
it('filters disappeared todo tombstones', () => {
expect(GetGroupTodoList.deserialize({} as never, {
banners: [{ bizType: 15, bannerType: 2, isDisappear: true, bizId: 20002 }],
})).toEqual([]);
});
it('supports the legacy todo text shape without inventing timestamps', () => {
expect(GetGroupTodoList.deserialize({} as never, {
banners: [{
msgId: Buffer.from('88_0'),
isDisappear: false,
todoBanner: { text: '旧版待办' },
}],
})).toEqual([{
sourceId: '88_0',
sequence: 88,
random: 0,
text: '旧版待办',
createdAt: 0,
updatedAt: 0,
}]);
});
it('rejects an active todo whose message identity cannot be mapped', () => {
expect(() => GetGroupTodoList.deserialize({} as never, {
banners: [{
bizType: 15,
bannerType: 2,
msgId: Buffer.from('not-a-message-id'),
isDisappear: false,
bizId: 20002,
}],
})).toThrow(/invalid group todo message identity/);
});
it('rejects disagreement between msgId and the jump payload', () => {
expect(() => GetGroupTodoList.deserialize({} as never, {
banners: [{
bizType: 15,
bannerType: 2,
msgId: Buffer.from('5631_0'),
isDisappear: false,
bizId: 20002,
commonBanner: {
jumpInfo: { jumpParam: Buffer.from('{"seq":5632,"random":0}') },
},
}],
})).toThrow(/identity mismatch/);
});
});