Merge pull request #390 from SnowLuma/dev

chore: promote dev → main (c869826)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-08-17 13:11:32 +00:00
commit 6deb3aa4d5
76 files changed
+2074 -251

No files matched your search

+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.14.10",
"version": "1.14.11",
"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.14.10",
"version": "1.14.11",
"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).",
+8 -1
View File
@@ -68,7 +68,9 @@ export type HookSessionDeps = {
*
* Emitted events:
* 'login' (uin, packetSender) — real-UIN login detected
* 'disconnected' (wasLoggedIn) — connection dropped or torn down
* 'disconnected' (wasLoggedIn) — connection dropped, torn down, or
* dispose() of a logged-in session
* (process shutdown uses this path)
* 'receive-health-changed' (healthy) — combined receive/request path health changed
* 'status-changed' (status, error) — status field mutated
* 'disposed' () — session stopped tracking this PID
@@ -237,8 +239,13 @@ export class HookSession extends EventEmitter {
dispose(): void {
if (this.disposed) return;
const wasLoggedIn = this.loggedIn;
this.disposed = true;
this.tearDownClient();
// Process shutdown must take the same PID-detach path as a live drop.
// tearDownClient strips the pipe client first, so this emit is the only
// disconnected edge HookManager will see.
if (wasLoggedIn) this.emit('disconnected', true);
this.removeAllListeners();
}
@@ -644,6 +644,40 @@ describe('HookSession — process gone', () => {
});
});
describe('HookSession — dispose', () => {
it('emits disconnected(true) while logged in so BridgeManager can detach the PID', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.currentClient().fireLogin('10001');
ctx.session.dispose();
expect(discSpy).toHaveBeenCalledOnce();
expect(discSpy).toHaveBeenCalledWith(true);
expect(ctx.session.isDisposed).toBe(true);
});
it('does not emit disconnected when disposed before login', async () => {
const ctx = makeSession({ pipeLive: true });
const discSpy = vi.fn();
ctx.session.on('disconnected', discSpy);
await ctx.session.load();
ctx.session.onPipeUp();
await flush();
ctx.session.dispose();
expect(discSpy).not.toHaveBeenCalled();
expect(ctx.session.isDisposed).toBe(true);
});
});
describe('HookSession — refresh drift fix', () => {
// refresh while the pipe is down on a connected-but-never-logged-in
// session now reports 'connecting' (matching what onPipeDown gives for the
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.14.10",
"version": "1.14.11",
"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.14.10",
"version": "1.14.11",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -389,6 +389,9 @@ export class ContactsApi {
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
@@ -445,6 +448,9 @@ export class ContactsApi {
eventType: operationType ?? 0,
comment: raw.comment ?? '',
filtered,
operateTransInfo: raw.operateTransInfo && raw.operateTransInfo.length > 0
? raw.operateTransInfo
: undefined,
});
}
this.ctx.identity.rememberGroupRequests(requests);
+65 -21
View File
@@ -11,18 +11,20 @@ import { SetAdmin } from '@snowluma/protocol/oidb-services/group-admin/set-admin
import { SetGroupName } from '@snowluma/protocol/oidb-services/group-admin/set-group-name';
import { SetGroupRemark } from '@snowluma/protocol/oidb-services/group-admin/set-group-remark';
import { SetMemberCard } from '@snowluma/protocol/oidb-services/group-admin/set-member-card';
import { FetchGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/get-group-ext-info';
import {
decodeMemberInvitePolicy,
MEMBER_INVITE_PRIVILEGE_MASK,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
} from '@snowluma/protocol/oidb-services/group-admin/set-member-invite-policy';
import {
GROUP_HISTORY_VISIBILITY_MASK,
mergeGroupHistoryVisibility,
decodeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
} from '@snowluma/protocol/oidb-services/group-admin/set-new-member-history-visibility';
import {
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
@@ -33,6 +35,21 @@ import { SetSpecialTitle } from '@snowluma/protocol/oidb-services/group-admin/se
import { ModifyGroupExtInfo } from '@snowluma/protocol/oidb-services/group-admin/modify-group-ext-info';
import type { BridgeContext } from '../bridge-context';
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: GroupMemberInvitePolicy;
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupMemberPermissions {
allowMemberUploadAlbum?: boolean;
allowMemberTemporarySession?: boolean;
@@ -47,6 +64,33 @@ export class GroupAdminApi {
return ModifyGroupExtInfo.invoke(this.ctx, { groupId, robotMemberSwitch, robotMemberExamine });
}
async getAdminSettings(groupId: number): Promise<GroupAdminSettings> {
const [detail, robot] = await Promise.all([
FetchGroupDetail.invoke(this.ctx, { groupUin: groupId }),
FetchGroupExtInfo.invoke(this.ctx, { groupId }),
]);
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read group admin settings for group ${groupId}`);
}
const privilegeFlag = results.privilegeFlag ?? 0;
const permissions = decodeGroupMemberPermissions(privilegeFlag);
return {
add_type: results.addType ?? 0,
group_question: results.question ?? '',
group_answer: results.answer ?? '',
robot_member_switch: robot.robotMemberSwitch,
robot_member_examine: robot.robotMemberExamine,
member_invite_policy: decodeMemberInvitePolicy(privilegeFlag),
allow_member_upload_album: permissions.allowMemberUploadAlbum,
allow_member_temporary_session: permissions.allowMemberTemporarySession,
allow_member_create_group: permissions.allowMemberCreateGroup,
new_member_history_visible: decodeGroupHistoryVisibility(results.groupFlagExt4 ?? 0),
no_finger_open: results.noFingerOpen ?? 0,
no_code_finger_open: results.noCodeFingerOpen ?? 0,
};
}
muteMember(groupId: number, userId: number, duration: number): Promise<void> {
return MuteMember.invoke(this.ctx, { groupId, userId, duration });
}
@@ -55,8 +99,13 @@ export class GroupAdminApi {
return MuteAll.invoke(this.ctx, { groupId, enable });
}
setAddOption(groupId: number, addType: number): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType });
setAddOption(
groupId: number,
addType: number,
groupQuestion?: string,
groupAnswer?: string,
): Promise<void> {
return SetAddOption.invoke(this.ctx, { groupId, addType, groupQuestion, groupAnswer });
}
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
@@ -90,11 +139,11 @@ export class GroupAdminApi {
private async fetchGroupPrivilegeFlag(groupId: number, setting: string, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const privilegeFlag = detail.groupInfo?.results?.privilegeFlag;
if (typeof privilegeFlag !== 'number') {
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read ${setting} ${phase} for group ${groupId}`);
}
return privilegeFlag;
return results.privilegeFlag ?? 0;
}
async setMemberPermissions(groupId: number, permissions: GroupMemberPermissions): Promise<void> {
@@ -137,36 +186,31 @@ export class GroupAdminApi {
}
async setNewMemberHistoryVisibility(groupId: number, visible: boolean): Promise<void> {
const currentGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'before update');
const expectedGroupFlagExt4 = mergeGroupHistoryVisibility(currentGroupFlagExt4, visible);
await SetNewMemberHistoryVisibility.invoke(this.ctx, {
groupId,
currentGroupFlagExt4,
visible,
});
await SetNewMemberHistoryVisibility.invoke(this.ctx, { groupId, visible });
const actualGroupFlagExt4 = await this.fetchGroupFlagExt4(groupId, 'after update');
const mask = BigInt(GROUP_HISTORY_VISIBILITY_MASK);
if ((BigInt(actualGroupFlagExt4) & mask) !== (BigInt(expectedGroupFlagExt4) & mask)) {
if (decodeGroupHistoryVisibility(actualGroupFlagExt4) !== visible) {
throw new Error(`new-member history visibility was not applied for group ${groupId}`);
}
}
private async fetchGroupFlagExt4(groupId: number, phase: string): Promise<number> {
const detail = await FetchGroupDetail.invoke(this.ctx, { groupUin: groupId });
const groupFlagExt4 = detail.groupInfo?.results?.groupFlagExt4;
if (typeof groupFlagExt4 !== 'number') {
const results = detail.groupInfo?.results;
if (!results) {
throw new Error(`unable to read new-member history visibility ${phase} for group ${groupId}`);
}
return groupFlagExt4;
return results.groupFlagExt4 ?? 0;
}
setAddRequest(
groupId: number, sequence: number, eventType: number,
approve: boolean, reason = '', filtered = false,
operateTransInfo?: Uint8Array,
): Promise<void> {
return SetAddRequest.invoke(this.ctx, { groupId, sequence, eventType, approve, reason, filtered });
return SetAddRequest.invoke(this.ctx, {
groupId, sequence, eventType, approve, reason, filtered, operateTransInfo,
});
}
kickMember(groupId: number, userId: number, reject: boolean, reason = ''): Promise<void> {
+66 -1
View File
@@ -435,6 +435,7 @@ export class GroupAlbumApi {
}
async delete(groupId: number, albumId: string, lloc: string): Promise<{ success: true }> {
const target = await this.resolveDeleteTarget(groupId, albumId, lloc);
const uin = this.ctx.identity.uin;
const clientKey = `${uin}_${Date.now()}_${Math.floor(Math.random() * 100000)}`;
@@ -445,7 +446,8 @@ export class GroupAlbumApi {
body: {
groupId: groupId.toString(),
albumId,
lloc,
mediaIds: [target.mediaId],
...(target.batchId ? { batchIds: [target.batchId] } : {}),
},
traceId: clientKey,
extMap: [{ key: 'fc-appid', value: '100' }],
@@ -472,7 +474,70 @@ export class GroupAlbumApi {
return { success: true };
}
/**
* Official delete uses a photo lloc, or a video's cover lloc plus batch id.
* Callers may pass either an image lloc or a video id; resolve the latter.
*/
private async resolveDeleteTarget(
groupId: number,
albumId: string,
mediaKey: string,
): Promise<{ mediaId: string; batchId?: string }> {
try {
const seenCursors = new Set<string>();
let attachInfo = '';
while (true) {
const page = await this.getMediaList(groupId, albumId, attachInfo);
const hit = findDeleteTarget(page.mediaList, mediaKey);
if (hit) return hit;
const next = page.nextAttachInfo ?? '';
if (!next || seenCursors.has(next)) {
return { mediaId: mediaKey };
}
seenCursors.add(next);
attachInfo = next;
}
} catch (err) {
log.debug(
'resolve album delete target failed, using raw id: group=%d album=%s err=%s',
groupId,
albumId,
err instanceof Error ? err.message : String(err),
);
return { mediaId: mediaKey };
}
}
}
interface AlbumDeleteMediaItem {
image?: { lloc?: string } | null;
video?: { id?: string; cover?: { lloc?: string } | null } | null;
batchId?: string | number;
}
function findDeleteTarget(
mediaList: ReadonlyArray<unknown>,
mediaKey: string,
): { mediaId: string; batchId?: string } | undefined {
for (const raw of mediaList) {
if (!raw || typeof raw !== 'object') continue;
const item = raw as AlbumDeleteMediaItem;
const batchId = item.batchId === undefined || item.batchId === ''
? undefined
: String(item.batchId);
if (item.image?.lloc === mediaKey) {
return { mediaId: mediaKey, batchId };
}
const coverLloc = item.video?.cover?.lloc;
if (item.video?.id === mediaKey || coverLloc === mediaKey) {
return { mediaId: coverLloc || mediaKey, batchId };
}
}
return undefined;
}
export interface GroupAlbumMediaResult {
mediaList: Array<JsonValue & Partial<MediaInfo>>;
nextAttachInfo: string;
+12 -12
View File
@@ -58,8 +58,12 @@ export class Bridge implements BridgeInterface {
this.pipeline = new IncomingPacketPipeline({
identity: this.identity,
events: this.events,
refreshMemberCache: (groupId, refreshGroupList, forceMemberList) =>
this.refreshMemberCache(groupId, refreshGroupList, forceMemberList),
fetchGroupList: async () => {
await this.apis.contacts.fetchGroupList();
},
fetchGroupMemberList: async (groupId) => {
await this.apis.contacts.fetchGroupMemberList(groupId);
},
resolveGroupJoinRequest: async (groupId, uid, subType) => {
const [main, filtered] = await Promise.allSettled([
this.apis.contacts.fetchGroupRequestsByUid(false),
@@ -80,10 +84,14 @@ export class Bridge implements BridgeInterface {
...(main.status === 'fulfilled' ? main.value : []),
...(filtered.status === 'fulfilled' ? filtered.value : []),
];
return requests.find(r => {
const matches = requests.filter((r) => {
if (r.groupId !== groupId) return false;
return subType === 'invite' ? r.invitorUid === uid : r.targetUid === uid;
}) ?? null;
});
if (subType === 'invite') {
return matches.find((r) => r.notifyType === 1) ?? matches[0] ?? null;
}
return matches.find((r) => r.notifyType === 7) ?? matches[0] ?? null;
},
resolveGroupInviteCardSequence: async (groupId) => {
const deadline = Date.now() + 1_000;
@@ -240,14 +248,6 @@ export class Bridge implements BridgeInterface {
return this.pipeline.process(pkt);
}
private async refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean> {
if (refreshGroupList) {
try { await this.apis.contacts.fetchGroupList(); } catch { /* ignore */ }
}
if (!this.identity.findGroup(groupId)) return false;
await this.apis.contacts.fetchGroupMemberList(groupId, { force: forceMemberList });
return true;
}
rememberUploadedFile(meta: UploadedFileMeta): void {
if (!meta.fileId) return;
if (this.uploadedFileMeta_.size >= Bridge.UPLOADED_FILE_CACHE_MAX) {
+7 -4
View File
@@ -118,14 +118,17 @@ async function main() {
exitCode = 1;
log.error('notification shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try { hookManager.dispose(); } catch (error) {
exitCode = 1;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
// Observers go deaf before Hook teardown. Hook dispose then emits the
// same disconnected → PID detach → Bridge closed path as a live drop;
// those closed edges must not look like a runtime offline.
try { stateWiring.dispose(); } catch (error) {
exitCode = 1;
log.error('state wiring shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
try { hookManager.dispose(); } catch (error) {
exitCode = 1;
log.error('hook shutdown failed: %s', error instanceof Error ? (error.stack ?? error.message) : String(error));
}
await closeLogger();
process.exit(exitCode);
};
@@ -74,6 +74,7 @@ export class NotificationManager {
private readonly nicknames = new Map<string, string>();
private readonly history: DeliveryRecord[] = [];
private readonly historyLimit: number;
private disposed = false;
constructor(deps: NotificationManagerDeps) {
this.deps = deps;
@@ -88,11 +89,13 @@ export class NotificationManager {
}
handleOnline(uin: string, nickname?: string): void {
if (this.disposed) return;
if (nickname) this.nicknames.set(uin, nickname);
this.apply(uin, this.machine.onOnline(uin));
}
handleOffline(uin: string, nickname?: string): void {
if (this.disposed) return;
if (nickname) this.nicknames.set(uin, nickname);
this.apply(uin, this.machine.onOffline(uin, this.debounceSeconds()));
}
@@ -221,6 +224,8 @@ export class NotificationManager {
}
dispose(): void {
if (this.disposed) return;
this.disposed = true;
for (const timer of this.timers.values()) clearTimeout(timer);
this.timers.clear();
}
+3 -2
View File
@@ -14,8 +14,9 @@
* listeners directly so `qq-list` + `connections` invalidate at the right
* moment without modifying BridgeManager.
*
* `dispose()` unwires everything so a test (or a future hot-reload) can
* recreate the wiring without leaking listeners.
* `dispose()` sets a latch and neuters the bus. BridgeManager listeners stay
* attached; further session edges publish nothing. Process shutdown disposes
* this wiring before Hook teardown so exit-time closed is not a WebUI invalidate.
*/
import { StateBus } from './state-bus';
+212 -18
View File
@@ -1,6 +1,7 @@
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb';
import type { OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
import type {
Oidb0x8a0Req,
Oidb0x8a7Resp,
@@ -56,6 +57,26 @@ function packGroupFlagExt4(groupFlagExt4?: number) {
}));
}
function packAdminDetail(results: NonNullable<NonNullable<OidbSvcTrpcTcp0x88D_0Response['groupInfo']>['results']>) {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n, results } },
}));
}
function packRobotExt(robotMemberSwitch?: number, robotMemberExamine?: number) {
return packResponse(protobuf_encode<OidbBase<OidbGetGroupExtResp>>({
body: {
items: [{
groupCode: 12345n,
ext: {
inviteRobotMemberSwitch: robotMemberSwitch,
inviteRobotMemberExamine: robotMemberExamine,
},
}],
},
}));
}
describe('apis/group-admin', () => {
it('muteMember resolves UID and dispatches 0x1253_1', async () => {
const bridge = mockBridge();
@@ -210,11 +231,24 @@ describe('apis/group-admin', () => {
const addOptEnv = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bridge.sendRawPacket.mock.calls[4]![1]);
expect(addOptEnv.body).toMatchObject({ groupUin: 1n, settings: { addType: 2 } });
expect(addOptEnv.body?.settings?.groupQuestion ?? undefined).toBeUndefined();
const searchEnv = protobuf_decode<OidbBase<Oidb0x89a_0Search>>(bridge.sendRawPacket.mock.calls[5]![1]);
expect(searchEnv.body?.groupUin).toBe(1n);
});
it('setAddOption forwards question and answer for type 4', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setAddOption(12345, 4, 'how', '42');
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(
bridge.sendRawPacket.mock.calls[0]![1],
);
expect(envelope.body).toMatchObject({
groupUin: 12345n,
settings: { addType: 4, groupQuestion: 'how', groupAnswer: '42' },
});
});
it('setAddRequest picks _1 / _2 based on filtered flag', async () => {
const bridge = mockBridge();
await new GroupAdminApi(bridge as any).setAddRequest(12345, 5, 1, true, 'ok', false);
@@ -264,9 +298,32 @@ describe('apis/group-admin', () => {
});
});
it('setMemberInvitePolicy fails before mutation when the current flag is absent', async () => {
it('setMemberInvitePolicy treats an omitted privilege flag as zero', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag());
bridge.sendRawPacket
.mockResolvedValueOnce(packPrivilegeFlag())
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packPrivilegeFlag(0));
await new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval');
const env = protobuf_decode<OidbBase<Oidb0x89a_0InvitePolicy>>(
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(env.body?.settings).toEqual({
appPrivilegeFlag: 0,
appPrivilegeMask: 0x06100000,
allowMemberInvite: 1,
});
});
it('setMemberInvitePolicy fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}),
));
await expect(
new GroupAdminApi(bridge as any).setMemberInvitePolicy(12345, 'require_approval'),
@@ -287,53 +344,83 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
});
it('setNewMemberHistoryVisibility reads, merges, writes, and verifies the extended flag (#336)', async () => {
it('setNewMemberHistoryVisibility accepts a 0/1 history-visible read-back (#387)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0x80000005));
.mockResolvedValueOnce(packGroupFlagExt4(1));
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true);
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0])).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0x89a_0',
'OidbSvcTrpcTcp.0x88d_0',
]);
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
bridge.sendRawPacket.mock.calls[1]![1],
bridge.sendRawPacket.mock.calls[0]![1],
);
expect(envelope.body).toMatchObject({
groupUin: 12345n,
settings: {
groupFlagExt4: 0x80000005,
groupFlagExt4: 0x4,
groupFlagExt4Mask: 0x4,
},
});
});
it('setNewMemberHistoryVisibility fails before mutation when the current flag is absent', async () => {
it('setNewMemberHistoryVisibility clears visibility when read-back is the off flag', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packGroupFlagExt4());
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0));
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, false);
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0HistoryVisibility>>(
bridge.sendRawPacket.mock.calls[0]![1],
);
expect(envelope.body?.settings).toEqual({
groupFlagExt4: 0,
groupFlagExt4Mask: 0x4,
});
});
it('setNewMemberHistoryVisibility treats an omitted history flag as hidden', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4());
await new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, false);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('setNewMemberHistoryVisibility fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}),
));
await expect(
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
).rejects.toThrow(/unable to read new-member history visibility before update/);
expect(bridge.sendRawPacket).toHaveBeenCalledOnce();
).rejects.toThrow(/unable to read new-member history visibility after update/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('setNewMemberHistoryVisibility rejects an ack when read-back does not match', async () => {
it('setNewMemberHistoryVisibility rejects an ack when read-back stays hidden', async () => {
const bridge = mockBridge();
bridge.sendRawPacket
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001))
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packGroupFlagExt4(0x80000001));
.mockResolvedValueOnce(packGroupFlagExt4(0));
await expect(
new GroupAdminApi(bridge as any).setNewMemberHistoryVisibility(12345, true),
).rejects.toThrow(/was not applied/);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(3);
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(2);
});
it('setMemberPermissions applies supplied switches separately and verifies the combined result (#335)', async () => {
@@ -377,9 +464,33 @@ describe('apis/group-admin', () => {
expect(bridge.sendRawPacket).not.toHaveBeenCalled();
});
it('setMemberPermissions fails before mutation when the current flag is absent', async () => {
it('setMemberPermissions treats an omitted privilege flag as all-allowed (#388)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packPrivilegeFlag());
bridge.sendRawPacket
.mockResolvedValueOnce(packPrivilegeFlag())
.mockResolvedValueOnce(packResponse(Buffer.alloc(0)))
.mockResolvedValueOnce(packPrivilegeFlag(0));
await new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
allowMemberUploadAlbum: true,
});
const envelope = protobuf_decode<OidbBase<Oidb0x89a_0MemberPermission>>(
bridge.sendRawPacket.mock.calls[1]![1],
);
expect(envelope.body?.settings).toEqual({
appPrivilegeFlag: 0,
appPrivilegeMask: 1,
});
});
it('setMemberPermissions fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockResolvedValueOnce(packResponse(
protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}),
));
await expect(
new GroupAdminApi(bridge as any).setMemberPermissions(12345, {
@@ -419,6 +530,89 @@ describe('apis/group-admin', () => {
});
});
it('getAdminSettings composes detail and ext-info into setter-aligned fields (#385)', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
return packAdminDetail({
addType: 2,
question: 'how',
answer: '42',
privilegeFlag: 0x84018001,
groupFlagExt4: 1,
noFingerOpen: 1,
});
}
if (cmd === 'OidbSvcTrpcTcp.0xef0_1') {
return packRobotExt(1, 2);
}
return packResponse(Buffer.alloc(0));
});
const out = await new GroupAdminApi(bridge as any).getAdminSettings(12345);
expect(out).toEqual({
add_type: 2,
group_question: 'how',
group_answer: '42',
robot_member_switch: 1,
robot_member_examine: 2,
member_invite_policy: 'disabled',
allow_member_upload_album: false,
allow_member_temporary_session: false,
allow_member_create_group: false,
new_member_history_visible: true,
no_finger_open: 1,
no_code_finger_open: 0,
});
expect(bridge.sendRawPacket.mock.calls.map((call) => call[0]).sort()).toEqual([
'OidbSvcTrpcTcp.0x88d_0',
'OidbSvcTrpcTcp.0xef0_1',
]);
});
it('getAdminSettings treats omitted detail/ext zeros as the default values', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
return packAdminDetail({});
}
if (cmd === 'OidbSvcTrpcTcp.0xef0_1') {
return packRobotExt();
}
return packResponse(Buffer.alloc(0));
});
await expect(new GroupAdminApi(bridge as any).getAdminSettings(12345)).resolves.toEqual({
add_type: 0,
group_question: '',
group_answer: '',
robot_member_switch: 0,
robot_member_examine: 0,
member_invite_policy: 'require_approval',
allow_member_upload_album: true,
allow_member_temporary_session: true,
allow_member_create_group: true,
new_member_history_visible: false,
no_finger_open: 0,
no_code_finger_open: 0,
});
});
it('getAdminSettings fails when group detail has no results block', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd === 'OidbSvcTrpcTcp.0x88d_0') {
return packResponse(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: { groupInfo: { uin: 12345n } },
}));
}
return packRobotExt(0, 0);
});
await expect(new GroupAdminApi(bridge as any).getAdminSettings(12345))
.rejects.toThrow(/unable to read group admin settings/);
});
it('getAtAllRemain falls back to zero / false when the response is empty', async () => {
const bridge = mockBridge();
// Empty OidbBase envelope (no body) — invokeOidb substitutes `{}`
@@ -1,5 +1,7 @@
import { describe, expect, it } from 'vitest';
import type {
DeleteMediasRequest,
DeleteMediasResponse,
GetAlbumListResponse,
GetMediaListResponse,
} from '@snowluma/proto-defs/oidb-actions/group-album';
@@ -437,4 +439,128 @@ describe('apis/group-album', () => {
nextAttachInfo: 'next-video-page',
});
});
function packDeleteOk() {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<DeleteMediasResponse>({ field1: 8694 })),
};
}
function packMediaList(body: GetMediaListResponse['data']) {
return {
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData: Buffer.from(protobuf_encode<GetMediaListResponse>({ data: body })),
};
}
it('deletes a photo by lloc and includes the batch id', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc: 'photo-lloc' }, batchId: 77n }],
});
}
return packDeleteOk();
});
await expect(new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'photo-lloc'))
.resolves.toEqual({ success: true });
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
expect(deleteCall?.[0]).toBe('QunAlbum.trpc.qzone.webapp_qun_media.QunMedia.DeleteMedias');
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body).toMatchObject({
groupId: '12345',
albumId: 'album-id',
mediaIds: ['photo-lloc'],
batchIds: ['77'],
});
});
it('deletes a video by video id using the cover lloc', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({
mediaList: [{
type: 2,
video: { id: 'video-id', cover: { lloc: 'cover-large' } },
batchId: 88n,
}],
});
}
return packDeleteOk();
});
await expect(new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'video-id'))
.resolves.toEqual({ success: true });
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body?.mediaIds).toEqual(['cover-large']);
expect(request.body?.batchIds).toEqual(['88']);
});
it('pages the media list until the video is found', async () => {
const bridge = mockBridge();
let pages = 0;
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
pages += 1;
if (pages === 1) {
return packMediaList({
mediaList: [{ type: 1, image: { lloc: 'other' }, batchId: 1n }],
nextAttachInfo: 'page-2',
});
}
return packMediaList({
mediaList: [{
type: 2,
video: { id: 'video-id', cover: { lloc: 'cover-2' } },
batchId: 2n,
}],
});
}
return packDeleteOk();
});
await new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'video-id');
expect(pages).toBe(2);
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body?.mediaIds).toEqual(['cover-2']);
expect(request.body?.batchIds).toEqual(['2']);
});
it('falls back to the raw id when the media list has no match', async () => {
const bridge = mockBridge();
bridge.sendRawPacket.mockImplementation(async (cmd: string) => {
if (cmd.endsWith('GetMediaList')) {
return packMediaList({ mediaList: [] });
}
return packDeleteOk();
});
await new GroupAlbumApi(bridge as never).delete(12345, 'album-id', 'unknown-id');
const deleteCall = bridge.sendRawPacket.mock.calls.find((call) =>
String(call[0]).endsWith('DeleteMedias'),
);
const request = protobuf_decode<DeleteMediasRequest>(deleteCall![1] as Uint8Array);
expect(request.body?.mediaIds).toEqual(['unknown-id']);
expect(request.body?.batchIds ?? []).toEqual([]);
});
});
+4 -2
View File
@@ -494,7 +494,8 @@ describe('parseMsgPush Event0x210 subType=364 (friend remark synchronization)',
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -942,7 +943,8 @@ describe('parseMsgPush PkgType 44 (group admin set/unset) keeps the member cache
const pipeline = new IncomingPacketPipeline({
identity,
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
@@ -196,4 +196,13 @@ describe('NotificationManager — debounce integration (fake timers)', () => {
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual(['offline']);
});
it('ignores online/offline after dispose so process exit is not a runtime drop', async () => {
const { events, mgr } = setup(0);
mgr.dispose();
mgr.handleOnline('123', 'Bob');
mgr.handleOffline('123', 'Bob');
await vi.advanceTimersByTimeAsync(0);
expect(events).toEqual([]);
});
});
@@ -43,7 +43,7 @@ describe('createStateWiring', () => {
expect(sub).toHaveBeenNthCalledWith(2, 'connections');
});
it('dispose() unwires onSessionsChanged + BridgeManager listeners (no further publishes)', () => {
it('dispose() latches so later Hook/Bridge edges publish nothing', () => {
const wiring = createStateWiring();
const bm = new BridgeManager();
wiring.bindBridgeManager(bm);
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.14.10",
"version": "1.14.11",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+138 -3
View File
@@ -1029,6 +1029,7 @@
{
"name": "del_group_album_media",
"aliases": [],
"summary": "删除群相册图片或视频",
"readOnly": false,
"params": [
{
@@ -1058,7 +1059,8 @@
"schema": {
"type": "string",
"minLength": 1
}
},
"desc": "图片长定位标识,或视频 id"
}
],
"invariants": [],
@@ -1077,7 +1079,8 @@
},
"lloc": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "图片长定位标识,或视频 id"
}
},
"required": [
@@ -3862,6 +3865,116 @@
},
"category": "扩展"
},
{
"name": "get_group_admin_settings",
"aliases": [],
"summary": "获取群管理设置的当前值",
"returns": "与对应设置接口字段对齐的当前群管理设置。",
"returnsSchema": {
"type": "object",
"properties": {
"add_type": {
"type": "integer",
"description": "加群选项(同 set_group_add_option.add_type)"
},
"group_question": {
"type": "string",
"description": "加群问题(同 set_group_add_option.group_question)"
},
"group_answer": {
"type": "string",
"description": "加群答案(同 set_group_add_option.group_answer)"
},
"robot_member_switch": {
"type": "integer",
"description": "机器人加群开关(同 set_group_robot_add_option)"
},
"robot_member_examine": {
"type": "integer",
"description": "机器人加群审核(同 set_group_robot_add_option)"
},
"member_invite_policy": {
"type": "string",
"enum": [
"disabled",
"require_approval",
"no_approval",
"no_approval_under_100"
],
"description": "成员邀请策略(同 set_group_member_invite_policy.policy)"
},
"allow_member_upload_album": {
"type": "boolean",
"description": "是否允许成员上传相册"
},
"allow_member_temporary_session": {
"type": "boolean",
"description": "是否允许成员发起临时会话"
},
"allow_member_create_group": {
"type": "boolean",
"description": "是否允许成员创建群聊"
},
"new_member_history_visible": {
"type": "boolean",
"description": "新成员是否可查看历史消息"
},
"no_finger_open": {
"type": "integer",
"description": "是否关闭群指纹/关键词搜索(0 开 1 关)"
},
"no_code_finger_open": {
"type": "integer",
"description": "是否关闭群号搜索(0 开 1 关)"
}
},
"required": [
"add_type",
"group_question",
"group_answer",
"robot_member_switch",
"robot_member_examine",
"member_invite_policy",
"allow_member_upload_album",
"allow_member_temporary_session",
"allow_member_create_group",
"new_member_history_visible",
"no_finger_open",
"no_code_finger_open"
]
},
"readOnly": true,
"params": [
{
"name": "group_id",
"type": "uint",
"required": true,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "群号"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_id": {
"type": "integer",
"minimum": 1,
"description": "群号",
"x-role": "group_id"
}
},
"required": [
"group_id"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "get_group_album_list",
"aliases": [],
@@ -9517,6 +9630,22 @@
"minimum": 0
},
"default": 0
},
{
"name": "group_question",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "group_answer",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
}
],
"invariants": [],
@@ -9533,6 +9662,12 @@
"type": "integer",
"minimum": 0,
"default": 0
},
"group_question": {
"type": "string"
},
"group_answer": {
"type": "string"
}
},
"required": [
@@ -12140,7 +12275,7 @@
},
{
"category": "群管理",
"count": 17
"count": 18
},
{
"category": "群文件",
+138 -3
View File
@@ -1032,6 +1032,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "del_group_album_media",
"aliases": [],
"summary": "删除群相册图片或视频",
"readOnly": false,
"params": [
{
@@ -1061,7 +1062,8 @@ export const ACTIONS: CatalogAction[] = [
"schema": {
"type": "string",
"minLength": 1
}
},
"desc": "图片长定位标识,或视频 id"
}
],
"invariants": [],
@@ -1080,7 +1082,8 @@ export const ACTIONS: CatalogAction[] = [
},
"lloc": {
"type": "string",
"minLength": 1
"minLength": 1,
"description": "图片长定位标识,或视频 id"
}
},
"required": [
@@ -3865,6 +3868,116 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "get_group_admin_settings",
"aliases": [],
"summary": "获取群管理设置的当前值",
"returns": "与对应设置接口字段对齐的当前群管理设置。",
"returnsSchema": {
"type": "object",
"properties": {
"add_type": {
"type": "integer",
"description": "加群选项(同 set_group_add_option.add_type)"
},
"group_question": {
"type": "string",
"description": "加群问题(同 set_group_add_option.group_question)"
},
"group_answer": {
"type": "string",
"description": "加群答案(同 set_group_add_option.group_answer)"
},
"robot_member_switch": {
"type": "integer",
"description": "机器人加群开关(同 set_group_robot_add_option)"
},
"robot_member_examine": {
"type": "integer",
"description": "机器人加群审核(同 set_group_robot_add_option)"
},
"member_invite_policy": {
"type": "string",
"enum": [
"disabled",
"require_approval",
"no_approval",
"no_approval_under_100"
],
"description": "成员邀请策略(同 set_group_member_invite_policy.policy)"
},
"allow_member_upload_album": {
"type": "boolean",
"description": "是否允许成员上传相册"
},
"allow_member_temporary_session": {
"type": "boolean",
"description": "是否允许成员发起临时会话"
},
"allow_member_create_group": {
"type": "boolean",
"description": "是否允许成员创建群聊"
},
"new_member_history_visible": {
"type": "boolean",
"description": "新成员是否可查看历史消息"
},
"no_finger_open": {
"type": "integer",
"description": "是否关闭群指纹/关键词搜索(0 开 1 关)"
},
"no_code_finger_open": {
"type": "integer",
"description": "是否关闭群号搜索(0 开 1 关)"
}
},
"required": [
"add_type",
"group_question",
"group_answer",
"robot_member_switch",
"robot_member_examine",
"member_invite_policy",
"allow_member_upload_album",
"allow_member_temporary_session",
"allow_member_create_group",
"new_member_history_visible",
"no_finger_open",
"no_code_finger_open"
]
},
"readOnly": true,
"params": [
{
"name": "group_id",
"type": "uint",
"required": true,
"role": "group_id",
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "群号"
}
],
"invariants": [],
"inputSchema": {
"type": "object",
"properties": {
"group_id": {
"type": "integer",
"minimum": 1,
"description": "群号",
"x-role": "group_id"
}
},
"required": [
"group_id"
],
"additionalProperties": true
},
"category": "群管理"
},
{
"name": "get_group_album_list",
"aliases": [],
@@ -9520,6 +9633,22 @@ export const ACTIONS: CatalogAction[] = [
"minimum": 0
},
"default": 0
},
{
"name": "group_question",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
},
{
"name": "group_answer",
"type": "string",
"required": false,
"schema": {
"type": "string"
}
}
],
"invariants": [],
@@ -9536,6 +9665,12 @@ export const ACTIONS: CatalogAction[] = [
"type": "integer",
"minimum": 0,
"default": 0
},
"group_question": {
"type": "string"
},
"group_answer": {
"type": "string"
}
},
"required": [
@@ -12144,7 +12279,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "群管理",
"count": 17
"count": 18
},
{
"category": "群文件",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.14.10",
"version": "1.14.11",
"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>'`.",
+53 -2
View File
@@ -45,9 +45,15 @@ export const actions = [
groupAction({
name: 'set_group_add_option',
summary: '设置加群选项',
params: { add_type: f.int({ min: 0 }).default(0) },
params: {
add_type: f.int({ min: 0 }).default(0),
group_question: f.string().optional(),
group_answer: f.string().optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setAddOption(p.group_id, p.add_type);
await ctx.bridge.apis.groupAdmin.setAddOption(
p.group_id, p.add_type, p.group_question, p.group_answer,
);
return okResponse();
},
}),
@@ -115,6 +121,51 @@ export const actions = [
},
}),
groupAction({
name: 'get_group_admin_settings',
summary: '获取群管理设置的当前值',
readOnly: true,
returns: '与对应设置接口字段对齐的当前群管理设置。',
returnsSchema: {
type: 'object',
properties: {
add_type: { type: 'integer', description: '加群选项(同 set_group_add_option.add_type)' },
group_question: { type: 'string', description: '加群问题(同 set_group_add_option.group_question)' },
group_answer: { type: 'string', description: '加群答案(同 set_group_add_option.group_answer)' },
robot_member_switch: { type: 'integer', description: '机器人加群开关(同 set_group_robot_add_option)' },
robot_member_examine: { type: 'integer', description: '机器人加群审核(同 set_group_robot_add_option)' },
member_invite_policy: {
type: 'string',
enum: ['disabled', 'require_approval', 'no_approval', 'no_approval_under_100'],
description: '成员邀请策略(同 set_group_member_invite_policy.policy)',
},
allow_member_upload_album: { type: 'boolean', description: '是否允许成员上传相册' },
allow_member_temporary_session: { type: 'boolean', description: '是否允许成员发起临时会话' },
allow_member_create_group: { type: 'boolean', description: '是否允许成员创建群聊' },
new_member_history_visible: { type: 'boolean', description: '新成员是否可查看历史消息' },
no_finger_open: { type: 'integer', description: '是否关闭群指纹/关键词搜索(0 开 1 关)' },
no_code_finger_open: { type: 'integer', description: '是否关闭群号搜索(0 开 1 关)' },
},
required: [
'add_type',
'group_question',
'group_answer',
'robot_member_switch',
'robot_member_examine',
'member_invite_policy',
'allow_member_upload_album',
'allow_member_temporary_session',
'allow_member_create_group',
'new_member_history_visible',
'no_finger_open',
'no_code_finger_open',
],
},
run: async (p, ctx) => {
return okResponse(await ctx.bridge.apis.groupAdmin.getAdminSettings(p.group_id));
},
}),
groupUserAction({
name: 'set_group_admin',
summary: '设置/取消管理员',
+2 -1
View File
@@ -223,9 +223,10 @@ export const actions = [
groupAction({
name: 'del_group_album_media',
summary: '删除群相册图片或视频',
params: {
album_id: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }),
lloc: f.string({ allowEmpty: false }).describe('图片长定位标识,或视频 id'),
},
run: async (p, ctx) => {
const res = await ctx.bridge.apis.groupAlbum.delete(p.group_id, p.album_id, p.lloc);
+1
View File
@@ -382,6 +382,7 @@ export class OneBotManager {
}
private onSessionClosed(uin: string): void {
if (this.disposed) return;
const migration = this.databaseMigrations.get(uin);
if (migration) {
migration.cancelled = true;
+34 -7
View File
@@ -99,21 +99,48 @@ function throwMissingGroupRequest(message: string, failures: readonly unknown[])
throw new Error(message);
}
async function resolveLiveGroupRequest(
bridge: BridgeInterface,
handle: GroupRequestHandle,
): Promise<GroupRequestHandle & { operateTransInfo?: Uint8Array }> {
const cardGroup = bridge.apis.contacts.findGroupInviteCardGroupBySequence?.(handle.sequence);
// Private invite-card seq is absent from 0x10C0; keep the flag tuple (#125).
if (cardGroup === handle.groupId) return handle;
const lookup = await fetchRequestInboxes(bridge, 'uin');
const live = lookup.requests.find((request) => (
request.groupId === handle.groupId
&& request.sequence === handle.sequence
&& request.eventType > 0
));
if (!live) return handle;
return {
sequence: live.sequence,
groupId: live.groupId,
eventType: live.eventType,
filtered: live.filtered,
operateTransInfo: live.operateTransInfo,
};
}
async function applyGroupRequest(
bridge: BridgeInterface,
handle: GroupRequestHandle,
approve: boolean,
reason: string,
knownLive?: GroupRequestInfo,
): Promise<void> {
const live = knownLive ?? await resolveLiveGroupRequest(bridge, handle);
log.debug('handling group request: group=%d sequence=%d eventType=%d filtered=%s approve=%s',
handle.groupId, handle.sequence, handle.eventType, handle.filtered, approve);
live.groupId, live.sequence, live.eventType, live.filtered, approve);
await bridge.apis.groupAdmin.setAddRequest(
handle.groupId,
handle.sequence,
handle.eventType,
live.groupId,
live.sequence,
live.eventType,
approve,
reason,
handle.filtered,
live.filtered,
live.operateTransInfo,
);
}
@@ -152,7 +179,7 @@ export async function handleGroupAddRequest(
lookup.failures,
);
}
await applyGroupRequest(bridge, matching, approve, reason);
await applyGroupRequest(bridge, matching, approve, reason, matching);
return;
}
@@ -182,5 +209,5 @@ export async function handleGroupAddRequest(
// Never fall back to an arbitrary request from the same group: when a UID
// does not match, approving another pending request is worse than failing.
if (!matching) throwMissingGroupRequest('matching group request not found', lookup.failures);
await applyGroupRequest(bridge, matching, approve, reason);
await applyGroupRequest(bridge, matching, approve, reason, matching);
}
@@ -39,6 +39,7 @@ const setGroupSearch = requireAction('set_group_search');
const setGroupMemberInvitePolicy = requireAction('set_group_member_invite_policy');
const setGroupNewMemberHistoryVisibility = requireAction('set_group_new_member_history_visibility');
const setGroupMemberPermissions = requireAction('set_group_member_permissions');
const getGroupAdminSettings = requireAction('get_group_admin_settings');
const setGroupAdmin = requireAction('set_group_admin');
const setGroupCard = requireAction('set_group_card');
const setGroupName = requireAction('set_group_name');
@@ -60,6 +61,7 @@ describe('group admin actions catalog', () => {
['set_group_member_invite_policy'],
['set_group_new_member_history_visibility'],
['set_group_member_permissions'],
['get_group_admin_settings'],
['set_group_admin'],
['set_group_card'],
['set_group_name'],
@@ -72,7 +74,7 @@ describe('group admin actions catalog', () => {
expect(actions.map((action) => action.kind)).toEqual([
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal', 'normal', 'normal', 'normal',
'normal', 'normal', 'normal',
'normal', 'normal', 'normal', 'normal',
]);
});
});
@@ -452,18 +454,18 @@ describe('set_group_add_option parse', () => {
it('defaults add_type to 0 and keeps a present 0', () => {
expect(setGroupAddOption.parse({ group_id: 12345 })).toEqual({
ok: true,
value: { group_id: 12345, add_type: 0 },
value: { group_id: 12345, add_type: 0, group_question: undefined, group_answer: undefined },
});
expect(setGroupAddOption.parse({ group_id: 12345, add_type: 0 })).toEqual({
ok: true,
value: { group_id: 12345, add_type: 0 },
value: { group_id: 12345, add_type: 0, group_question: undefined, group_answer: undefined },
});
});
it('accepts a positive add_type and rejects a negative one', () => {
expect(setGroupAddOption.parse({ group_id: 12345, add_type: '2' })).toEqual({
ok: true,
value: { group_id: 12345, add_type: 2 },
value: { group_id: 12345, add_type: 2, group_question: undefined, group_answer: undefined },
});
expect(setGroupAddOption.parse({ group_id: 12345, add_type: -1 })).toEqual({
ok: false,
@@ -471,6 +473,23 @@ describe('set_group_add_option parse', () => {
reason: 'must be >= 0',
});
});
it('keeps optional question and answer when present', () => {
expect(setGroupAddOption.parse({
group_id: 12345,
add_type: 4,
group_question: 'q',
group_answer: 'a',
})).toEqual({
ok: true,
value: {
group_id: 12345,
add_type: 4,
group_question: 'q',
group_answer: 'a',
},
});
});
});
describe('set_group_add_option toHandler', () => {
@@ -481,7 +500,7 @@ describe('set_group_add_option toHandler', () => {
await expect(setGroupAddOption.toHandler(ctx)({ group_id: 12345 }))
.resolves.toEqual({ status: 'ok', retcode: 0, data: null });
expect(setAddOption.mock.calls).toEqual([[12345, 0]]);
expect(setAddOption.mock.calls).toEqual([[12345, 0, undefined, undefined]]);
});
it('forwards an explicit add_type', async () => {
@@ -493,7 +512,21 @@ describe('set_group_add_option toHandler', () => {
add_type: 3,
})).resolves.toEqual({ status: 'ok', retcode: 0, data: null });
expect(setAddOption.mock.calls).toEqual([[941657197, 3]]);
expect(setAddOption.mock.calls).toEqual([[941657197, 3, undefined, undefined]]);
});
it('forwards question and answer', async () => {
const setAddOption = vi.fn(async () => {});
const { ctx } = adminCtx({ setAddOption });
await expect(setGroupAddOption.toHandler(ctx)({
group_id: 941657197,
add_type: 4,
group_question: 'q',
group_answer: 'a',
})).resolves.toEqual({ status: 'ok', retcode: 0, data: null });
expect(setAddOption.mock.calls).toEqual([[941657197, 4, 'q', 'a']]);
});
});
@@ -760,6 +793,45 @@ describe('set_group_member_permissions toHandler', () => {
});
});
describe('get_group_admin_settings parse', () => {
it('requires group_id and has no extra params', () => {
expect(getGroupAdminSettings.parse({})).toEqual({
ok: false,
field: 'group_id',
reason: 'is required',
});
expect(getGroupAdminSettings.parse({ group_id: 12345 })).toEqual({
ok: true,
value: { group_id: 12345 },
});
});
});
describe('get_group_admin_settings toHandler', () => {
it('forwards group_id and returns the current settings', async () => {
const settings = {
add_type: 2,
group_question: 'q',
group_answer: 'a',
robot_member_switch: 1,
robot_member_examine: 0,
member_invite_policy: 'require_approval',
allow_member_upload_album: true,
allow_member_temporary_session: false,
allow_member_create_group: true,
new_member_history_visible: true,
no_finger_open: 0,
no_code_finger_open: 1,
};
const getAdminSettings = vi.fn(async () => settings);
const { ctx } = adminCtx({ getAdminSettings });
await expect(getGroupAdminSettings.toHandler(ctx)({ group_id: 12345 }))
.resolves.toEqual({ status: 'ok', retcode: 0, data: settings });
expect(getAdminSettings.mock.calls).toEqual([[12345]]);
});
});
describe('set_group_member_permissions describe', () => {
it('documents the at-least-one capability invariant', () => {
const doc = setGroupMemberPermissions.describe();
@@ -627,8 +627,8 @@ describe('buildApiContext handleGroupRequest', () => {
await api.handleGroupRequest('slreq:1:123456:710410:22:1', 'add', true, 'welcome');
expect(setAddRequest).toHaveBeenCalledWith(710410, 123456, 22, true, 'welcome', true);
expect(fetchGroupRequests).not.toHaveBeenCalled();
expect(setAddRequest).toHaveBeenCalledWith(710410, 123456, 22, true, 'welcome', true, undefined);
expect(fetchGroupRequests).toHaveBeenCalled();
expect(ref.bridge.apis.groupAdmin.setAddRequest).toHaveBeenCalledOnce();
});
});
@@ -513,4 +513,28 @@ describe('OneBotManager lifecycle failure accounting', () => {
await expect(manager.dispose()).rejects.toThrow(/failed to dispose OneBot manager cleanly/);
});
it('ignores session-closed after dispose so process-exit closed does not retire again', async () => {
const manager = new OneBotManager();
const dispose = vi.fn(async () => ({ closed: true, errors: [] }));
const instance = fakeInstance('10001', dispose);
const internals = manager as unknown as {
instances: Map<string, OneBotInstance>;
retiringInstances: Set<OneBotInstance>;
onSessionClosed(uin: string): void;
};
internals.instances.set('10001', instance);
await manager.dispose();
expect(dispose).toHaveBeenCalledOnce();
const lateDispose = vi.fn(async () => ({ closed: true, errors: [] }));
const late = fakeInstance('10001', lateDispose);
internals.instances.set('10001', late);
internals.onSessionClosed('10001');
expect(lateDispose).not.toHaveBeenCalled();
expect(internals.retiringInstances.has(late)).toBe(false);
expect(manager.getInstance('10001')).toBe(late);
});
});
+33 -10
View File
@@ -52,7 +52,7 @@ function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInf
}
describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
it('uses a canonical self-contained flag without refetching the request queue', async () => {
it('uses a canonical flag and keeps the tuple when the inbox has no match', async () => {
const setAddRequest = vi.fn(async () => {});
const fetchGroupRequests = vi.fn(async () => []);
const bridge = fakeBridge({
@@ -62,8 +62,31 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, 'slreq:1:123456:999:22:1', true, 'ok');
expect(fetchGroupRequests).not.toHaveBeenCalled();
expect(setAddRequest).toHaveBeenCalledWith(999, 123456, 22, true, 'ok', true);
expect(fetchGroupRequests).toHaveBeenCalled();
expect(setAddRequest).toHaveBeenCalledWith(999, 123456, 22, true, 'ok', true, undefined);
});
it('corrects a stale canonical eventType from the live inbox', async () => {
const setAddRequest = vi.fn(async () => {});
const trans = Uint8Array.from([0xaa]);
const bridge = fakeBridge({
findGroupInviteCardGroupBySequence: vi.fn(() => undefined),
fetchGroupRequests: vi.fn(async (filtered: boolean) => filtered ? [] : [
fakeRequest({
groupId: 999,
sequence: 123456,
notifyType: 7,
eventType: 1,
filtered: false,
operateTransInfo: trans,
}),
]),
apis: { groupAdmin: { setAddRequest } } as any,
});
await handleGroupAddRequest(bridge, 'slreq:1:123456:999:2:0', true, '');
expect(setAddRequest).toHaveBeenCalledWith(999, 123456, 1, true, '', false, trans);
});
it('accepts a NapCat numeric sequence and resolves the exact main-inbox request', async () => {
@@ -78,7 +101,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, '261237407', false, 'no');
expect(setAddRequest).toHaveBeenCalledWith(999, 261237407, 7, false, 'no', false);
expect(setAddRequest).toHaveBeenCalledWith(999, 261237407, 7, false, 'no', false, undefined);
});
it('accepts a NapCat numeric sequence from the filtered inbox', async () => {
@@ -93,7 +116,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, '55', true, 'ok');
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true);
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true, undefined);
});
it('resolves a private invite-card msgseq by its cached group', async () => {
@@ -106,7 +129,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, '778899', true, 'ok');
expect(setAddRequest).toHaveBeenCalledWith(999, 778899, 2, true, 'ok', false);
expect(setAddRequest).toHaveBeenCalledWith(999, 778899, 2, true, 'ok', false, undefined);
});
it('matches add requests by groupId and targetUid', async () => {
@@ -122,7 +145,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok');
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false);
expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false, undefined);
expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(false, 100);
expect(fetchGroupRequestsByUid).toHaveBeenCalledWith(true, 100);
});
@@ -140,7 +163,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no');
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false);
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false, undefined);
});
it('finds a request that only lives in the filtered inbox (#197)', async () => {
@@ -159,7 +182,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
// Approved through the filtered inbox (subCommand 2 → last arg true).
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true);
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true, undefined);
});
it('surfaces "not found" only when neither inbox has the request', async () => {
@@ -214,7 +237,7 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
await handleGroupAddRequest(bridge, '55', true, 'ok');
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true);
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true, undefined);
});
it('does not report not-found when an unavailable inbox may contain the request', async () => {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.14.10",
"version": "1.14.11",
"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).",
+17 -7
View File
@@ -25,6 +25,10 @@ export interface OidbMuteAll {
}
export interface Oidb0x89a_0AddOptionSettings {
addType?: pb<16, uint_32>;
// EncodeModifyGroupDetailInfoParam: question=30/60224, answer=31/60225.
// Empty string is a real write (clears the other mode), so these are optional.
groupQuestion?: pb_optional<30, string>;
groupAnswer?: pb_optional<31, string>;
}
export interface Oidb0x89a_0AddOption {
groupUin?: pb<1, uint_64>;
@@ -139,10 +143,13 @@ export interface OidbDeleteFriend {
field1?: pb<1, OidbDeleteFriendField1>;
}
export interface OidbGroupRequestBody {
sequence?: pb<1, uint_64>;
eventType?: pb<2, uint_32>;
groupUin?: pb<3, uint_32>;
message?: pb<4, string>;
sequence?: pb<1, uint_64>;
eventType?: pb<2, uint_32>;
groupUin?: pb<3, uint_32>;
// Encoder always writes this field. An omitted empty string is not the
// same as a present empty/space value; callers must set it.
message?: pb_optional<4, string>;
operateTransInfo?: pb<7, bytes>;
}
export interface OidbGroupRequestAction {
accept?: pb<1, uint_32>;
@@ -343,6 +350,7 @@ export interface OidbGroupDetailFlags {
createTime?: pb<2, bool>;
maxMemberCount?: pb<5, bool>;
memberCount?: pb<6, bool>;
addType?: pb<7, bool>;
level?: pb<10, bool>;
name?: pb<15, string>;
noticePreview?: pb<16, string>;
@@ -355,10 +363,12 @@ export interface OidbGroupDetailFlags {
// Official request mask for group shutup expire (proto tag 45 → 60027).
// Lagrange's tag 59 requests 60259, which is a different field.
shutUpAllTimestamp?: pb<45, bool>;
/** Current complete app privilege bitfield; needed for masked mutations. */
privilegeFlag?: pb<99, bool>;
/** Current complete groupFlagExt4 bitfield; needed for masked mutations. */
/** Request the complete app privilege bitfield. */
privilegeFlag?: pb<56, bool>;
/** Request the new-member history-visible switch. */
groupFlagExt4?: pb<101, bool>;
noFingerOpen?: pb<82, bool>;
noCodeFingerOpen?: pb<83, bool>;
}
export interface OidbGroupDetailConfig {
uin?: pb<1, uint_64>;
@@ -278,7 +278,10 @@ export interface DoQunLikeResponse {
export interface DeleteMediasReqBody {
groupId?: pb<1, string>;
albumId?: pb<2, string>;
lloc?: pb<3, string>;
// deleteMedias 4th arg: photo lloc, or a video's cover lloc.
mediaIds?: pb_repeated<3, string>;
// deleteMedias 5th arg: matching batch ids. Android always sends these.
batchIds?: pb_repeated<4, string>;
}
export interface DeleteMediasRequest {
field1?: pb<1, int_32>;
@@ -1,23 +1,17 @@
// Group ext-info modify (robot-add option), RE'd from QQNT
// wrapper.linux.node — OidbSvcTrpcTcp.0xf00_3 (modifyGroupExtInfoV2,
// codec `group_ext_list_modify_codec.cc`). Worker ctor sub_4180800 passes
// cmd=0xf00, sub=3, flag=1 (uin form).
// Group ext-info modify (robot-add option).
// OidbSvcTrpcTcp.0xf00_3 / modifyGroupExtInfoV2.
//
// Wire (EncodeModifyGroupExtInfoReq sub_4180B80 + ...Params sub_4180980):
// ModifyGroupExtInfoReq{ 1:groupCode, 2:GroupExtInfo{ 1:groupCode,
// 2:EXTInfo{ 30:inviteRobotMemberSwitch, 31:inviteRobotMemberExamine } } }
// The GroupExtFilter that modifyGroupExtInfoV2 takes as its 2nd arg is
// CLIENT-SIDE ONLY (it gates which EXTInfo fields the encoder emits); it is
// NOT a wire field. So presence of EXTInfo tag 30/31 IS the write signal.
// NOTE: proto3 omits zero-valued scalars, so a value of 0 will not transmit;
// the robot toggles are non-zero in practice (QQ avoids 0 for set-states).
// Response (DecodeModifyGroupExtInfoRsp sub_4180DB0): {1:groupCode, 2:result}.
// Wire: ModifyGroupExtInfoReq{ 1:groupCode, 2:GroupExtInfo{ 1:groupCode,
// 2:EXTInfo{ 29:inviteRobotMemberSwitch, 30:inviteRobotMemberExamine } } }
// GroupExtFilter is client-side only: it decides which EXTInfo fields the
// encoder emits. Presence of tag 29/30 IS the write signal, including 0.
// Response: {1:groupCode, 2:result}.
import type { pb, int_32, uint_32 } from '@snowluma/proton';
import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64 } from '@snowluma/proton';
export interface OidbGroupExtBody {
inviteRobotMemberSwitch?: pb<30, uint_32>;
inviteRobotMemberExamine?: pb<31, uint_32>;
inviteRobotMemberSwitch?: pb_optional<29, uint_32>;
inviteRobotMemberExamine?: pb_optional<30, uint_32>;
}
export interface OidbGroupExtInfo {
groupCode?: pb<1, uint_32>;
@@ -31,3 +25,24 @@ export interface OidbModifyGroupExtResp {
groupCode?: pb<1, uint_32>;
result?: pb<2, int_32>;
}
// OidbSvcTrpcTcp.0xef0_1 / getGroupExt0xEF0Info.
// DoFetchGroupExtList request: {1:groupCodes, 2:GroupExtFilter}.
// fillGroupExt0xEF0Filter writes filter tags 29/30 when those bits are set.
// Response: repeated item{1:groupCode, 2:resultCode, 3:EXTInfo}.
export interface OidbGroupExtFilter {
inviteRobotMemberSwitch?: pb<29, uint_32>;
inviteRobotMemberExamine?: pb<30, uint_32>;
}
export interface OidbGetGroupExtReq {
groupCodes?: pb_repeated<1, uint_64>;
filter?: pb<2, OidbGroupExtFilter>;
}
export interface OidbGetGroupExtItem {
groupCode?: pb<1, uint_64>;
resultCode?: pb<2, uint_32>;
ext?: pb<3, OidbGroupExtBody>;
}
export interface OidbGetGroupExtResp {
items?: pb_repeated<1, OidbGetGroupExtItem>;
}
+18 -9
View File
@@ -110,6 +110,9 @@ export interface OidbSvcTrpcTcp0x88D_0Results {
createTime?: pb<2, uint_64>;
maxMemberCount?: pb<5, uint_64>;
memberCount?: pb<6, uint_64>;
// DecodeSingleGroupDetailInfoByBaseFilter: tag 7 → 60205 addOption.
// SET uses a different message domain (0x89A settings tag 16).
addType?: pb<7, uint_32>;
level?: pb<10, uint_64>;
name?: pb<15, string>;
noticePreview?: pb<16, string>;
@@ -123,10 +126,14 @@ export interface OidbSvcTrpcTcp0x88D_0Results {
// DecodeSingleGroupDetailInfoByBaseFilter: tag 45 → internal 60027.
// Tag 59 is 60259, not the mute expire. Request mask tag is also 45.
shutUpAllTimestamp?: pb<45, uint_32>;
/** Complete app privilege bitfield (requested with detail flag tag 99). */
privilegeFlag?: pb<99, uint_32>;
/** Complete groupFlagExt4 bitfield (requested with detail flag tag 101). */
/** Complete app privilege bitfield (requested with detail flag tag 56). */
privilegeFlag?: pb<56, uint_32>;
/** New-member history-visible switch (0/1; omitted means hidden). */
groupFlagExt4?: pb<101, uint_32>;
// DecodeSingleGroupDetailInfoByBaseFilter: tag 82 → 60282, tag 83 → 60283.
// SET counterparts are 0x89A settings 35/36. 0 = that search mode is open.
noFingerOpen?: pb<82, uint_32>;
noCodeFingerOpen?: pb<83, uint_32>;
}
export interface OidbSvcTrpcTcp0x88D_0ResponseGroupInfo {
uin?: pb<1, uint_64>;
@@ -208,9 +215,10 @@ export interface OidbSvcTrpcTcp0x10C0ResponseRequest {
group?: pb<4, OidbSvcTrpcTcp0x10C0ResponseGroup>;
target?: pb<5, OidbSvcTrpcTcp0x10C0ResponseUser>;
invitor?: pb<6, OidbSvcTrpcTcp0x10C0ResponseUser>;
operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUser>;
field9?: pb<9, string>;
comment?: pb<10, string>;
operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUser>;
field9?: pb<9, string>;
comment?: pb<10, string>;
operateTransInfo?: pb<14, bytes>;
}
export interface OidbSvcTrpcTcp0x10C0Response {
@@ -238,9 +246,10 @@ export interface OidbSvcTrpcTcp0x10C0ResponseRequestByUin {
group?: pb<4, OidbSvcTrpcTcp0x10C0ResponseGroup>;
target?: pb<5, OidbSvcTrpcTcp0x10C0ResponseUserByUin>;
invitor?: pb<6, OidbSvcTrpcTcp0x10C0ResponseUserByUin>;
operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUserByUin>;
field9?: pb<9, string>;
comment?: pb<10, string>;
operatorUser?: pb<7, OidbSvcTrpcTcp0x10C0ResponseUserByUin>;
field9?: pb<9, string>;
comment?: pb<10, string>;
operateTransInfo?: pb<14, bytes>;
}
export interface OidbSvcTrpcTcp0x10C0ResponseByUin {
+2 -1
View File
@@ -134,7 +134,8 @@ function makePipeline(identity: IdentityService): IncomingPacketPipeline {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: async () => false,
fetchGroupList: async () => {},
fetchGroupMemberList: async () => {},
});
pipeline.registerCmd(MSG_PUSH_CMD, parseMsgPush);
return pipeline;
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.14.10",
"version": "1.14.11",
"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>'`.",
+2 -17
View File
@@ -1,4 +1,5 @@
import type { MsgPushHead, PushMsgBody } from './context';
import { hasDecodableContent } from './rich-body-decoder';
// C2C-family message types (private 166, temp 141, and 167) whose pushes QQ NT
// classifies by `c2c_cmd`. RE: `long_cnn_msg_mgr.cc::OnRecvSysMsg` gates on
@@ -24,22 +25,6 @@ export function isC2cControlPush(head: Pick<MsgPushHead, 'msgType' | 'c2cCmd'>):
return C2C_CONTROL_TYPES.has(head.msgType) && C2C_CONTROL_CMDS.has(head.c2cCmd);
}
/**
* Whether a push body carries anything {@link decodeRichBody} could turn into an
* element: source `richText.elems`, a voice (`ptt`), a c2c file
* (`notOnlineFile`), or serialised `msgContent` file metadata. Mirrors exactly
* what the rich-body decoder reads. A body with none of these is a genuinely
* content-less control push, not an element type we merely fail to decode.
*/
export function bodyHasDecodableContent(body: PushMsgBody | undefined): boolean {
const rt = body?.richText;
if (rt) {
if (rt.elems && rt.elems.length > 0) return true;
if (rt.ptt || rt.notOnlineFile) return true;
}
return !!(body?.msgContent && body.msgContent.length > 0);
}
/**
* A message-kind event is "blank" — the "[空消息]" phantom from #102 — when it
* decoded to zero elements AND its body carried nothing decodable. These are
@@ -62,5 +47,5 @@ export function isBlankMessage(
elements: readonly unknown[],
body: PushMsgBody | undefined,
): boolean {
return elements.length === 0 && !bodyHasDecodableContent(body);
return elements.length === 0 && !hasDecodableContent(body);
}
+7 -1
View File
@@ -13,7 +13,13 @@ export type DecompressDataResult =
export function makeImageUrl(origUrl: string): string {
if (!origUrl) return '';
if (origUrl.includes('rkey')) return 'https://multimedia.nt.qq.com.cn' + origUrl;
if (/^https?:\/\//i.test(origUrl)) return origUrl;
// Compatibility faces sometimes carry a query fragment without a path.
// Prefixing the host onto that produces an unusable URL.
if (!origUrl.startsWith('/')) return '';
if (origUrl.includes('rkey') || origUrl.includes('fileid')) {
return 'https://multimedia.nt.qq.com.cn' + origUrl;
}
return 'http://gchat.qpic.cn' + origUrl;
}
+3 -2
View File
@@ -4,7 +4,8 @@ import type { PacketInfo } from '@snowluma/common/protocol-types';
import type { Elem } from '@snowluma/proto-defs/element';
import type { QQEventVariant } from '../events';
import type { IdentityService } from '../identity-service';
import { bodyHasDecodableContent, isC2cControlPush } from './blank-filter';
import { isC2cControlPush } from './blank-filter';
import { hasDecodableContent } from './rich-body-decoder';
import { buildContext, type PushMsgBody } from './context';
import { decodeEvent0x210 } from './decoders/event-0x210';
import { decodeEvent0x2DC } from './decoders/event-0x2dc';
@@ -217,7 +218,7 @@ function parseMsgPushInternal(
// If instead the body *had* content we just couldn't decode, keep the
// (still-empty) event but warn so the missing decoder gets noticed rather
// than silently swallowed.
if (bodyHasDecodableContent(ctx.body)) {
if (hasDecodableContent(ctx.body)) {
log.warn('message had content but decoded to 0 elements — missing decoder? (kind=%s seq=%d from=%d msgType=%d/%d): %s',
ev.kind, ctx.head.sequence, ctx.fromUin, ctx.head.msgType, ctx.head.subType,
describeUndecodedBody(ctx.body));
@@ -457,6 +457,19 @@ function buildMediaNode(idx: IndexNode, fi: FileInfo): MessageElement['mediaNode
};
}
/** Whether this body carries any slot {@link decodeRichBody} would try:
* `richText.elems`, a voice (`ptt`), a c2c file (`notOnlineFile`), or
* serialized `msgContent`. Presence, not successful decode — a body that
* has elems we do not yet understand is still decodable content. */
export function hasDecodableContent(body: PushMsgBody | undefined): boolean {
const rt = body?.richText;
if (rt) {
if (rt.elems && rt.elems.length > 0) return true;
if (rt.ptt || rt.notOnlineFile) return true;
}
return !!(body?.msgContent && body.msgContent.length > 0);
}
export function decodeRichBody(body: PushMsgBody | undefined, isGroup: boolean): MessageElement[] {
const elements: MessageElement[] = [];
logUnknownWireFields(body, 'body');
@@ -937,7 +950,46 @@ function convertElements(elems: ElemDecoded[]): MessageElement[] {
}
}
return result;
return dropLegacyImageSiblings(result);
}
function isNtImage(element: MessageElement): boolean {
if (element.type !== 'image') return false;
if (element.picFormat != null || element.sha1Hex) return true;
const url = element.imageUrl ?? '';
return url.includes('://multimedia.nt.qq.com.cn/');
}
function isUsableImageUrl(url: string): boolean {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return false;
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return false;
if (parsed.hostname === 'multimedia.nt.qq.com.cn') return parsed.pathname.length > 1;
return parsed.pathname.length > 1;
}
function sameImageFile(left: MessageElement, right: MessageElement): boolean {
if (left.type !== 'image' || right.type !== 'image') return false;
if (left.fileId && right.fileId && left.fileId === right.fileId) return true;
return Boolean(left.md5Hex && right.md5Hex && left.md5Hex === right.md5Hex);
}
// [#389] NT pictures arrive as CommonElem plus a CustomFace / NotOnlineImage
// sibling for older clients. QQ shows one picture. Keep the NT image and drop
// the sibling when it names the same file, or when its URL cannot be fetched.
function dropLegacyImageSiblings(elements: MessageElement[]): MessageElement[] {
const ntImages = elements.filter(isNtImage);
return elements.filter((element) => {
if (element.type !== 'image') return true;
if (isNtImage(element)) return true;
const url = element.imageUrl ?? '';
if (!url || !isUsableImageUrl(url)) return false;
return !ntImages.some((nt) => sameImageFile(nt, element));
});
}
/**
@@ -33,7 +33,8 @@ export namespace FetchGroupDetail {
level: on, name: '', noticePreview: '', uin: on, lastSequence: on,
lastMessageTime: on, question: on, answer: '', maxAdminCount: '',
// Tag 45 (not Lagrange's 59): official request mask for 60027.
shutUpAllTimestamp: on, privilegeFlag: on, groupFlagExt4: on,
shutUpAllTimestamp: on, addType: on, privilegeFlag: on, groupFlagExt4: on,
noFingerOpen: on, noCodeFingerOpen: on,
},
},
});
@@ -0,0 +1,52 @@
// 0xef0_1 — getGroupExt0xEF0Info. Used to read the current robot-add
// switch/examine values that set_group_robot_add_option writes.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGetGroupExtReq, OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupExtRobotOption {
robotMemberSwitch: number;
robotMemberExamine: number;
}
export namespace FetchGroupExtInfo {
export const command = 0xEF0;
export const subCommand = 1;
export const uinForm = true;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGetGroupExtReq => ({
groupCodes: [BigInt(p.groupId)],
filter: {
inviteRobotMemberSwitch: 1,
inviteRobotMemberExamine: 1,
},
});
export const deserialize = (_ctx: Deps, body: OidbGetGroupExtResp): GroupExtRobotOption => {
const item = body.items?.[0];
if (!item) {
throw new Error('unable to read group robot-add option');
}
if (item.resultCode && item.resultCode !== 0) {
throw new Error(`unable to read group robot-add option: result=${item.resultCode}`);
}
return {
robotMemberSwitch: item.ext?.inviteRobotMemberSwitch ?? 0,
robotMemberExamine: item.ext?.inviteRobotMemberExamine ?? 0,
};
};
export const encode = (env: OidbBase<OidbGetGroupExtReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGetGroupExtReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGetGroupExtResp> =>
protobuf_decode<OidbBase<OidbGetGroupExtResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupExtRobotOption> =>
invokeOidb(deps, FetchGroupExtInfo, params);
}
@@ -1,10 +1,9 @@
// 0xf00_3 — modifyGroupExtInfoV2, used for set_group_robot_add_option.
// RE'd from QQNT group_ext_list_modify_codec.cc:
// ModifyGroupExtInfoReq{ 1:groupCode, 2:GroupExtInfo{ 1:groupCode,
// 2:EXTInfo{ 30:inviteRobotMemberSwitch, 31:inviteRobotMemberExamine } } }
// The NT GroupExtFilter (2nd kernel arg) is client-side only — it just gates
// which EXTInfo fields the encoder emits — so we mirror that by only setting
// the fields the caller provides. uin-form OIDB (envelope reserved=1).
// 2:EXTInfo{ 29:inviteRobotMemberSwitch, 30:inviteRobotMemberExamine } } }
// GroupExtFilter is client-side only — it gates which EXTInfo fields the
// encoder emits, including a value of 0. We only set the fields the caller
// provides. uin-form OIDB (envelope reserved=1).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
@@ -50,6 +49,10 @@ export namespace ModifyGroupExtInfo {
export const decode = (bytes: Uint8Array): OidbBase<OidbModifyGroupExtResp> =>
protobuf_decode<OidbBase<OidbModifyGroupExtResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
invokeOidb(deps, ModifyGroupExtInfo, params);
export const invoke = (deps: Deps, params: Params): Promise<void> => {
if (params.robotMemberSwitch === undefined && params.robotMemberExamine === undefined) {
return Promise.resolve();
}
return invokeOidb(deps, ModifyGroupExtInfo, params);
};
}
@@ -4,22 +4,44 @@
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0AddOption } from '@snowluma/proto-defs/oidb-actions/base';
import type {
Oidb0x89a_0AddOption,
Oidb0x89a_0AddOptionSettings,
} from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
/** Official join modes that carry a question. 55 is accepted as an alias of 5. */
export function isQuestionAddType(addType: number): boolean {
return addType === 4 || addType === 5 || addType === 55;
}
export function wireAddType(addType: number): number {
return addType === 55 ? 5 : addType;
}
export namespace SetAddOption {
export const command = 0x89A;
export const subCommand = 0;
export interface Params { groupId: number; addType: number; }
export interface Params {
groupId: number;
addType: number;
groupQuestion?: string;
groupAnswer?: string;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0AddOption => ({
groupUin: BigInt(p.groupId),
settings: { addType: p.addType },
field12: 0,
});
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0AddOption => {
const addType = wireAddType(p.addType);
const settings: Oidb0x89a_0AddOptionSettings = { addType };
if (isQuestionAddType(p.addType)) {
settings.groupQuestion = p.groupQuestion ?? '';
// Type 4 keeps the answer; type 5/55 is question-only and clears it.
settings.groupAnswer = addType === 4 ? (p.groupAnswer ?? '') : '';
}
return { groupUin: BigInt(p.groupId), settings, field12: 0 };
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
@@ -20,21 +20,30 @@ export namespace SetAddRequest {
approve: boolean;
reason?: string;
filtered?: boolean;
operateTransInfo?: Uint8Array;
}
export type Deps = OidbSender;
export const resolveSubCommand = (p: Params): number => p.filtered ? 2 : 1;
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestAction => ({
accept: p.approve ? 1 : 2,
body: {
sequence: BigInt(p.sequence),
eventType: p.eventType,
groupUin: p.groupId,
message: p.reason ?? '',
},
});
export const serialize = (_ctx: Deps, p: Params): OidbGroupRequestAction => {
const reason = p.reason ?? '';
return {
accept: p.approve ? 1 : 2,
body: {
sequence: BigInt(p.sequence),
eventType: p.eventType,
groupUin: p.groupId,
// Native operate always writes field 4. An omitted empty string is
// rejected; a present space is the native empty-reason form.
message: reason.length > 0 ? reason : ' ',
...(p.operateTransInfo && p.operateTransInfo.length > 0
? { operateTransInfo: p.operateTransInfo }
: {}),
},
};
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
@@ -39,6 +39,15 @@ export function mergeMemberInvitePrivilegeFlag(
return Number((current & ~mask) | (requested & mask));
}
export function decodeMemberInvitePolicy(privilegeFlag: number): GroupMemberInvitePolicy {
assertUint32(privilegeFlag, 'privilege flag');
const bits = privilegeFlag & MEMBER_INVITE_PRIVILEGE_MASK;
if ((bits & 0x04000000) !== 0) return 'disabled';
if ((bits & 0x02000000) !== 0) return 'no_approval_under_100';
if ((bits & 0x00100000) !== 0) return 'no_approval';
return 'require_approval';
}
export namespace SetMemberInvitePolicy {
export const command = 0x89A;
export const subCommand = 0;
@@ -32,6 +32,22 @@ export function mergeGroupMemberPermission(
return Number(allow ? current & ~mask : current | mask);
}
export function decodeGroupMemberPermissions(privilegeFlag: number): {
allowMemberUploadAlbum: boolean;
allowMemberTemporarySession: boolean;
allowMemberCreateGroup: boolean;
} {
assertUint32(privilegeFlag, 'privilege flag');
return {
allowMemberUploadAlbum:
(privilegeFlag & GROUP_MEMBER_PERMISSION_MASKS.upload_album) === 0,
allowMemberTemporarySession:
(privilegeFlag & GROUP_MEMBER_PERMISSION_MASKS.temporary_session) === 0,
allowMemberCreateGroup:
(privilegeFlag & GROUP_MEMBER_PERMISSION_MASKS.create_group) === 0,
};
}
export namespace SetMemberPermission {
export const command = 0x89A;
export const subCommand = 0;
@@ -1,6 +1,7 @@
// 0x89A_0 — control whether newly joined members may browse group history.
// QQ sends the complete current groupFlagExt4 value with a mutation mask, so
// callers must read the flag before invoking this namespace.
// Mutation writes the extended-flag value plus a one-bit mask. The matching
// group-detail reply is a 0/1 switch (omitted means hidden), not the full
// extended-flag bitfield.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
@@ -22,13 +23,18 @@ export function mergeGroupHistoryVisibility(currentGroupFlagExt4: number, visibl
return Number(visible ? current | mask : current & ~mask);
}
export function decodeGroupHistoryVisibility(groupFlagExt4: number): boolean {
assertUint32(groupFlagExt4, 'group history flag');
// Detail replies use 0/1. The mutation bitfield still uses bit 2.
return groupFlagExt4 === 1 || (groupFlagExt4 & GROUP_HISTORY_VISIBILITY_MASK) !== 0;
}
export namespace SetNewMemberHistoryVisibility {
export const command = 0x89A;
export const subCommand = 0;
export interface Params {
groupId: number;
currentGroupFlagExt4: number;
visible: boolean;
}
@@ -37,7 +43,7 @@ export namespace SetNewMemberHistoryVisibility {
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0HistoryVisibility => ({
groupUin: BigInt(p.groupId),
settings: {
groupFlagExt4: mergeGroupHistoryVisibility(p.currentGroupFlagExt4, p.visible),
groupFlagExt4: p.visible ? GROUP_HISTORY_VISIBILITY_MASK : 0,
groupFlagExt4Mask: GROUP_HISTORY_VISIBILITY_MASK,
},
});
+25 -24
View File
@@ -40,12 +40,12 @@ class EnrichedDispatchError extends Error {
export interface PacketPipelineDeps {
identity: IdentityService;
events: BridgeEventBus;
/**
* Refresh group + member roster as a side-effect. Resolves with
* whether any refresh actually ran (false when the group is unknown
* and `refreshGroupList` was false).
*/
refreshMemberCache(groupId: number, refreshGroupList: boolean, forceMemberList: boolean): Promise<boolean>;
/** Account group-list fetch. Roster side-effect only; the pipeline
* swallows failures and does not read the returned roster. */
fetchGroupList(): Promise<void>;
/** One group's member-list fetch (adapter TTL applies). Roster
* side-effect only; the pipeline does not pass `force`. */
fetchGroupMemberList(groupId: number): Promise<void>;
/**
* Resolve the verify message ("postscript") + server sequence number
* for a pending group-join / group-invite. The OIDB push only
@@ -335,12 +335,11 @@ export class IncomingPacketPipeline {
pkt: PacketInfo,
event: QQEventVariant,
mode: 'sync' | 'enriched',
alreadyRefreshed = false,
): number {
// Snapshot the sender's cached group card BEFORE dispatch — the side-effects
// inside finishDispatch self-heal it, so the old value must be read first.
const cardBefore = this.groupCardBefore(event);
this.finishDispatch(event, alreadyRefreshed);
this.finishDispatch(event);
this.traceDispatch(pkt, event.kind, mode);
if (!this.emitGroupCardChange(event, cardBefore)) return 1;
this.traceDispatch(pkt, 'group_card_change', 'derived');
@@ -382,13 +381,10 @@ export class IncomingPacketPipeline {
/**
* Common dispatch tail shared by the sync path and the two async enrichment
* paths: run side effects, log the event, then emit it. `alreadyRefreshed` is
* threaded through to `handleSideEffects` (true only on the identity-refresh
* path, where the roster refresh was already done) — it defaults false, so
* `finishDispatch(event)` matches the old `handleSideEffects(event)` calls.
* paths: run side effects, log the event, then emit it.
*/
private finishDispatch(event: QQEventVariant, alreadyRefreshed = false): void {
this.handleSideEffects(event, alreadyRefreshed);
private finishDispatch(event: QQEventVariant): void {
this.handleSideEffects(event);
printEvent(this.eventLog, this.deps.identity, event);
this.emit(event);
}
@@ -422,9 +418,8 @@ export class IncomingPacketPipeline {
pkt: PacketInfo,
event: Extract<QQEventVariant, { kind: 'group_member_join' }>,
): Promise<number> {
let refreshed = false;
try {
refreshed = await this.prepareGroupMemberJoinIdentity(event);
await this.prepareGroupMemberJoinIdentity(event);
} catch (e) {
this.packetLog.trace(() => [
'packet_branch serviceCmd=%j seqId=%d branch=enrichment_degraded eventKind=%j enrichment="identity_refresh" error=%j',
@@ -438,7 +433,7 @@ export class IncomingPacketPipeline {
}
try {
return this.dispatchEvent(pkt, event, 'enriched', refreshed);
return this.dispatchEvent(pkt, event, 'enriched');
} catch (error) {
throw new EnrichedDispatchError(error);
}
@@ -546,15 +541,13 @@ export class IncomingPacketPipeline {
}
}
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<boolean> {
private async prepareGroupMemberJoinIdentity(event: Extract<QQEventVariant, { kind: 'group_member_join' }>): Promise<void> {
this.resolveMemberIdentityFromCache(event);
if (event.userUin > 0 || !event.userUid) return false;
if (event.userUin > 0 || !event.userUid) return;
const uin = await this.deps.identity.resolveUin(event.userUid, event.groupId);
if (uin !== null) event.userUin = uin;
this.resolveMemberIdentityFromCache(event);
// Roster refresh stays a post-dispatch side-effect, not the UIN hop.
return false;
}
private resolveMemberIdentityFromCache(event: GroupMemberIdentityEvent): void {
@@ -574,9 +567,8 @@ export class IncomingPacketPipeline {
return (uin > 0 && uin === selfUin) || (Boolean(uid) && uid === this.deps.identity.selfUid);
}
private handleSideEffects(event: QQEventVariant, alreadyRefreshed = false): void {
private handleSideEffects(event: QQEventVariant): void {
this.rememberEventIdentity(event);
if (alreadyRefreshed) return;
let groupId = 0;
let reason = '';
@@ -607,7 +599,16 @@ export class IncomingPacketPipeline {
const task = (async () => {
try {
await this.deps.refreshMemberCache(groupId, refreshGroupList, false);
if (refreshGroupList) {
try {
await this.deps.fetchGroupList();
} catch { /* ignore */ }
}
if (!this.deps.identity.findGroup(groupId)) {
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
return;
}
await this.deps.fetchGroupMemberList(groupId);
this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason);
} catch (e) {
this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s',
+1
View File
@@ -81,6 +81,7 @@ export interface GroupRequestInfo {
eventType: number;
comment: string;
filtered: boolean;
operateTransInfo?: Uint8Array;
}
/** Approval tuple required by OIDB 0x10C8. The OneBot flag is opaque to
@@ -12,7 +12,7 @@ import { describe, expect, it } from 'vitest';
import { deflateSync } from 'zlib';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { getLogLevel, setLogLevel, subscribeLogs } from '@snowluma/common/logger';
import { decodeRichBody } from '../../src/msg-push/rich-body-decoder';
import { decodeRichBody, hasDecodableContent } from '../../src/msg-push/rich-body-decoder';
import { MAX_RICH_CARD_OUTPUT_BYTES } from '../../src/msg-push/helpers';
import { buildSendElems } from '../../src/element-builder';
import { assertValidMessageElement } from '../../src/element-manifest';
@@ -25,6 +25,7 @@ import type {
SrcMsgPbReserve,
TextElem,
} from '@snowluma/proto-defs/element';
import { makeImageUrl } from '../../src/msg-push/helpers';
function lightAppBytes(json: unknown): Uint8Array {
const buf = deflateSync(Buffer.from(JSON.stringify(json), 'utf8'));
@@ -922,6 +923,153 @@ describe('decodeRichBody / unknown wire element observability', () => {
}));
});
function ntImageElem(fileName: string): Elem {
const msgInfo: MsgInfo = {
msgInfoBody: [{
index: {
info: {
fileSize: 10711,
fileHash: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
fileSha1: 'bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb',
fileName,
width: 1080,
height: 1080,
type: { picFormat: 1001 },
},
},
picture: {
urlPath: '/download?appid=1407&fileid=EhRgood',
domain: 'multimedia.nt.qq.com.cn',
ext: { originalParameter: '&rkey=good' },
},
}],
extBizInfo: { pic: { bizType: 0, textSummary: '[图片]' } },
};
return {
commonElem: {
serviceType: 48,
businessType: 20,
pbElem: protobuf_encode<MsgInfo>(msgInfo),
},
};
}
function customFaceElem(filePath: string, origUrl: string, md5: Uint8Array): Elem {
return {
customFace: {
filePath,
origUrl,
md5,
size: 10711,
width: 1080,
height: 1080,
},
};
}
describe('decodeRichBody / NT image compatibility siblings (#389)', () => {
const fileName = 'bcc7bbcc76a1a9d940c57346a5d223e8.png';
const otherMd5 = Uint8Array.from({ length: 16 }, (_, i) => i + 1);
it('keeps the NT image and drops the query-only customFace sibling', () => {
const out = decodeRichBody({
richText: {
elems: [
ntImageElem(fileName),
customFaceElem(fileName, '&rkey=xxx&spec=0', otherMd5),
],
},
}, true);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({
type: 'image',
fileId: fileName,
imageUrl: 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=EhRgood&rkey=good',
picFormat: 1001,
});
});
it('drops a same-file customFace even when its legacy URL is well-formed', () => {
const out = decodeRichBody({
richText: {
elems: [
ntImageElem(fileName),
customFaceElem(fileName, '/gchatpic_new/0/0-0-AABB/0', otherMd5),
],
},
}, true);
expect(out).toEqual([
expect.objectContaining({ type: 'image', fileId: fileName, picFormat: 1001 }),
]);
});
it('keeps a standalone customFace with a usable download path', () => {
const out = decodeRichBody({
richText: {
elems: [customFaceElem(fileName, '/gchatpic_new/0/0-0-AABB/0', otherMd5)],
},
}, true);
expect(out).toEqual([{
type: 'image',
imageUrl: 'http://gchat.qpic.cn/gchatpic_new/0/0-0-AABB/0',
fileId: fileName,
fileSize: 10711,
width: 1080,
height: 1080,
subType: 0,
summary: '[图片]',
md5Hex: '0102030405060708090A0B0C0D0E0F10',
}]);
});
it('drops a standalone customFace whose URL cannot be fetched', () => {
const out = decodeRichBody({
richText: {
elems: [customFaceElem(fileName, '&rkey=xxx&spec=0', otherMd5)],
},
}, true);
expect(out).toEqual([]);
});
it('keeps two distinct pictures', () => {
const second = 'other.png';
const out = decodeRichBody({
richText: {
elems: [
ntImageElem(fileName),
customFaceElem(second, '/gchatpic_new/0/0-0-CCDD/0', otherMd5),
],
},
}, true);
expect(out.map((el) => el.type === 'image' ? el.fileId : el.type)).toEqual([
fileName,
second,
]);
});
});
describe('makeImageUrl', () => {
it('prefixes NT paths that already include a download path', () => {
expect(makeImageUrl('/download?appid=1407&fileid=abc&rkey=x'))
.toBe('https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=abc&rkey=x');
});
it('does not glue the NT host onto a query fragment (#389)', () => {
expect(makeImageUrl('&rkey=xxx&spec=0')).toBe('');
expect(makeImageUrl('rkey=xxx&spec=0')).toBe('');
});
it('prefixes legacy gchat paths', () => {
expect(makeImageUrl('/gchatpic_new/0/0-0-AABB/0'))
.toBe('http://gchat.qpic.cn/gchatpic_new/0/0-0-AABB/0');
});
});
it('bounds retained card output across the entire message', () => {
const previousLevel = getLogLevel();
const captured: Array<{ scope: string; message: string }> = [];
@@ -982,3 +1130,24 @@ describe('decodeRichBody / unknown wire element observability', () => {
expect(exhausted).toHaveLength(2);
});
});
describe('hasDecodableContent', () => {
it('is false for a missing or empty body', () => {
expect(hasDecodableContent(undefined)).toBe(false);
expect(hasDecodableContent({})).toBe(false);
expect(hasDecodableContent({ richText: { elems: [] } })).toBe(false);
});
it('is true for elems, ptt, notOnlineFile, or msgContent', () => {
expect(hasDecodableContent({ richText: { elems: [{ text: { str: 'hi' } }] } })).toBe(true);
expect(hasDecodableContent({ richText: { ptt: { fileName: 'a.amr' } } })).toBe(true);
expect(hasDecodableContent({ richText: { notOnlineFile: { fileName: 'a.bin' } } })).toBe(true);
expect(hasDecodableContent({ msgContent: new Uint8Array([1]) })).toBe(true);
});
it('is true when elems exist even if decodeRichBody would emit nothing', () => {
const body: MessageBody = { richText: { elems: [{ commonElem: { serviceType: 999, businessType: 0 } }] } };
expect(hasDecodableContent(body)).toBe(true);
expect(decodeRichBody(body, false)).toEqual([]);
});
});
@@ -20,7 +20,7 @@ interface GroupDetailResultsFixture {
name?: pb<15, string>;
shutUpAllTimestamp?: pb<45, uint_32>;
leftover59?: pb<59, uint_32>;
privilegeFlag?: pb<99, uint_32>;
privilegeFlag?: pb<56, uint_32>;
groupFlagExt4?: pb<101, uint_32>;
}
@@ -60,6 +60,9 @@ describe('FetchGroupDetail namespace', () => {
.toBe(true);
expect(out.config?.flags?.privilegeFlag).toBe(true);
expect(out.config?.flags?.groupFlagExt4).toBe(true);
expect(out.config?.flags?.addType).toBe(true);
expect(out.config?.flags?.noFingerOpen).toBe(true);
expect(out.config?.flags?.noCodeFingerOpen).toBe(true);
});
});
@@ -182,5 +185,29 @@ describe('FetchGroupDetail namespace', () => {
const out = await FetchGroupDetail.invoke(sender, { groupUin: 601692726 });
expect(out.groupInfo?.results?.groupFlagExt4).toBe(0x80000005);
});
it('decodes add-option and search flags from the detail response', async () => {
const responseData = Buffer.from(protobuf_encode<OidbBase<OidbSvcTrpcTcp0x88D_0Response>>({
body: {
groupInfo: {
uin: 601692726n,
results: { addType: 2, noFingerOpen: 1, noCodeFingerOpen: 0 },
},
},
}));
const sender = makeSender();
sender.sendRawPacket.mockResolvedValue({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
});
const out = await FetchGroupDetail.invoke(sender, { groupUin: 601692726 });
expect(out.groupInfo?.results?.addType).toBe(2);
expect(out.groupInfo?.results?.noFingerOpen).toBe(1);
expect(out.groupInfo?.results?.noCodeFingerOpen ?? 0).toBe(0);
});
});
});
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { OidbGetGroupExtReq, OidbGetGroupExtResp } from '@snowluma/proto-defs/oidb-actions/group-ext';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { FetchGroupExtInfo } from '../../../src/oidb-services/group-admin/get-group-ext-info';
import { env, v, m } from '../_pb-oracle';
function makeSender(body?: OidbGetGroupExtResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGetGroupExtResp>>({ body }))
: Buffer.alloc(0);
const result: SendPacketResult = {
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData,
};
return { sendRawPacket: vi.fn(async () => result) };
}
describe('FetchGroupExtInfo namespace', () => {
it('declares command 0xEF0 sub 1, uin form', () => {
expect(FetchGroupExtInfo.command).toBe(0xEF0);
expect(FetchGroupExtInfo.subCommand).toBe(1);
expect(FetchGroupExtInfo.uinForm).toBe(true);
});
it('byte-oracle: routes to 0xef0_1 and locks {1:groupCode, 2:{29:1,30:1}}', async () => {
const sender = makeSender({
items: [{ groupCode: 12345n, ext: { inviteRobotMemberSwitch: 1, inviteRobotMemberExamine: 2 } }],
});
await FetchGroupExtInfo.invoke(sender, { groupId: 12345 });
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xef0_1');
const filter = [...v(29, 1), ...v(30, 1)];
const body = [...v(1, 12345), ...m(2, filter)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0xEF0, 1, body, true));
const envelope = protobuf_decode<OidbBase<OidbGetGroupExtReq>>(bytes);
expect(envelope.reserved).toBe(1);
expect(envelope.body?.groupCodes).toEqual([12345n]);
});
it('returns robot-add switch/examine from the first item', async () => {
const sender = makeSender({
items: [{
groupCode: 12345n,
ext: { inviteRobotMemberSwitch: 1, inviteRobotMemberExamine: 2 },
}],
});
await expect(FetchGroupExtInfo.invoke(sender, { groupId: 12345 })).resolves.toEqual({
robotMemberSwitch: 1,
robotMemberExamine: 2,
});
});
it('treats omitted zeros as 0', async () => {
const sender = makeSender({ items: [{ groupCode: 12345n, ext: {} }] });
await expect(FetchGroupExtInfo.invoke(sender, { groupId: 12345 })).resolves.toEqual({
robotMemberSwitch: 0,
robotMemberExamine: 0,
});
});
it('throws when the list is empty', async () => {
const sender = makeSender({ items: [] });
await expect(FetchGroupExtInfo.invoke(sender, { groupId: 12345 }))
.rejects.toThrow(/unable to read group robot-add option/);
});
it('throws on a non-zero item result', async () => {
const sender = makeSender({
items: [{ groupCode: 12345n, resultCode: 5, ext: { inviteRobotMemberSwitch: 1 } }],
});
await expect(FetchGroupExtInfo.invoke(sender, { groupId: 12345 }))
.rejects.toThrow(/result=5/);
});
});
@@ -29,24 +29,42 @@ describe('ModifyGroupExtInfo namespace', () => {
.toEqual({ groupCode: 1, info: { groupCode: 1, ext: {} } });
});
it('byte-oracle: routes to 0xf00_3 and locks nested tags {1:gc,2:{1:gc,2:{30:switch,31:examine}}}', async () => {
it('byte-oracle: routes to 0xf00_3 and locks nested tags {1:gc,2:{1:gc,2:{29:switch,30:examine}}}', async () => {
const sender = makeSender();
await ModifyGroupExtInfo.invoke(sender, { groupId: 12345, robotMemberSwitch: 1, robotMemberExamine: 2 });
const [cmd, bytes] = sender.sendRawPacket.mock.calls[0]!;
expect(cmd).toBe('OidbSvcTrpcTcp.0xf00_3');
const ext = [...v(30, 1), ...v(31, 2)];
const ext = [...v(29, 1), ...v(30, 2)];
const info = [...v(1, 12345), ...m(2, ext)];
const body = [...v(1, 12345), ...m(2, info)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0xF00, 3, body, true));
});
it('CAVEAT: a value of 0 is omitted on the wire (proto3 default) — documents the disable edge', async () => {
it('emits switch=0 on the wire (explicit presence; omit would look like "unchanged")', async () => {
const sender = makeSender();
await ModifyGroupExtInfo.invoke(sender, { groupId: 12345, robotMemberSwitch: 0 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
// tag 30 varint = 0xF0 0x01; with value 0 it must NOT appear on the wire.
expect(Buffer.from(bytes).toString('hex')).not.toContain('f001');
const ext = [...v(29, 0)];
const info = [...v(1, 12345), ...m(2, ext)];
const body = [...v(1, 12345), ...m(2, info)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0xF00, 3, body, true));
});
it('emits both zeros when the caller sets switch and examine to 0', async () => {
const sender = makeSender();
await ModifyGroupExtInfo.invoke(sender, { groupId: 12345, robotMemberSwitch: 0, robotMemberExamine: 0 });
const [, bytes] = sender.sendRawPacket.mock.calls[0]!;
const ext = [...v(29, 0), ...v(30, 0)];
const info = [...v(1, 12345), ...m(2, ext)];
const body = [...v(1, 12345), ...m(2, info)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0xF00, 3, body, true));
});
it('does not send when neither field is provided', async () => {
const sender = makeSender();
await ModifyGroupExtInfo.invoke(sender, { groupId: 12345 });
expect(sender.sendRawPacket).not.toHaveBeenCalled();
});
it('deserialize throws on a non-zero body result', () => {
@@ -4,7 +4,12 @@ import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0AddOption } from '@snowluma/proto-defs/oidb-actions/base';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetAddOption } from '../../../src/oidb-services/group-admin/set-add-option';
import {
isQuestionAddType,
SetAddOption,
wireAddType,
} from '../../../src/oidb-services/group-admin/set-add-option';
import { env, v, s, m } from '../_pb-oracle';
function makeDeps() {
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
@@ -22,7 +27,51 @@ describe('SetAddOption namespace', () => {
await SetAddOption.invoke(deps, { groupId: 12345, addType: 2 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x89a_0');
const env = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bytes);
expect(env.body).toMatchObject({ groupUin: 12345n, settings: { addType: 2 } });
const decoded = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(bytes);
expect(decoded.body).toMatchObject({ groupUin: 12345n, settings: { addType: 2 } });
expect(decoded.body?.settings?.groupQuestion ?? undefined).toBeUndefined();
expect(decoded.body?.settings?.groupAnswer ?? undefined).toBeUndefined();
});
it('treats 4 as question+answer and 5/55 as question-only', () => {
expect(isQuestionAddType(4)).toBe(true);
expect(isQuestionAddType(5)).toBe(true);
expect(isQuestionAddType(55)).toBe(true);
expect(isQuestionAddType(2)).toBe(false);
expect(wireAddType(55)).toBe(5);
expect(wireAddType(4)).toBe(4);
});
it('byte-oracle: type 4 writes question and answer', async () => {
const deps = makeDeps();
await SetAddOption.invoke(deps, {
groupId: 12345, addType: 4, groupQuestion: 'q', groupAnswer: 'a',
});
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const settings = [...v(16, 4), ...s(30, 'q'), ...s(31, 'a')];
const body = [...v(1, 12345), ...m(2, settings)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0x89A, 0, body, false));
});
it('byte-oracle: type 5 writes question and clears answer', async () => {
const deps = makeDeps();
await SetAddOption.invoke(deps, {
groupId: 12345, addType: 5, groupQuestion: 'why', groupAnswer: 'ignored',
});
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const settings = [...v(16, 5), ...s(30, 'why'), ...s(31, '')];
const body = [...v(1, 12345), ...m(2, settings)];
expect(Buffer.from(bytes).toString('hex')).toBe(env(0x89A, 0, body, false));
});
it('maps add_type 55 onto the official question-only mode', async () => {
const deps = makeDeps();
await SetAddOption.invoke(deps, { groupId: 1, addType: 55, groupQuestion: 'q' });
const decoded = protobuf_decode<OidbBase<Oidb0x89a_0AddOption>>(
deps.sendRawPacket.mock.calls[0]![1],
);
expect(decoded.body?.settings).toMatchObject({
addType: 5, groupQuestion: 'q', groupAnswer: '',
});
});
});
@@ -41,12 +41,25 @@ describe('SetAddRequest namespace', () => {
expect(env.body?.accept).toBe(2);
});
it('defaults reason to empty string', async () => {
it('writes a space when the reason is empty so field 4 stays present', async () => {
const deps = makeDeps();
await SetAddRequest.invoke(deps, { groupId: 1, sequence: 1, eventType: 0, approve: true });
await SetAddRequest.invoke(deps, { groupId: 1, sequence: 1, eventType: 1, approve: true });
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes);
// proto3 empty string omitted on the wire.
expect(env.body?.body?.message ?? '').toBe('');
expect(env.body?.body?.message).toBe(' ');
const arr = Array.from(bytes);
const hasMessageField = arr.some((_, i) => arr[i] === 0x22 && arr[i + 1] === 0x01 && arr[i + 2] === 0x20);
expect(hasMessageField).toBe(true);
});
it('forwards operateTransInfo as body field 7', async () => {
const deps = makeDeps();
const operateTransInfo = Uint8Array.from([0x01, 0x02, 0x03]);
await SetAddRequest.invoke(deps, {
groupId: 1, sequence: 1, eventType: 1, approve: true, reason: 'ok', operateTransInfo,
});
const [, bytes] = deps.sendRawPacket.mock.calls[0]!;
const env = protobuf_decode<OidbBase<OidbGroupRequestAction>>(bytes);
expect(env.body?.body?.operateTransInfo).toEqual(operateTransInfo);
});
});
@@ -6,6 +6,7 @@ import type { Oidb0x89a_0InvitePolicy } from '@snowluma/proto-defs/oidb-actions/
import {
MEMBER_INVITE_PRIVILEGE_MASK,
decodeMemberInvitePolicy,
mergeMemberInvitePrivilegeFlag,
SetMemberInvitePolicy,
type GroupMemberInvitePolicy,
@@ -55,6 +56,27 @@ describe('SetMemberInvitePolicy namespace', () => {
.toBe(0xE1000001);
});
it.each<[number, GroupMemberInvitePolicy]>([
[0x04000000, 'disabled'],
[0, 'require_approval'],
[0x00100000, 'no_approval'],
[0x02000000, 'no_approval_under_100'],
[0x80100001, 'no_approval'],
[0x84000001, 'disabled'],
])('decodes privilege %# as %s', (privilegeFlag, policy) => {
expect(decodeMemberInvitePolicy(privilegeFlag)).toBe(policy);
});
it('round-trips each invite policy through merge then decode', () => {
const policies: GroupMemberInvitePolicy[] = [
'disabled', 'require_approval', 'no_approval', 'no_approval_under_100',
];
for (const policy of policies) {
expect(decodeMemberInvitePolicy(mergeMemberInvitePrivilegeFlag(0x80000001, policy)))
.toBe(policy);
}
});
it('keeps explicit zero fields on the wire', async () => {
const sender = makeSender();
await SetMemberInvitePolicy.invoke(sender, {
@@ -5,6 +5,7 @@ import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0MemberPermission } from '@snowluma/proto-defs/oidb-actions/base';
import {
decodeGroupMemberPermissions,
GROUP_MEMBER_PERMISSION_MASKS,
mergeGroupMemberPermission,
SetMemberPermission,
@@ -74,6 +75,36 @@ describe('SetMemberPermission namespace', () => {
.toBe(0xF0008000);
});
it('treats permission bits as deny flags when decoding', () => {
expect(decodeGroupMemberPermissions(0)).toEqual({
allowMemberUploadAlbum: true,
allowMemberTemporarySession: true,
allowMemberCreateGroup: true,
});
expect(decodeGroupMemberPermissions(0x80018001)).toEqual({
allowMemberUploadAlbum: false,
allowMemberTemporarySession: false,
allowMemberCreateGroup: false,
});
expect(decodeGroupMemberPermissions(0x80000000)).toEqual({
allowMemberUploadAlbum: true,
allowMemberTemporarySession: true,
allowMemberCreateGroup: true,
});
});
it('round-trips each permission through merge then decode', () => {
let flag = 0x80000000;
flag = mergeGroupMemberPermission(flag, 'upload_album', false);
flag = mergeGroupMemberPermission(flag, 'temporary_session', true);
flag = mergeGroupMemberPermission(flag, 'create_group', false);
expect(decodeGroupMemberPermissions(flag)).toEqual({
allowMemberUploadAlbum: false,
allowMemberTemporarySession: true,
allowMemberCreateGroup: false,
});
});
it('keeps explicit zero fields on the wire', async () => {
const sender = makeSender();
await SetMemberPermission.invoke(sender, {
@@ -5,6 +5,7 @@ import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0HistoryVisibility } from '@snowluma/proto-defs/oidb-actions/base';
import {
decodeGroupHistoryVisibility,
GROUP_HISTORY_VISIBILITY_MASK,
mergeGroupHistoryVisibility,
SetNewMemberHistoryVisibility,
@@ -23,14 +24,13 @@ function makeSender() {
describe('SetNewMemberHistoryVisibility namespace', () => {
it.each([
[true, 0x80000001, 0x80000005],
[false, 0x80000005, 0x80000001],
])('writes visible=%s without changing unrelated bits', async (visible, current, expected) => {
[true, GROUP_HISTORY_VISIBILITY_MASK],
[false, 0],
])('writes visible=%s as the mutation bit only', async (visible, expected) => {
const sender = makeSender();
await SetNewMemberHistoryVisibility.invoke(sender, {
groupId: 12345,
currentGroupFlagExt4: current,
visible,
});
@@ -52,11 +52,28 @@ describe('SetNewMemberHistoryVisibility namespace', () => {
expect(mergeGroupHistoryVisibility(0xF0000005, false)).toBe(0xF0000001);
});
it('decodes the history-visibility switch from a 0/1 reply or the mutation bit', () => {
expect(decodeGroupHistoryVisibility(0)).toBe(false);
expect(decodeGroupHistoryVisibility(1)).toBe(true);
expect(decodeGroupHistoryVisibility(GROUP_HISTORY_VISIBILITY_MASK)).toBe(true);
expect(decodeGroupHistoryVisibility(0x80000001)).toBe(false);
expect(decodeGroupHistoryVisibility(0x80000005)).toBe(true);
});
it('round-trips history visibility through merge then decode', () => {
expect(decodeGroupHistoryVisibility(mergeGroupHistoryVisibility(0x80000001, true))).toBe(true);
expect(decodeGroupHistoryVisibility(mergeGroupHistoryVisibility(0x80000005, false))).toBe(false);
});
it('does not treat a 0/1 detail reply as a missing mutation bit (#387)', () => {
expect(decodeGroupHistoryVisibility(1)).toBe(true);
expect(decodeGroupHistoryVisibility(mergeGroupHistoryVisibility(0, true))).toBe(true);
});
it('keeps an explicit zero value on the wire', async () => {
const sender = makeSender();
await SetNewMemberHistoryVisibility.invoke(sender, {
groupId: 1,
currentGroupFlagExt4: GROUP_HISTORY_VISIBILITY_MASK,
visible: false,
});
@@ -67,13 +84,7 @@ describe('SetNewMemberHistoryVisibility namespace', () => {
expect(envelope.body?.settings?.groupFlagExt4Mask).toBe(GROUP_HISTORY_VISIBILITY_MASK);
});
it('rejects an invalid current flag before sending', async () => {
const sender = makeSender();
await expect(SetNewMemberHistoryVisibility.invoke(sender, {
groupId: 1,
currentGroupFlagExt4: -1,
visible: true,
})).rejects.toThrow(/unsigned 32-bit/);
expect(sender.sendRawPacket).not.toHaveBeenCalled();
it('rejects an invalid current flag when merging', () => {
expect(() => mergeGroupHistoryVisibility(-1, true)).toThrow(/unsigned 32-bit/);
});
});
@@ -0,0 +1,215 @@
import { getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import type { PacketInfo } from '@snowluma/common/protocol-types';
import { BridgeEventBus } from '@snowluma/protocol/event-bus';
import type { QQEventVariant } from '@snowluma/protocol/events';
import { IdentityService } from '@snowluma/protocol/identity-service';
import { IncomingPacketPipeline } from '@snowluma/protocol/packet-pipeline';
import type { GroupMemberInfo, QQGroupInfo, UserProfileInfo } from '@snowluma/protocol/qq-info';
import { afterEach, describe, expect, it, vi } from 'vitest';
const SELF_UIN = 10001;
const GROUP_ID = 123456789;
const previousLogLevel = getLogLevel();
afterEach(() => {
setLogLevel(previousLogLevel);
});
function makeProfile(uin: number, uid = ''): UserProfileInfo {
return { uin, uid, nickname: '', remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '', level: 0 };
}
function makeMember(uin: number, uid: string): GroupMemberInfo {
return {
uin, uid, nickname: '', card: '', isRobot: false, role: 'member',
level: 0, title: '', joinTime: 0, lastSentTime: 0, shutUpTime: 0,
};
}
function makeGroup(): QQGroupInfo {
return {
groupId: GROUP_ID, groupName: 'g', remark: '', memberCount: 1, memberMax: 500,
members: new Map([[22222, makeMember(22222, 'u_member')]]),
};
}
function pkt(): PacketInfo {
return {
pid: 1, uin: String(SELF_UIN), serviceCmd: 'test.roster', seqId: 1,
retCode: 0, fromClient: false, body: new Uint8Array(),
};
}
function join(over: Partial<Extract<QQEventVariant, { kind: 'group_member_join' }>> = {}): QQEventVariant {
return {
kind: 'group_member_join', time: 1, selfUin: SELF_UIN, groupId: GROUP_ID,
userUin: 22222, operatorUin: 0, userUid: 'u_member', operatorUid: 'u_op',
...over,
};
}
function leave(): QQEventVariant {
return {
kind: 'group_member_leave', time: 1, selfUin: SELF_UIN, groupId: GROUP_ID,
userUin: 22222, operatorUin: 0, userUid: 'u_member', operatorUid: 'u_op',
leaveType: 'leave',
};
}
function admin(): QQEventVariant {
return {
kind: 'group_admin', time: 1, selfUin: SELF_UIN, groupId: GROUP_ID,
userUin: 22222, set: true,
};
}
function makePipeline(opts: {
plantGroup?: boolean;
plantGroupOnListFetch?: boolean;
fetchGroupList?: () => Promise<void>;
fetchGroupMemberList?: (groupId: number) => Promise<void>;
fetchProfileByUid?: () => Promise<UserProfileInfo>;
} = {}) {
const identity = IdentityService.memory(String(SELF_UIN));
if (opts.plantGroup) identity.rememberGroups([makeGroup()]);
if (opts.fetchProfileByUid) {
identity.setFetcher({
fetchProfile: async () => makeProfile(0),
fetchProfileByUid: opts.fetchProfileByUid,
});
}
const fetchGroupList = opts.fetchGroupList ?? vi.fn(async () => {
if (opts.plantGroupOnListFetch) identity.rememberGroups([makeGroup()]);
});
const fetchGroupMemberList = opts.fetchGroupMemberList ?? vi.fn(async () => {});
const events = new BridgeEventBus();
const captured: QQEventVariant[] = [];
events.onAny((event) => { captured.push(event as QQEventVariant); });
const pipeline = new IncomingPacketPipeline({
identity,
events,
fetchGroupList,
fetchGroupMemberList,
resolveGroupJoinRequest: vi.fn(async () => null),
});
return { identity, pipeline, captured, fetchGroupList, fetchGroupMemberList };
}
async function afterSideEffect(): Promise<void> {
await Promise.resolve();
await Promise.resolve();
await Promise.resolve();
}
describe('IncomingPacketPipeline roster refresh', () => {
it('unknown-group join fetches the group list and skips members when still unknown', async () => {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline();
pipeline.registerCmd('test.roster', () => [join()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
});
it('swallows fetchGroupList failure and still skips members when the group is unknown', async () => {
const fetchGroupList = vi.fn(async () => {
throw new Error('list down');
});
const { pipeline, captured, fetchGroupMemberList } = makePipeline({ fetchGroupList });
pipeline.registerCmd('test.roster', () => [join()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
expect(captured).toHaveLength(1);
});
it('fetches members after an unknown-group join if the list fetch plants the group', async () => {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({
plantGroupOnListFetch: true,
});
pipeline.registerCmd('test.roster', () => [join()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
});
it('known-group join / leave / admin fetch only the member list', async () => {
for (const event of [join(), leave(), admin()]) {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({ plantGroup: true });
pipeline.registerCmd('test.roster', () => [event]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).not.toHaveBeenCalled();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
}
});
it('self-join of a known group fetches both the group list and the member list', async () => {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline({ plantGroup: true });
pipeline.registerCmd('test.roster', () => [join({ userUin: SELF_UIN, userUid: 'u_self' })]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
});
it('unknown-group leave / admin do not fetch the group list or members', async () => {
for (const event of [leave(), admin()]) {
const { pipeline, fetchGroupList, fetchGroupMemberList } = makePipeline();
pipeline.registerCmd('test.roster', () => [event]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupList).not.toHaveBeenCalled();
expect(fetchGroupMemberList).not.toHaveBeenCalled();
}
});
it('warns when the member list fails and still emits the event', async () => {
const entries: LogEntry[] = [];
setLogLevel('warn');
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, captured } = makePipeline({
plantGroup: true,
fetchGroupMemberList: vi.fn(async () => {
throw new Error('net down');
}),
});
pipeline.registerCmd('test.roster', () => [leave()]);
await pipeline.process(pkt());
expect(captured).toHaveLength(1);
await afterSideEffect();
expect(entries.some((entry) => (
entry.level === 'warn' && String(entry.message).includes('failed to refresh member cache')
))).toBe(true);
} finally {
unsubscribe();
}
});
it('resolves an unresolved join UIN through Identity, not the roster ports', async () => {
const fetchProfileByUid = vi.fn(async () => makeProfile(22222, 'u_new'));
const { pipeline, captured, fetchGroupList, fetchGroupMemberList } = makePipeline({
plantGroup: true,
fetchProfileByUid,
});
pipeline.registerCmd('test.roster', () => [join({ userUin: 0, userUid: 'u_new' })]);
await pipeline.process(pkt());
expect(captured).toHaveLength(1);
expect((captured[0] as Extract<QQEventVariant, { kind: 'group_member_join' }>).userUin).toBe(22222);
expect(fetchProfileByUid).toHaveBeenCalledWith('u_new');
await afterSideEffect();
expect(fetchGroupList).not.toHaveBeenCalled();
expect(fetchGroupMemberList).toHaveBeenCalledWith(GROUP_ID);
});
it('coalesces concurrent refreshes for the same group', async () => {
const { pipeline, fetchGroupMemberList } = makePipeline({ plantGroup: true });
pipeline.registerCmd('test.roster', () => [leave(), admin()]);
await pipeline.process(pkt());
await afterSideEffect();
expect(fetchGroupMemberList).toHaveBeenCalledOnce();
});
});
@@ -37,7 +37,8 @@ function makePipeline(opts: {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest,
resolveGroupInviteCardSequence,
});
@@ -387,7 +388,8 @@ describe('IncomingPacketPipeline / #1 group card self-heal', () => {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
return { identity, pipeline };
@@ -452,7 +454,8 @@ describe('IncomingPacketPipeline / group_card_change from message traffic', () =
const events = new BridgeEventBus();
const pipeline = new IncomingPacketPipeline({
identity, events,
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
const captured: QQEventVariant[] = [];
@@ -519,7 +522,8 @@ describe('IncomingPacketPipeline / invite-card pending application', () => {
const pipeline = new IncomingPacketPipeline({
identity: IdentityService.memory('10001'),
events: new BridgeEventBus(),
refreshMemberCache: vi.fn(async () => false),
fetchGroupList: vi.fn(async () => {}),
fetchGroupMemberList: vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
rememberGroupInviteCardSequence,
});
@@ -74,7 +74,8 @@ function msgPushContext(
}
function makePipeline(opts: {
refreshMemberCache?: () => Promise<boolean>;
fetchGroupList?: () => Promise<void>;
fetchGroupMemberList?: (groupId: number) => Promise<void>;
fetchProfileByUid?: () => Promise<{ uin: number; uid: string; nickname: string; remark: string; qid: string; sex: string; age: number; sign: string; avatar: string; level: number }>;
} = {}) {
const identity = IdentityService.memory('10001');
@@ -91,7 +92,8 @@ function makePipeline(opts: {
const pipeline = new IncomingPacketPipeline({
identity,
events,
refreshMemberCache: opts.refreshMemberCache ?? vi.fn(async () => false),
fetchGroupList: opts.fetchGroupList ?? vi.fn(async () => {}),
fetchGroupMemberList: opts.fetchGroupMemberList ?? vi.fn(async () => {}),
resolveGroupJoinRequest: vi.fn(async () => null),
});
const dispatched: Array<{ event: QQEventVariant; req: number | undefined }> = [];
@@ -214,7 +216,7 @@ describe('IncomingPacketPipeline TRACE lifecycle', () => {
const unsubscribe = subscribeLogs((entry) => entries.push(entry));
try {
const { pipeline, dispatched } = makePipeline({
refreshMemberCache: vi.fn(async () => {
fetchGroupList: vi.fn(async () => {
throw new Error('fixture refresh failed');
}),
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.14.10",
"version": "1.14.11",
"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.",
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.14.10",
"version": "1.14.11",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.14.10",
"version": "1.14.11",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+2
View File
@@ -86,6 +86,7 @@ import type {
ForwardMessageResult,
FriendCategoryResult,
FriendMessageHistory,
GroupAdminSettings,
GroupAtAllRemainInfo,
GroupFileSystemInfo,
GroupFileUrl,
@@ -139,6 +140,7 @@ export interface SnowLumaActionMap {
set_group_whole_ban: { params: SetGroupWholeBanParams; data: EmptyData };
set_group_add_option: { params: SetGroupAddOptionParams; data: EmptyData };
set_group_search: { params: GroupIdParams; data: EmptyData };
get_group_admin_settings: { params: GroupIdParams; data: GroupAdminSettings };
set_group_admin: { params: SetGroupAdminParams; data: EmptyData };
set_group_card: { params: SetGroupCardParams; data: EmptyData };
set_group_name: { params: SetGroupNameParams; data: EmptyData };
+2
View File
@@ -88,6 +88,8 @@ export interface SetGroupWholeBanParams extends GroupIdParams {
export interface SetGroupAddOptionParams extends GroupIdParams {
add_type: number;
group_question?: string;
group_answer?: string;
}
export interface SetGroupAdminParams extends GroupIdParams {
+15
View File
@@ -217,6 +217,21 @@ export interface GroupAtAllRemainInfo {
remain_at_all_count_for_uin: number;
}
export type GroupAdminSettings = {
add_type: number;
group_question: string;
group_answer: string;
robot_member_switch: number;
robot_member_examine: number;
member_invite_policy: 'disabled' | 'require_approval' | 'no_approval' | 'no_approval_under_100';
allow_member_upload_album: boolean;
allow_member_temporary_session: boolean;
allow_member_create_group: boolean;
new_member_history_visible: boolean;
no_finger_open: number;
no_code_finger_open: number;
};
export interface GroupTodoListItem {
message_id: number;
message_seq: number;
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.14.10",
"version": "1.14.11",
"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.14.10",
"version": "1.14.11",
"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.14.10",
"version": "1.14.11",
"type": "module",
"scripts": {
"dev": "vite",