Merge pull request #198 from SnowLuma/dev

chore: promote dev → main (6cb7f2c)
This commit is contained in:
snowluma-bot[bot] authored and GitHub committed 2026-07-04 05:39:20 +00:00
commit 5f01c6ab5f
54 files changed
+1718 -360

No files matched your search

+6 -2
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "snowluma-monorepo",
"version": "1.11.1",
"version": "1.11.2",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",
@@ -47,7 +47,11 @@
},
"onlyBuiltDependencies": [
"better-sqlite3"
]
],
"overrides": {
"esbuild@<0.28.1": "^0.28.1",
"@babel/core@<7.29.6": "^7.29.6"
}
},
"packageManager": "pnpm@10.28.0",
"engines": {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/bridge",
"version": "1.11.1",
"version": "1.11.2",
"private": true,
"type": "module",
"description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/common",
"version": "1.11.1",
"version": "1.11.2",
"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.11.1",
"version": "1.11.2",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",
@@ -115,6 +115,10 @@ export class ContactsApi {
memberCount: raw.info?.memberCount ?? 0,
memberMax: raw.info?.memberMax ?? 0,
members: new Map(),
// #197: the list already carries these — no extra fetch needed. `level`
// is not in the list (0x88D_0 detail only), so it stays undefined here.
createTime: raw.info?.createdTime ?? 0,
memo: raw.info?.announcement || raw.info?.description || '',
});
}
this.ctx.identity.rememberGroups(groups);
@@ -140,6 +144,11 @@ export class ContactsApi {
memberCount: Number(r.memberCount ?? 0n),
memberMax: Number(r.maxMemberCount ?? 0n),
members: new Map(),
// #197: the detail is the only source of `level`; it also carries
// createTime + the notice preview (memo).
createTime: Number(r.createTime ?? 0n),
level: Number(r.level ?? 0n),
memo: r.noticePreview ?? '',
};
}
+2 -2
View File
@@ -35,8 +35,8 @@ export class GroupAdminApi {
return SetAddOption.invoke(this.ctx, { groupId, addType });
}
setSearch(groupId: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId });
setSearch(groupId: number, noFingerOpen?: number, noCodeFingerOpen?: number): Promise<void> {
return SetSearch.invoke(this.ctx, { groupId, noFingerOpen, noCodeFingerOpen });
}
setAddRequest(
+6 -1
View File
@@ -12,6 +12,7 @@ import { CreateGroupFolder } from '@snowluma/protocol/oidb-services/group-file/c
import { DeleteGroupFile } from '@snowluma/protocol/oidb-services/group-file/delete-group-file';
import { DeleteGroupFolder } from '@snowluma/protocol/oidb-services/group-file/delete-group-folder';
import { GetGroupFileCount } from '@snowluma/protocol/oidb-services/group-file/get-group-file-count';
import { GetGroupFileSpace } from '@snowluma/protocol/oidb-services/group-file/get-group-file-space';
import { GetGroupFileUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-file-url';
import { GetGroupPttUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-ptt-url';
import { GetGroupVideoUrl } from '@snowluma/protocol/oidb-services/group-file/get-group-video-url';
@@ -250,6 +251,10 @@ export class GroupFileApi {
return GetGroupFileCount.invoke(this.ctx, { groupId });
}
getSpace(groupId: number): Promise<{ usedSpace: number; totalSpace: number }> {
return GetGroupFileSpace.invoke(this.ctx, { groupId });
}
// ─────────────── upload (3-stage: OIDB preflight → highway → publish) ───────────────
async upload(
@@ -623,7 +628,7 @@ export class GroupFileApi {
// ─────────────── folders ───────────────
createFolder(groupId: number, name: string, parentId = '/'): Promise<void> {
createFolder(groupId: number, name: string, parentId = '/'): Promise<CreateGroupFolder.Result> {
return CreateGroupFolder.invoke(this.ctx, {
groupId, parentId: normalizeDirectory(parentId), folderName: name,
});
+11
View File
@@ -5,11 +5,13 @@ import {
getQzoneMsgList,
publishQzoneMsg,
setQzoneLike,
updateQzoneMsgRight,
uploadQzoneImageFromSource,
type QzoneCommentResult,
type QzoneFeedsResult,
type QzoneMsgListResult,
type QzonePublishResult,
type QzoneUpdateRightResult,
type QzoneUploadImageResult,
} from '@snowluma/protocol/web/qzone';
import type { BridgeContext } from '../bridge-context';
@@ -74,6 +76,15 @@ export class QzoneApi {
await deleteQzoneMsg(cookieObject, this.ctx.identity.uin, tid);
}
/**
* 修改机器人自己空间一条已发说说的查看权限(按 tid)。
* `ugcRight` / `targetUins` 含义同 publish(16/128 时 targetUins 必填)。
*/
async updateRight(tid: string, ugcRight: number, targetUins?: string): Promise<QzoneUpdateRightResult> {
const cookieObject = await this.ctx.apis.web.getCookies('qzone.qq.com');
return updateQzoneMsgRight(cookieObject, this.ctx.identity.uin, tid, ugcRight, targetUins);
}
/**
* 给一条说说点赞/取消赞。`targetUin` 省略时点赞机器人自己空间的说说;
* 点赞好友说说时传好友 uin(tid 来自 get_qzone_feeds / get_qzone_msg_list)。
+10
View File
@@ -117,6 +117,16 @@ describe('apis/qzone', () => {
expect(delSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9');
});
it('updateRight changes a feed\'s visibility on the bot\'s own space', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
const updSpy = vi.spyOn(qzoneWeb, 'updateQzoneMsgRight').mockResolvedValue({ ugc_right: 16 });
const out = await new QzoneApi(bridge as never).updateRight('TID9', 16, '10002|10003');
expect(getCookies).toHaveBeenCalledWith('qzone.qq.com');
expect(updSpy).toHaveBeenCalledWith({ p_skey: 'PSK' }, '10001', 'TID9', 16, '10002|10003');
expect(out).toEqual({ ugc_right: 16 });
});
it('like defaults the feed owner to self and passes opUin=self + like flag', async () => {
const getCookies = vi.fn(async () => ({ p_skey: 'PSK' }));
const bridge = mockBridge({ apis: { ...mockApiHub(), web: { getCookies } } as never });
@@ -3,7 +3,7 @@
// so this exercises the loop/cursor logic, not the wire decode (covered in
// packages/protocol/tests/msg-push/fetch-group-history.test.ts).
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('@snowluma/protocol/msg-push', async (importOriginal) => {
const actual = await importOriginal<typeof import('@snowluma/protocol/msg-push')>();
@@ -27,7 +27,22 @@ function gm(seq: number): any {
const ctx = { identity: {}, sendRawPacket: vi.fn() } as any;
describe('MessageApi.getGroupHistory walk-back', () => {
beforeEach(() => mockFetch.mockReset());
// The walk-back loop enforces a real ~300ms gap between each SsoGetGroupMsg
// send (a deliberate anti-flood throttle, unchanged in production). Fake the
// clock so the test exercises the loop/cursor logic instantly instead of
// waiting out 300ms × up-to-12 real sends.
beforeEach(() => {
mockFetch.mockReset();
vi.useFakeTimers();
});
afterEach(() => vi.useRealTimers());
// Drives a throttled getGroupHistory to completion under fake timers: kick it
// off, flush the queued send-gap timers, then await the result.
async function runHistory<T>(promise: Promise<T>): Promise<T> {
await vi.runAllTimersAsync();
return promise;
}
it('walks back across short-capped windows, dedups, returns newest `want` ascending', async () => {
// Server caps every window to its newest 10 sequences → forces walk-back.
@@ -37,7 +52,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
return out;
});
const res = await new MessageApi(ctx).getGroupHistory(9999, 200, 50);
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 200, 50));
expect(res).toHaveLength(50);
expect(res[0].msgSeq).toBe(151); // newest 50 ending at 200 → 151..200
@@ -54,7 +69,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
return out;
});
const res = await new MessageApi(ctx).getGroupHistory(9999, 20, 100); // only seq 1..20 exist
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 20, 100)); // only seq 1..20 exist
expect(res.map((m) => m.msgSeq)).toEqual(Array.from({ length: 20 }, (_, i) => i + 1));
});
@@ -65,7 +80,7 @@ describe('MessageApi.getGroupHistory walk-back', () => {
return [gm(end)]; // one message per window → never reaches a large `want`
});
const res = await new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999);
const res = await runHistory(new MessageApi(ctx).getGroupHistory(9999, 100_000, 9999));
expect(calls).toBeLessThanOrEqual(12); // HISTORY_MAX_REQUESTS
expect(res.length).toBeLessThanOrEqual(200); // HISTORY_MAX_COUNT
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/mcp",
"version": "1.11.1",
"version": "1.11.2",
"description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.",
"repository": {
"type": "git",
+176 -6
View File
@@ -837,6 +837,7 @@
"name": "create_group_file_folder",
"aliases": [],
"summary": "创建群文件夹",
"returns": "{ result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName, folderPath, createTime, modifyTime, createUin, modifyUin } } }",
"readOnly": false,
"params": [
{
@@ -3275,7 +3276,7 @@
"name": "get_group_file_system_info",
"aliases": [],
"summary": "获取群文件系统信息",
"returns": "{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(used_space 恒 0,total_space 为固定 10GiB 常量)。",
"returns": "{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(均为服务端实际值)。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -3285,15 +3286,15 @@
},
"limit_count": {
"type": "integer",
"description": "最大文件数"
"description": "文件数上限"
},
"used_space": {
"type": "integer",
"description": "已用空间(占位,恒 0)"
"description": "已用空间(字节)"
},
"total_space": {
"type": "integer",
"description": "总空间(占位,恒 10GiB)"
"description": "总空间(字节)"
}
},
"required": [
@@ -3785,6 +3786,18 @@
"max_member_count": {
"type": "integer",
"description": "成员上限"
},
"group_create_time": {
"type": "integer",
"description": "建群时间戳(秒)"
},
"group_level": {
"type": "integer",
"description": "群等级"
},
"group_memo": {
"type": "string",
"description": "群简介 / 公告预览"
}
},
"required": [
@@ -3898,6 +3911,18 @@
"max_member_count": {
"type": "integer",
"description": "成员上限"
},
"group_create_time": {
"type": "integer",
"description": "建群时间戳(秒)"
},
"group_level": {
"type": "integer",
"description": "群等级(列表批量场景恒 0,详见 get_group_info)"
},
"group_memo": {
"type": "string",
"description": "群简介 / 公告预览"
}
},
"required": [
@@ -3994,6 +4019,22 @@
"title": {
"type": "string",
"description": "专属头衔"
},
"area": {
"type": "string",
"description": "地区(QQ NT 不提供,恒空)"
},
"unfriendly": {
"type": "boolean",
"description": "是否不良记录(QQ NT 不提供,恒 false)"
},
"title_expire_time": {
"type": "integer",
"description": "头衔过期时间戳(QQ NT 不提供,恒 0)"
},
"card_changeable": {
"type": "boolean",
"description": "是否可改名片(占位,恒 true)"
}
},
"required": [
@@ -4129,6 +4170,22 @@
"title": {
"type": "string",
"description": "专属头衔"
},
"area": {
"type": "string",
"description": "地区(QQ NT 不提供,恒空)"
},
"unfriendly": {
"type": "boolean",
"description": "是否不良记录(QQ NT 不提供,恒 false)"
},
"title_expire_time": {
"type": "integer",
"description": "头衔过期时间戳(QQ NT 不提供,恒 0)"
},
"card_changeable": {
"type": "boolean",
"description": "是否可改名片(占位,恒 true)"
}
},
"required": [
@@ -8410,7 +8467,7 @@
{
"name": "set_group_search",
"aliases": [],
"summary": "允许群被搜索",
"summary": "设置群被搜索方式(群指纹 / 群号搜索开关)",
"readOnly": false,
"params": [
{
@@ -8423,6 +8480,24 @@
"minimum": 1
},
"desc": "群号"
},
{
"name": "no_finger_open",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "no_code_finger_open",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
}
],
"invariants": [],
@@ -8434,6 +8509,14 @@
"minimum": 1,
"description": "群号",
"x-role": "group_id"
},
"no_finger_open": {
"type": "integer",
"minimum": 0
},
"no_code_finger_open": {
"type": "integer",
"minimum": 0
}
},
"required": [
@@ -8903,6 +8986,93 @@
},
"category": "扩展"
},
{
"name": "set_qzone_msg_right",
"aliases": [],
"summary": "修改一条已发说说的查看权限(QQ 空间,按 tid)",
"returns": "更新后的权限对象。",
"returnsSchema": {
"type": "object",
"properties": {
"ugc_right": {
"type": "integer",
"description": "更新后的查看权限"
}
},
"required": [
"ugc_right"
]
},
"readOnly": false,
"params": [
{
"name": "tid",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
},
"desc": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)"
},
{
"name": "ugc_right",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见"
},
{
"name": "target_uins",
"type": "uint[]",
"required": false,
"schema": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
}
},
"desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
],
"invariants": [
"ugc_right must be one of 1, 4, 16, 64, 128",
"target_uins is required when ugc_right is 16 or 128"
],
"inputSchema": {
"type": "object",
"properties": {
"tid": {
"type": "string",
"minLength": 1,
"description": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)"
},
"ugc_right": {
"type": "integer",
"minimum": 1,
"description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见"
},
"target_uins": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
},
"required": [
"tid",
"ugc_right"
],
"additionalProperties": true
},
"category": "空间"
},
{
"name": "set_restart",
"aliases": [],
@@ -9834,7 +10004,7 @@
},
{
"category": "空间",
"count": 7
"count": 8
},
{
"category": "流式接口",
+176 -6
View File
@@ -840,6 +840,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "create_group_file_folder",
"aliases": [],
"summary": "创建群文件夹",
"returns": "{ result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName, folderPath, createTime, modifyTime, createUin, modifyUin } } }",
"readOnly": false,
"params": [
{
@@ -3278,7 +3279,7 @@ export const ACTIONS: CatalogAction[] = [
"name": "get_group_file_system_info",
"aliases": [],
"summary": "获取群文件系统信息",
"returns": "{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(used_space 恒 0,total_space 为固定 10GiB 常量)。",
"returns": "{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(均为服务端实际值)。",
"returnsSchema": {
"type": "object",
"properties": {
@@ -3288,15 +3289,15 @@ export const ACTIONS: CatalogAction[] = [
},
"limit_count": {
"type": "integer",
"description": "最大文件数"
"description": "文件数上限"
},
"used_space": {
"type": "integer",
"description": "已用空间(占位,恒 0)"
"description": "已用空间(字节)"
},
"total_space": {
"type": "integer",
"description": "总空间(占位,恒 10GiB)"
"description": "总空间(字节)"
}
},
"required": [
@@ -3788,6 +3789,18 @@ export const ACTIONS: CatalogAction[] = [
"max_member_count": {
"type": "integer",
"description": "成员上限"
},
"group_create_time": {
"type": "integer",
"description": "建群时间戳(秒)"
},
"group_level": {
"type": "integer",
"description": "群等级"
},
"group_memo": {
"type": "string",
"description": "群简介 / 公告预览"
}
},
"required": [
@@ -3901,6 +3914,18 @@ export const ACTIONS: CatalogAction[] = [
"max_member_count": {
"type": "integer",
"description": "成员上限"
},
"group_create_time": {
"type": "integer",
"description": "建群时间戳(秒)"
},
"group_level": {
"type": "integer",
"description": "群等级(列表批量场景恒 0,详见 get_group_info)"
},
"group_memo": {
"type": "string",
"description": "群简介 / 公告预览"
}
},
"required": [
@@ -3997,6 +4022,22 @@ export const ACTIONS: CatalogAction[] = [
"title": {
"type": "string",
"description": "专属头衔"
},
"area": {
"type": "string",
"description": "地区(QQ NT 不提供,恒空)"
},
"unfriendly": {
"type": "boolean",
"description": "是否不良记录(QQ NT 不提供,恒 false)"
},
"title_expire_time": {
"type": "integer",
"description": "头衔过期时间戳(QQ NT 不提供,恒 0)"
},
"card_changeable": {
"type": "boolean",
"description": "是否可改名片(占位,恒 true)"
}
},
"required": [
@@ -4132,6 +4173,22 @@ export const ACTIONS: CatalogAction[] = [
"title": {
"type": "string",
"description": "专属头衔"
},
"area": {
"type": "string",
"description": "地区(QQ NT 不提供,恒空)"
},
"unfriendly": {
"type": "boolean",
"description": "是否不良记录(QQ NT 不提供,恒 false)"
},
"title_expire_time": {
"type": "integer",
"description": "头衔过期时间戳(QQ NT 不提供,恒 0)"
},
"card_changeable": {
"type": "boolean",
"description": "是否可改名片(占位,恒 true)"
}
},
"required": [
@@ -8413,7 +8470,7 @@ export const ACTIONS: CatalogAction[] = [
{
"name": "set_group_search",
"aliases": [],
"summary": "允许群被搜索",
"summary": "设置群被搜索方式(群指纹 / 群号搜索开关)",
"readOnly": false,
"params": [
{
@@ -8426,6 +8483,24 @@ export const ACTIONS: CatalogAction[] = [
"minimum": 1
},
"desc": "群号"
},
{
"name": "no_finger_open",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
},
{
"name": "no_code_finger_open",
"type": "int",
"required": false,
"schema": {
"type": "integer",
"minimum": 0
}
}
],
"invariants": [],
@@ -8437,6 +8512,14 @@ export const ACTIONS: CatalogAction[] = [
"minimum": 1,
"description": "群号",
"x-role": "group_id"
},
"no_finger_open": {
"type": "integer",
"minimum": 0
},
"no_code_finger_open": {
"type": "integer",
"minimum": 0
}
},
"required": [
@@ -8906,6 +8989,93 @@ export const ACTIONS: CatalogAction[] = [
},
"category": "扩展"
},
{
"name": "set_qzone_msg_right",
"aliases": [],
"summary": "修改一条已发说说的查看权限(QQ 空间,按 tid)",
"returns": "更新后的权限对象。",
"returnsSchema": {
"type": "object",
"properties": {
"ugc_right": {
"type": "integer",
"description": "更新后的查看权限"
}
},
"required": [
"ugc_right"
]
},
"readOnly": false,
"params": [
{
"name": "tid",
"type": "string",
"required": true,
"schema": {
"type": "string",
"minLength": 1
},
"desc": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)"
},
{
"name": "ugc_right",
"type": "int",
"required": true,
"schema": {
"type": "integer",
"minimum": 1
},
"desc": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见"
},
{
"name": "target_uins",
"type": "uint[]",
"required": false,
"schema": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
}
},
"desc": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
],
"invariants": [
"ugc_right must be one of 1, 4, 16, 64, 128",
"target_uins is required when ugc_right is 16 or 128"
],
"inputSchema": {
"type": "object",
"properties": {
"tid": {
"type": "string",
"minLength": 1,
"description": "说说 tid(来自 get_qzone_msg_list / send_qzone_msg)"
},
"ugc_right": {
"type": "integer",
"minimum": 1,
"description": "查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见"
},
"target_uins": {
"type": "array",
"items": {
"type": "integer",
"minimum": 1
},
"description": "权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单"
}
},
"required": [
"tid",
"ugc_right"
],
"additionalProperties": true
},
"category": "空间"
},
{
"name": "set_restart",
"aliases": [],
@@ -9838,7 +10008,7 @@ export const CATEGORIES: CatalogCategory[] = [
},
{
"category": "空间",
"count": 7
"count": 8
},
{
"category": "流式接口",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/onebot",
"version": "1.11.1",
"version": "1.11.2",
"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>'`.",
+13 -9
View File
@@ -706,24 +706,28 @@ export const actions = [
name: 'get_group_file_system_info',
summary: '获取群文件系统信息',
readOnly: true,
returns: '{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(used_space 恒 0,total_space 为固定 10GiB 常量)。',
returns: '{ file_count, limit_count, used_space, total_space }:群文件数量与容量信息(均为服务端实际值)。',
returnsSchema: {
type: 'object',
properties: {
file_count: { type: 'integer', description: '当前文件数' },
limit_count: { type: 'integer', description: '最大文件数' },
used_space: { type: 'integer', description: '已用空间(占位,恒 0)' },
total_space: { type: 'integer', description: '总空间(占位,恒 10GiB)' },
limit_count: { type: 'integer', description: '文件数上限' },
used_space: { type: 'integer', description: '已用空间(字节)' },
total_space: { type: 'integer', description: '总空间(字节)' },
},
required: ['file_count', 'limit_count', 'used_space', 'total_space'],
},
run: async (p, ctx) => {
const info = await ctx.bridge.apis.groupFile.getCount(p.group_id);
// 0x6D8 count (subcmd 2) + space (subcmd 3) are separate queries (#196).
const [count, space] = await Promise.all([
ctx.bridge.apis.groupFile.getCount(p.group_id),
ctx.bridge.apis.groupFile.getSpace(p.group_id),
]);
return okResponse({
file_count: info.fileCount,
limit_count: info.maxCount,
used_space: 0,
total_space: 10737418240,
file_count: count.fileCount,
limit_count: count.maxCount,
used_space: space.usedSpace,
total_space: space.totalSpace,
});
},
}),
+6 -2
View File
@@ -54,9 +54,13 @@ export const actions = [
groupAction({
name: 'set_group_search',
summary: '允许群被搜索',
summary: '设置群被搜索方式(群指纹 / 群号搜索开关)',
params: {
no_finger_open: f.int({ min: 0 }).optional(),
no_code_finger_open: f.int({ min: 0 }).optional(),
},
run: async (p, ctx) => {
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id);
await ctx.bridge.apis.groupAdmin.setSearch(p.group_id, p.no_finger_open, p.no_code_finger_open);
return okResponse();
},
}),
+8 -2
View File
@@ -224,10 +224,16 @@ export const actions = [
groupAction({
name: 'create_group_file_folder',
summary: '创建群文件夹',
// NapCat-aligned data so callers can read back the new folderId (#195):
// { result, groupItem: { folderInfo: { folderId, folderName, … } } }.
returns: '{ result: { retCode, retMsg }, groupItem: { folderInfo: { folderId, folderName, folderPath, createTime, modifyTime, createUin, modifyUin } } }',
params: { name: f.string({ allowEmpty: false }), parent_id: f.string().default('/') },
run: async (p, ctx) => {
await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
return okResponse();
const folderInfo = await ctx.bridge.apis.groupFile.createFolder(p.group_id, p.name, p.parent_id || '/');
return okResponse({
result: { retCode: 0, retMsg: 'success' },
groupItem: { folderInfo },
});
},
}),
+17 -2
View File
@@ -18,6 +18,9 @@ export const actions = [
group_name: { type: 'string', description: '群名' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级(列表批量场景恒 0,详见 get_group_info)' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
},
required: ['group_id', 'group_name', 'member_count', 'max_member_count'],
},
@@ -44,6 +47,9 @@ export const actions = [
group_name: { type: 'string', description: '群名' },
member_count: { type: 'integer', description: '当前成员数' },
max_member_count: { type: 'integer', description: '成员上限' },
group_create_time: { type: 'integer', description: '建群时间戳(秒)' },
group_level: { type: 'integer', description: '群等级' },
group_memo: { type: 'string', description: '群简介 / 公告预览' },
},
required: ['group_id', 'group_name', 'member_count', 'max_member_count'],
},
@@ -51,11 +57,12 @@ export const actions = [
run: async (p, ctx) => {
const groupId = p.group_id;
const noCache = p.no_cache;
const fallback = { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0, group_create_time: 0, group_level: 0, group_memo: '' };
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
return okResponse(info ?? fallback);
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
return okResponse(fallback);
},
}),
@@ -80,6 +87,10 @@ export const actions = [
level: { type: 'string', description: '群等级' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
@@ -114,6 +125,10 @@ export const actions = [
level: { type: 'string', description: '群等级' },
role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' },
title: { type: 'string', description: '专属头衔' },
area: { type: 'string', description: '地区(QQ NT 不提供,恒空)' },
unfriendly: { type: 'boolean', description: '是否不良记录(QQ NT 不提供,恒 false)' },
title_expire_time: { type: 'integer', description: '头衔过期时间戳(QQ NT 不提供,恒 0)' },
card_changeable: { type: 'boolean', description: '是否可改名片(占位,恒 true)' },
},
required: ['group_id', 'user_id', 'nickname', 'role'],
},
+28
View File
@@ -147,6 +147,34 @@ export const actions = [
},
}),
// set_qzone_msg_right — 修改机器人自己空间一条已发说说的查看权限(按 tid)。
// 写操作;ugc_right/target_uins 语义与 send_qzone_msg 一致。
defineAction({
name: 'set_qzone_msg_right',
returns: '更新后的权限对象。',
returnsSchema: {
type: 'object',
properties: {
ugc_right: { type: 'integer', description: '更新后的查看权限' },
},
required: ['ugc_right'],
},
summary: '修改一条已发说说的查看权限(QQ 空间,按 tid)',
params: {
tid: f.string({ allowEmpty: false }).describe('说说 tid(来自 get_qzone_msg_list / send_qzone_msg)'),
ugc_right: f.int({ min: 1 }).describe('查看权限:1=所有人可见,4=好友可见,16=部分好友可见,64=仅自己可见,128=部分好友不可见'),
target_uins: f.array(f.uint()).describe('权限作用 QQ 号数组;ugc_right=16 时表示可见名单,128 时表示不可见名单').optional(),
},
rules: (r) => [
r.rule('ugc_right must be one of 1, 4, 16, 64, 128', (p) => QZONE_UGC_RIGHTS.has(p.ugc_right)),
r.rule('target_uins is required when ugc_right is 16 or 128', (p) => (p.ugc_right !== 16 && p.ugc_right !== 128) || !!p.target_uins?.length),
],
run: async (p, ctx) => {
const res = await ctx.bridge.apis.qzone.updateRight(p.tid, p.ugc_right, p.target_uins?.join('|'));
return okResponse(res as unknown as JsonValue);
},
}),
// like_qzone — 给一条说说点赞。target_uin 省略=机器人自己空间;点赞好友说说传其 uin。
// abstime=该说说的发表时间(unix 秒,来自 get_qzone_feeds/get_qzone_msg_list),
// 传真实值更可靠;不传按 0。写操作;高频点赞会被 Qzone 风控,调用方需限流。
@@ -50,9 +50,34 @@ export async function getGroupList(
group_name: g.groupName,
member_count: g.memberCount,
max_member_count: g.memberMax,
// #197: create_time + memo come free from the list; group_level is only in
// the per-group 0x88D_0 detail, so it stays 0 here (a per-group fetch across
// the whole list would be far too expensive). get_group_info fills it in.
group_create_time: g.createTime ?? 0,
group_level: g.level ?? 0,
group_memo: g.memo ?? '',
}));
}
// group_level lives only in the 0x88D_0 detail. Memoize it (short TTL) so a
// joined-group get_group_info doesn't fetch the detail on every call (#197).
const GROUP_LEVEL_TTL_MS = 5 * 60 * 1000;
const groupLevelCache = new Map<number, { level: number; at: number }>();
async function getGroupLevel(bridge: BridgeInterface, groupId: number, noCache?: boolean): Promise<number> {
if (!noCache) {
const c = groupLevelCache.get(groupId);
if (c && Date.now() - c.at < GROUP_LEVEL_TTL_MS) return c.level;
}
try {
const detail = await bridge.apis.contacts.fetchGroupDetail(groupId);
const level = detail?.level ?? 0;
groupLevelCache.set(groupId, { level, at: Date.now() });
return level;
} catch {
return 0;
}
}
// Short-TTL cache for the non-member group lookup (0x88D_0). Joined groups come
// from the identity roster (kept fresh by fetchGroupList) and are NOT cached
// here; this only memoizes the per-id server query so a burst of invites for the
@@ -79,6 +104,9 @@ export async function getGroupInfo(
group_name: g.groupName,
member_count: g.memberCount,
max_member_count: g.memberMax,
group_create_time: g.createTime ?? 0,
group_level: await getGroupLevel(bridge, groupId, noCache),
group_memo: g.memo ?? '',
};
}
@@ -96,6 +124,9 @@ export async function getGroupInfo(
group_name: detail.groupName,
member_count: detail.memberCount,
max_member_count: detail.memberMax,
group_create_time: detail.createTime ?? 0,
group_level: detail.level ?? 0,
group_memo: detail.memo ?? '',
};
nonMemberGroupCache.set(groupId, { info, at: Date.now() });
return { ...info };
@@ -264,5 +295,12 @@ function formatGroupMember(
level: String(member.level),
role: member.role,
title: member.title,
// OneBot v11 completeness (#197). QQ NT doesn't expose these, so they're
// fixed placeholders — matching go-cqhttp / NapCat, which also hardcode
// them: area='', unfriendly=false, title_expire_time=0, card_changeable=true.
area: '',
unfriendly: false,
title_expire_time: 0,
card_changeable: true,
};
}
+12 -1
View File
@@ -27,7 +27,18 @@ export async function handleGroupAddRequest(
}
}
const requests = await bridge.apis.contacts.fetchGroupRequests();
// A join/invite request lands in either the main inbox (0x10c8 subCommand 1)
// or the spam-filtered one (subCommand 2). The old code only fetched the main
// inbox, so a filtered request that SnowLuma had already reported to the
// client couldn't be approved through its own flag — "matching group request
// not found" (#197). Search both; each request keeps the `filtered` flag its
// inbox needs for the approval subCommand. One inbox failing degrades to the
// other rather than aborting.
const [mainInbox, filteredInbox] = await Promise.all([
bridge.apis.contacts.fetchGroupRequests(false).catch(() => []),
bridge.apis.contacts.fetchGroupRequests(true).catch(() => []),
]);
const requests = [...mainInbox, ...filteredInbox];
const matching = requests.find((r) => {
if (r.groupId !== groupId) return false;
if (requestType === 'add') return r.targetUid === targetUid;
@@ -151,6 +151,7 @@ describe('onebot/contact-actions / getGroupList', () => {
expect(out).toEqual([{
group_id: 100, group_name: 'Group A',
member_count: 0, max_member_count: 500,
group_create_time: 0, group_level: 0, group_memo: '',
}]);
});
@@ -62,4 +62,31 @@ describe('qzone actions', () => {
expect(publish).not.toHaveBeenCalled();
});
it('set_qzone_msg_right joins target_uins with | and passes through', async () => {
const updateRight = vi.fn().mockResolvedValue({ ugc_right: 16 });
const handler = makeHandler({ updateRight });
const res = await handler.handle('set_qzone_msg_right', {
tid: 'T1',
ugc_right: 16,
target_uins: [10001, 10002],
});
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: { ugc_right: 16 } });
expect(updateRight).toHaveBeenCalledWith('T1', 16, '10001|10002');
});
it('set_qzone_msg_right rejects invalid ugc_right and 16/128 without target_uins', async () => {
const updateRight = vi.fn();
const handler = makeHandler({ updateRight });
const bad = await handler.handle('set_qzone_msg_right', { tid: 'T1', ugc_right: 2 });
expect(bad).toMatchObject({ status: 'failed' });
const missing = await handler.handle('set_qzone_msg_right', { tid: 'T1', ugc_right: 128 });
expect(missing).toMatchObject({ status: 'failed' });
expect(updateRight).not.toHaveBeenCalled();
});
});
@@ -82,4 +82,33 @@ describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false);
});
it('finds a request that only lives in the filtered inbox (#197)', async () => {
const setAddRequest = vi.fn(async () => {});
const bridge = fakeBridge({
// Main inbox empty; the invite sits only in the spam-filtered inbox.
fetchGroupRequests: vi.fn(async (filtered: boolean) =>
filtered
? [fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 55, eventType: 2, filtered: true })]
: []),
getGroupInviteCardSequence: vi.fn(() => null),
apis: { groupAdmin: { setAddRequest } } as any,
});
await handleGroupAddRequest(bridge, 'invite:999:u_i', true, 'ok');
// Approved through the filtered inbox (subCommand 2 → last arg true).
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 55, 2, true, 'ok', true);
});
it('surfaces "not found" only when neither inbox has the request', async () => {
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => []),
getGroupInviteCardSequence: vi.fn(() => null),
apis: { groupAdmin: { setAddRequest: vi.fn(async () => {}) } } as any,
});
await expect(handleGroupAddRequest(bridge, 'invite:999:u_i', true, 'ok'))
.rejects.toThrow(/matching group request not found/);
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proto-defs",
"version": "1.11.1",
"version": "1.11.2",
"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).",
+21 -1
View File
@@ -31,9 +31,29 @@ export interface Oidb0x89a_0AddOption {
settings?: pb<2, Oidb0x89a_0AddOptionSettings>;
field12?: pb<12, uint_32>;
}
// The `settings` payload is the GroupDetailInfo "modify" sub-message carrying
// only the fields being changed (the NT GroupDetailFilter is client-side — it
// just gates which fields the encoder emits, like modify-group-ext-info). This
// is a DIFFERENT message domain from the 0x88D_0 group-detail GET: mute/
// shutUpTime is tag 17 here (Lagrange/MuteAll) but a string in the GET, so the
// tags do NOT match the GET's groupInfo. Tags RE'd empirically on a live group
// (bot as admin) by sweeping this sub-message tag-by-tag and reading the effect
// back through the 0x88D_0 GET (82/83), then confirming against the client's
// 3-state "被搜索方式" dropdown (私密 / 群号 / 群号+关键词):
// noFingerOpen (关键词/群指纹搜索) = tag 35 → GET 82
// noCodeFingerOpen (群号搜索 / 总开关) = tag 36 → GET 83
// Value 0 = that mode open/enabled, 1 = disabled ("no…Open"); keyword search
// additionally requires code search on. Matches NapCat modifyGroupDetailInfoV2.
export interface Oidb0x89a_0SearchSettings {
// pb_optional (explicit presence): a value of 0 (mode enabled) MUST be sent,
// so these can't use plain pb<> — proto3 would drop the zero and the request
// would silently no-op. undefined is still elided (field left unchanged).
noFingerOpen?: pb_optional<35, uint_32>;
noCodeFingerOpen?: pb_optional<36, uint_32>;
}
export interface Oidb0x89a_0Search {
groupUin?: pb<1, uint_64>;
settings?: pb<2, bytes>;
settings?: pb<2, Oidb0x89a_0SearchSettings>;
field12?: pb<12, uint_32>;
}
export interface OidbKickMember {
@@ -183,10 +183,25 @@ export interface OidbGroupFileFolderReq {
delete?: pb<2, OidbGroupFileDeleteFolderReq>;
rename?: pb<3, OidbGroupFileRenameFolderReq>;
}
// The create (0x6D7_0) response also carries the new folder's info at field 4
// — the source of folderId (#195). delete/rename responses leave it empty.
// Tags confirmed against a live create response (bot creating a folder in a
// test group): modifyUin is field 9, NOT 7 as Lagrange's
// OidbSvcTrpcTcp0x6D7_0ResponseFolderInfo has it.
export interface OidbGroupFileFolderInfoResp {
folderId?: pb<1, string>;
folderPath?: pb<2, string>;
folderName?: pb<3, string>;
createTime?: pb<4, uint_32>;
modifyTime?: pb<5, uint_32>;
createUin?: pb<6, uint_32>;
modifyUin?: pb<9, uint_32>;
}
export interface OidbGroupFileFolderRetResp {
retcode?: pb<1, uint_32>;
retMsg?: pb<2, string>;
clientWording?: pb<3, string>;
folderInfo?: pb<4, OidbGroupFileFolderInfoResp>;
}
export interface OidbGroupFileFolderResp {
create?: pb<1, OidbGroupFileFolderRetResp>;
@@ -198,14 +213,30 @@ export interface OidbGroupFileCountReq {
appId?: pb<2, uint_32>;
busId?: pb<3, uint_32>;
}
// Count response (0x6D8_2): fileCount is field 4 and maxCount (the group's file
// ceiling, e.g. 1500) field 6 — RE'd from a live count query (#196). The old
// pb<1>/pb<2> tags matched nothing, so file_count always decoded to 0.
export interface OidbGroupFileCountResp {
fileCount?: pb<1, uint_32>;
maxCount?: pb<2, uint_32>;
isEnd?: pb<3, bool>;
fileCount?: pb<4, uint_32>;
maxCount?: pb<6, uint_32>;
isFull?: pb<7, bool>;
}
// Space request/response (0x6D8_3). Both values are 64-bit — the 10 GiB ceiling
// already exceeds uint32.
export interface OidbGroupFileSpaceReq {
groupUin?: pb<1, uint_32>;
appId?: pb<2, uint_32>;
}
export interface OidbGroupFileSpaceResp {
totalSpace?: pb<4, uint_64>;
usedSpace?: pb<5, uint_64>;
}
// count → subCommand 2, space → subCommand 3 (List is subCommand 1).
export interface OidbGroupFileCountViewReq {
count?: pb<3, OidbGroupFileCountReq>;
space?: pb<4, OidbGroupFileSpaceReq>;
}
export interface OidbGroupFileCountViewResp {
count?: pb<3, OidbGroupFileCountResp>;
space?: pb<4, OidbGroupFileSpaceResp>;
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/protocol",
"version": "1.11.1",
"version": "1.11.2",
"private": true,
"type": "module",
"description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/<x>'` collapses to `import { … } from '@snowluma/protocol/<x>'`.",
@@ -1,24 +1,36 @@
// 0x89A_0 — toggle group "searchable" flag. Same cmd+subcmd shape as
// MuteAll / SetAddOption / SetName.
// 0x89A_0 — set a group's "被搜索方式" (searchability). Same cmd+subcmd shape as
// MuteAll / SetAddOption / SetName; the `settings` submessage carries the two
// search flags. Empty settings is a no-op (why the earlier version silently
// did nothing) — a real change must emit at least one flag. Command + tags
// (noFingerOpen=35, noCodeFingerOpen=36) RE'd empirically on a live group by
// sweeping the modify sub-message and reading the effect back through the
// 0x88D_0 GET (see Oidb0x89a_0SearchSettings for the full derivation).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase, OidbEmpty } from '@snowluma/proto-defs/oidb';
import type { Oidb0x89a_0Search } from '@snowluma/proto-defs/oidb-actions/base';
import type { Oidb0x89a_0Search, Oidb0x89a_0SearchSettings } from '@snowluma/proto-defs/oidb-actions/base';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export namespace SetSearch {
export const command = 0x89A;
export const subCommand = 0;
export interface Params { groupId: number; }
export interface Params {
groupId: number;
/** 群指纹(关键词)搜索开关。undefined → 不改(不下发该字段)。 */
noFingerOpen?: number;
/** 群号搜索开关。undefined → 不改(不下发该字段)。 */
noCodeFingerOpen?: number;
}
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0Search => ({
groupUin: BigInt(p.groupId),
settings: new Uint8Array(0),
field12: 0,
});
export const serialize = (_ctx: Deps, p: Params): Oidb0x89a_0Search => {
const settings: Oidb0x89a_0SearchSettings = {};
if (p.noFingerOpen !== undefined) settings.noFingerOpen = p.noFingerOpen;
if (p.noCodeFingerOpen !== undefined) settings.noCodeFingerOpen = p.noCodeFingerOpen;
return { groupUin: BigInt(p.groupId), settings, field12: 0 };
};
export const deserialize = (_ctx: Deps, _: OidbEmpty): void => {};
@@ -17,6 +17,17 @@ export namespace CreateGroupFolder {
export interface Params { groupId: number; parentId: string; folderName: string; }
export type Deps = OidbSender;
/** The newly created folder, from the create response's folderInfo (#195). */
export type Result = {
folderId: string;
folderName: string;
folderPath: string;
createTime: number;
modifyTime: number;
createUin: number;
modifyUin: number;
};
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileFolderReq => ({
create: {
groupUin: p.groupId,
@@ -25,10 +36,20 @@ export namespace CreateGroupFolder {
},
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): void => {
export const deserialize = (_ctx: Deps, body: OidbGroupFileFolderResp): Result => {
const result = body.create;
if (!result) throw new Error('group folder create response missing');
ensureRetCodeZero('group folder create', result.retcode, result.retMsg, result.clientWording);
const info = result.folderInfo ?? {};
return {
folderId: info.folderId ?? '',
folderName: info.folderName ?? '',
folderPath: info.folderPath ?? '',
createTime: info.createTime ?? 0,
modifyTime: info.modifyTime ?? 0,
createUin: info.createUin ?? 0,
modifyUin: info.modifyUin ?? 0,
};
};
export const encode = (env: OidbBase<OidbGroupFileFolderReq>): Uint8Array =>
@@ -37,6 +58,6 @@ export namespace CreateGroupFolder {
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileFolderResp> =>
protobuf_decode<OidbBase<OidbGroupFileFolderResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<void> =>
export const invoke = (deps: Deps, params: Params): Promise<Result> =>
invokeOidb(deps, CreateGroupFolder, params);
}
@@ -1,7 +1,8 @@
// 0x6D8_3 — fetch group file slot usage. Returns the current count
// alongside the server-side ceiling (NTQQ's `maxCount` default is
// 10000; we surface that fallback so the OneBot action can render
// the gauge without a second call when the server elides the field).
// 0x6D8_2 — fetch the group file slot count. The 0x6D8 view command splits
// into three subcommands: 1=List, 2=Count, 3=Space (see GetGroupFileSpace).
// This was previously mis-wired to subCommand 3 (Space) with busId=0, so the
// Count block was never returned and file_count always came back 0 (#196).
// The count request needs busId=6.
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
@@ -17,13 +18,13 @@ export interface GroupFileCount {
export namespace GetGroupFileCount {
export const command = 0x6D8;
export const subCommand = 3;
export const subCommand = 2;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileCountViewReq => ({
count: { groupUin: p.groupId, appId: 7, busId: 0 },
count: { groupUin: p.groupId, appId: 7, busId: 6 },
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileCountViewResp): GroupFileCount => ({
@@ -0,0 +1,42 @@
// 0x6D8_3 — fetch the group file space usage (used / total bytes). Sibling of
// GetGroupFileCount (0x6D8_2): the 0x6D8 view command's subCommand 3 = Space.
// RE'd from a live query (#196) — the response carries a Space block at field 4
// with totalSpace at field 4 and usedSpace at field 5 (both 64-bit).
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type {
OidbGroupFileCountViewReq, OidbGroupFileCountViewResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import { invokeOidb, type OidbSender } from '../../oidb-service';
export interface GroupFileSpace {
usedSpace: number;
totalSpace: number;
}
export namespace GetGroupFileSpace {
export const command = 0x6D8;
export const subCommand = 3;
export interface Params { groupId: number; }
export type Deps = OidbSender;
export const serialize = (_ctx: Deps, p: Params): OidbGroupFileCountViewReq => ({
space: { groupUin: p.groupId, appId: 7 },
});
export const deserialize = (_ctx: Deps, body: OidbGroupFileCountViewResp): GroupFileSpace => ({
usedSpace: Number(body.space?.usedSpace ?? 0),
totalSpace: Number(body.space?.totalSpace ?? 0),
});
export const encode = (env: OidbBase<OidbGroupFileCountViewReq>): Uint8Array =>
protobuf_encode<OidbBase<OidbGroupFileCountViewReq>>(env);
export const decode = (bytes: Uint8Array): OidbBase<OidbGroupFileCountViewResp> =>
protobuf_decode<OidbBase<OidbGroupFileCountViewResp>>(bytes);
export const invoke = (deps: Deps, params: Params): Promise<GroupFileSpace> =>
invokeOidb(deps, GetGroupFileSpace, params);
}
+6
View File
@@ -41,6 +41,12 @@ export interface QQGroupInfo {
memberCount: number;
memberMax: number;
members: Map<number, GroupMemberInfo>;
/** Group creation time (unix seconds). 0 when unknown (#197). */
createTime?: number;
/** Group level. Only the 0x88D_0 detail carries it; 0 from the list (#197). */
level?: number;
/** Group memo / announcement preview. '' when unknown (#197). */
memo?: string;
}
export interface GroupRequestInfo {
+258 -5
View File
@@ -64,20 +64,30 @@ export interface QzoneMsgListResult {
/**
* Parse a Qzone CGI body that may be raw JSON or a JSONP callback wrapper
* (`_Callback({...});` / `callback({...})`). We slice from the first `{`
* to the last `}` and JSON.parse that — robust to either form without
* (`_Callback({...});` / `callback({...})`). We first attempt to slice from
* the first `{` to the last `}`, when failed attempt from the first `back({`
* to the last `})` and JSON.parse that — robust to either form without
* pinning the callback name, which Qzone varies. Throws if no object body
* is present (e.g. an HTML error page), which the caller turns into a
* failed response rather than a silent empty list.
*/
export function parseQzoneJson<T>(text: string): T {
const s = text.trim();
const start = s.indexOf('{');
const end = s.lastIndexOf('}');
try {
const start = s.indexOf('{');
const end = s.lastIndexOf('}');
if (start !== -1 && end !== -1 && end > start) {
return JSON.parse(s.slice(start, end + 1)) as T;
}
} catch {
}
const start = s.indexOf('back({');
const end = s.lastIndexOf('})');
if (start === -1 || end === -1 || end < start) {
throw new Error('invalid response from qzone api');
}
return JSON.parse(s.slice(start, end + 1)) as T;
return JSON.parse(s.slice(start + 5, end + 1)) as T;
}
/**
@@ -1040,3 +1050,246 @@ export async function commentQzoneMsg(
const commentId = data.commentid ?? data.commentId;
return { comment_id: commentId !== undefined ? String(commentId) : '' };
}
// ─────── 改说说权限 (update right) — emotion_cgi_msgdetail_v6 + emotion_cgi_update ───────
// Changes the view permission (ugc_right) of an EXISTING 说说. The update CGI
// is not a partial patch — it re-submits the whole feed (content, richval,
// pic_bo, …), so the flow is two-step: GET the feed detail from
// emotion_cgi_msgdetail_v6 (NOTE: proxied domain is taotao.qq.com, not
// taotao.qzone.qq.com — that's what the working impl hits), rebuild the full
// publish-shaped payload from it, override ugc_right/allow_uins, and POST to
// emotion_cgi_update. Both the detail param set and the payload rebuild are
// CONFIRMED against php-qzone/qzone.class.php updateRight (live-verified
// there); success signal is `subcode == 0`, same envelope as the siblings.
// WRITE OP — rate-limit like publish.
interface RawMsgDetailPic {
pic_id?: string;
pictype?: number | string;
type?: number | string;
height?: number | string;
b_height?: number | string;
width?: number | string;
b_width?: number | string;
smallurl?: string;
url1?: string;
url2?: string;
url3?: string;
}
interface RawMsgDetailResponse {
code?: number;
subcode?: number;
message?: string;
msg?: string;
tid?: string;
uin?: number | string;
content?: string;
conlist?: Array<{ con?: string }> | null;
pic?: RawMsgDetailPic[] | null;
richtype?: number | string;
richval?: string;
pic_template?: string;
special_url?: string;
t1_subtype?: number | string;
subrichtype?: number | string;
feedversion?: number | string;
ver?: number | string;
ugc_right?: number | string;
to_sign?: number | string;
ugcright_id?: string;
code_version?: number | string;
}
interface RawUpdateResponse {
code?: number;
subcode?: number;
message?: string;
msg?: string;
ugc_right?: number | string;
}
/** Result of changing a 说说's view permission. */
export interface QzoneUpdateRightResult {
[key: string]: JsonValue;
/** The feed's ugc_right after the update (echoed by the server when present). */
ugc_right: number;
}
/**
* Rebuild the full emotion_cgi_update payload from a msgdetail_v6 response.
* Field-for-field port of php-qzone's buildUpdatePayloadFromDetail: richval
* strings are reconstructed from each `pic[].pic_id` (`,albumid,lloc,sloc,
* type,height,width,,0,0`, tab-joined), `pic_bo` from the `bo=` query param
* of any picture URL variant (group tab-doubled), and the content from
* `conlist` when present. Exported for tests; THROWS on a detail body it
* cannot rebuild from (missing tid, or an image post whose pic info is
* unusable) rather than submitting a lossy update.
*/
export function buildQzoneUpdatePayload(detail: RawMsgDetailResponse, selfUin: string): URLSearchParams {
if (!detail.tid) {
throw new Error('qzone msg detail is missing tid');
}
const pics = detail.pic ?? [];
const richtype = detail.richtype !== undefined ? Number(detail.richtype) : (pics.length === 0 ? '' : 1);
const richvals: string[] = [];
const picBoItems: string[] = [];
for (const pic of pics) {
const picId = String(pic.pic_id ?? '');
if (!picId) continue;
const parts = picId.split(',');
const albumId = parts[1] ?? '';
const lloc = parts[2] ?? '';
if (!albumId || !lloc) {
throw new Error('qzone msg detail has unsupported pic info');
}
const sloc = lloc;
const picType = String(pic.pictype ?? pic.type ?? 22);
const height = String(pic.height ?? pic.b_height ?? 0);
const width = String(pic.width ?? pic.b_width ?? 0);
richvals.push(`,${albumId},${lloc},${sloc},${picType},${height},${width},,0,0`);
for (const urlKey of ['smallurl', 'url1', 'url2', 'url3'] as const) {
const picUrl = pic[urlKey];
if (!picUrl) continue;
const match = /[?&]bo=([^&#]+)/.exec(picUrl);
if (match) {
picBoItems.push(decodeURIComponent(match[1]!));
break;
}
}
}
if (richtype === 1 && richvals.length === 0) {
throw new Error('qzone image post detail is missing pic info');
}
let content = detail.content ?? '';
const conParts = (detail.conlist ?? [])
.map((c) => c.con)
.filter((c): c is string => c !== undefined);
if (conParts.length > 0) {
content = conParts.join('').trim();
}
const subrichtype = detail.t1_subtype ?? detail.subrichtype ?? (richvals.length === 0 ? '' : 1);
const boGroup = picBoItems.join(',');
const picBo = boGroup ? `${boGroup}\t${boGroup}` : '';
const hostuin = String(detail.uin ?? selfUin);
return new URLSearchParams({
syn_tweet_verson: '1',
tid: String(detail.tid),
paramstr: '1',
pic_template: detail.pic_template ?? '',
richtype: String(richtype),
richval: richvals.length > 0 ? richvals.join('\t') : (detail.richval ?? ''),
special_url: detail.special_url ?? '',
subrichtype: String(subrichtype),
pic_bo: picBo,
con: content,
feedversion: String(detail.feedversion ?? 1),
ver: String(detail.ver ?? 1),
ugc_right: String(Number(detail.ugc_right ?? 1)),
to_sign: String(Number(detail.to_sign ?? 0)),
ugcright_id: String(detail.ugcright_id ?? detail.tid),
hostuin,
code_version: String(detail.code_version ?? 1),
format: 'fs',
qzreferrer: `https://user.qzone.qq.com/${hostuin}`,
});
}
/** Fetch one 说说's full detail (the update payload's source of truth). */
async function getQzoneMsgDetail(
cookieObject: Record<string, string>,
selfUin: string,
tid: string,
): Promise<RawMsgDetailResponse> {
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6?${new URLSearchParams(
{
tid,
uin: selfUin,
t1_source: '1',
not_trunc_con: '1',
need_right: '1',
not_adapt_outpic: '1',
g_tk: bkn,
},
).toString()}`;
const text = await RequestUtil.HttpGetText(url, 'GET', '', {
Cookie: cookieToString(cookieObject),
});
log.trace('getQzoneMsgDetail raw body (tid=%s): %s', tid, text);
const data = parseQzoneJson<RawMsgDetailResponse>(text);
const code = data.subcode ?? data.code ?? -1;
if (code !== 0) {
log.warn('getQzoneMsgDetail: non-zero code (tid=%s) code=%d msg=%s', tid, code, data.message ?? data.msg);
throw new Error(`qzone msg detail failed: code=${code} ${data.message ?? data.msg ?? ''}`.trim());
}
return data;
}
/**
* Change the view permission of an existing 说说 (`tid`, on the bot's own
* space) via the msgdetail_v6 → emotion_cgi_update two-step. `ugcRight` is
* one of 1(所有人)/4(好友)/16(部分可见)/64(仅自己)/128(部分不可见);
* `targetUins` (|-separated QQ numbers) is required for 16/128 and ignored
* otherwise. Errors PROPAGATE from both steps: a transport failure, a
* non-zero Qzone code on the detail fetch (unknown/foreign tid, auth), an
* unrebuildable detail, or a non-zero `subcode` on the update all throw.
*/
export async function updateQzoneMsgRight(
cookieObject: Record<string, string>,
selfUin: string,
tid: string,
ugcRight: number,
targetUins?: string,
): Promise<QzoneUpdateRightResult> {
if (!cookieObject || typeof cookieObject !== 'object') {
throw new Error('cookieObject is required');
}
if (!tid) {
throw new Error('tid is required');
}
const right = normalizeQzoneUgcRight(ugcRight);
const effectiveTargetUins = right === 16 || right === 128 ? normalizeTargetUins(targetUins) : '';
if ((right === 16 || right === 128) && !effectiveTargetUins) {
throw new Error('target_uins is required when ugc_right is 16 or 128');
}
const detail = await getQzoneMsgDetail(cookieObject, selfUin, tid);
const bodyParams = buildQzoneUpdatePayload(detail, selfUin);
bodyParams.set('ugc_right', String(right));
if (effectiveTargetUins) bodyParams.set('allow_uins', effectiveTargetUins);
const bkn = getBknFromCookie(cookieObject);
const url = `https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update?g_tk=${bkn}`;
const text = await RequestUtil.HttpGetText(url, 'POST', bodyParams.toString(), {
Cookie: cookieToString(cookieObject),
'Content-Type': 'application/x-www-form-urlencoded',
});
// format=fs wraps the JSON in a callback (`frameElement.callback({...});`
// or `_Callback({...});`) — parseQzoneJson's first-{-to-last-} slice
// handles every observed variant.
const data = parseQzoneJson<RawUpdateResponse>(text);
if (typeof data.subcode === 'number' && data.subcode !== 0) {
log.warn('updateQzoneMsgRight: non-zero subcode (tid=%s) subcode=%d msg=%s', tid, data.subcode, data.message ?? data.msg);
throw new Error(`qzone update right failed: subcode=${data.subcode} ${data.message ?? data.msg ?? ''}`.trim());
}
if (typeof data.code === 'number' && data.code !== 0) {
log.warn('updateQzoneMsgRight: non-zero code (tid=%s) code=%d msg=%s', tid, data.code, data.message ?? data.msg);
throw new Error(`qzone update right failed: code=${data.code} ${data.message ?? data.msg ?? ''}`.trim());
}
return { ugc_right: Number(data.ugc_right ?? right) };
}
@@ -37,4 +37,28 @@ describe('CreateGroupFolder namespace', () => {
await expect(CreateGroupFolder.invoke(deps, { groupId: 1, parentId: '/', folderName: 'f' }))
.rejects.toThrow(/code=7/);
});
it('returns the new folder info from the response folderInfo (#195)', async () => {
const deps = makeDeps({ create: {
retcode: 0,
folderInfo: {
folderId: '/0f1e2d', folderPath: '/docs', folderName: 'docs',
createTime: 100, modifyTime: 200, createUin: 111, modifyUin: 222,
},
} as any });
const r = await CreateGroupFolder.invoke(deps, { groupId: 1, parentId: '/', folderName: 'docs' });
expect(r).toEqual({
folderId: '/0f1e2d', folderName: 'docs', folderPath: '/docs',
createTime: 100, modifyTime: 200, createUin: 111, modifyUin: 222,
});
});
it('defaults every field when the response omits folderInfo (#195)', async () => {
const deps = makeDeps({ create: { retcode: 0 } as any });
const r = await CreateGroupFolder.invoke(deps, { groupId: 1, parentId: '/', folderName: 'f' });
expect(r).toEqual({
folderId: '', folderName: '', folderPath: '',
createTime: 0, modifyTime: 0, createUin: 0, modifyUin: 0,
});
});
});
@@ -17,21 +17,21 @@ function makeDeps(body?: OidbGroupFileCountViewResp) {
}
describe('GetGroupFileCount namespace', () => {
it('declares 0x6D8_3', () => {
it('declares 0x6D8_2 (Count subcommand)', () => {
expect(GetGroupFileCount.command).toBe(0x6D8);
expect(GetGroupFileCount.subCommand).toBe(3);
expect(GetGroupFileCount.subCommand).toBe(2);
});
it('routes to 0x6d8_3 with groupUin + appId=7 + busId=0', async () => {
it('routes to 0x6d8_2 with groupUin + appId=7 + busId=6 (#196)', async () => {
const deps = makeDeps({ count: { fileCount: 1, maxCount: 100 } });
await GetGroupFileCount.invoke(deps, { groupId: 12345 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d8_3');
expect(wire).toBe('OidbSvcTrpcTcp.0x6d8_2');
const env = protobuf_decode<OidbBase<OidbGroupFileCountViewReq>>(bytes);
expect(env.body?.count).toMatchObject({ groupUin: 12345, appId: 7 });
expect(env.body?.count).toMatchObject({ groupUin: 12345, appId: 7, busId: 6 });
});
it('decodes both counters as plain numbers', async () => {
it('decodes fileCount (field 4) + maxCount (field 6) as plain numbers', async () => {
const deps = makeDeps({ count: { fileCount: 42, maxCount: 1000 } });
const out = await GetGroupFileCount.invoke(deps, { groupId: 1 });
expect(out).toEqual({ fileCount: 42, maxCount: 1000 });
@@ -0,0 +1,46 @@
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 {
OidbGroupFileCountViewReq, OidbGroupFileCountViewResp,
} from '@snowluma/proto-defs/oidb-actions/group-file';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { GetGroupFileSpace } from '../../../src/oidb-services/group-file/get-group-file-space';
function makeDeps(body?: OidbGroupFileCountViewResp) {
const responseData = body !== undefined
? Buffer.from(protobuf_encode<OidbBase<OidbGroupFileCountViewResp>>({ body }))
: Buffer.alloc(0);
const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData };
return { sendRawPacket: vi.fn(async () => r) };
}
describe('GetGroupFileSpace namespace (#196)', () => {
it('declares 0x6D8_3 (Space subcommand)', () => {
expect(GetGroupFileSpace.command).toBe(0x6D8);
expect(GetGroupFileSpace.subCommand).toBe(3);
});
it('routes to 0x6d8_3 with a space request (groupUin + appId=7)', async () => {
const deps = makeDeps({ space: {} });
await GetGroupFileSpace.invoke(deps, { groupId: 12345 });
const [wire, bytes] = deps.sendRawPacket.mock.calls[0]!;
expect(wire).toBe('OidbSvcTrpcTcp.0x6d8_3');
const env = protobuf_decode<OidbBase<OidbGroupFileCountViewReq>>(bytes);
expect(env.body?.space).toMatchObject({ groupUin: 12345, appId: 7 });
expect(env.body?.count).toBeNull();
});
it('decodes usedSpace (field 5) + totalSpace (field 4) as plain numbers', async () => {
const deps = makeDeps({ space: { usedSpace: 20103729n, totalSpace: 10737418240n } });
const out = await GetGroupFileSpace.invoke(deps, { groupId: 1 });
expect(out).toEqual({ usedSpace: 20103729, totalSpace: 10737418240 });
});
it('defaults to 0 when the server elides the space block', async () => {
const deps = makeDeps({ space: {} });
const out = await GetGroupFileSpace.invoke(deps, { groupId: 1 });
expect(out).toEqual({ usedSpace: 0, totalSpace: 0 });
});
});
@@ -0,0 +1,48 @@
import { describe, expect, it, vi } from 'vitest';
import type { SendPacketResult } from '@snowluma/common/packet-sender';
import { SetSearch } from '../../src/oidb-services/group-admin/set-search';
// Capture the exact OIDB request bytes SetSearch sends, via a fake sender.
async function sentHex(params: SetSearch.Params): Promise<string> {
let body: Uint8Array | undefined;
const deps = {
sendRawPacket: vi.fn(async (_cmd: string, b: Uint8Array): Promise<SendPacketResult> => {
body = b;
return { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) };
}),
};
await SetSearch.invoke(deps as never, params);
return Buffer.from(body!).toString('hex');
}
// settings (field2) sub-message: noFingerOpen = tag 35 (35<<3 = 280 → varint
// "98 02"), noCodeFingerOpen = tag 36 (36<<3 = 288 → "a0 02"). Tags RE'd
// empirically on a live group (#191, see Oidb0x89a_0SearchSettings).
describe('SetSearch (0x89a_0) settings encoding (#191)', () => {
it('emits BOTH flags even at value 0 — toggle-off must not be dropped', async () => {
const h = await sentHex({ groupId: 941657197, noFingerOpen: 0, noCodeFingerOpen: 0 });
// field2 = { 35: 0, 36: 0 } → 12 06 980200 a00200
expect(h).toContain('1206980200a00200');
});
it('emits value 1 correctly', async () => {
const h = await sentHex({ groupId: 941657197, noFingerOpen: 1, noCodeFingerOpen: 1 });
expect(h).toContain('1206980201a00201');
});
it('elides an unprovided flag (undefined → not sent)', async () => {
const h = await sentHex({ groupId: 941657197, noCodeFingerOpen: 0 });
expect(h).toContain('a00200'); // tag 36 (noCodeFingerOpen) present, value 0
expect(h).not.toContain('980200'); // tag 35 (noFingerOpen) absent
});
it('carries the group uin + command 0x89a_0', async () => {
const deps = {
sendRawPacket: vi.fn(async (): Promise<SendPacketResult> => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0),
})),
};
await SetSearch.invoke(deps as never, { groupId: 941657197, noFingerOpen: 1 });
expect(deps.sendRawPacket).toHaveBeenCalledWith('OidbSvcTrpcTcp.0x89a_0', expect.anything(), undefined);
});
});
@@ -0,0 +1,143 @@
import { describe, it, expect, vi, afterEach } from 'vitest';
import { buildQzoneUpdatePayload, updateQzoneMsgRight } from '@snowluma/protocol/web/qzone';
import { RequestUtil } from '@snowluma/protocol/web/request-util';
// updateQzoneMsgRight is the two-step msgdetail_v6 → emotion_cgi_update flow.
// The real logic is the payload REBUILD (detail → publish-shaped form body,
// ported from php-qzone's live-verified updateRight): richval reconstruction
// from pic_id, pic_bo from the `bo=` query param, conlist → con. We pin that
// plus both request shapes and the throw contracts.
const cookies = { p_skey: 'PSK', skey: 'SK', uin: 'o10000', p_uin: 'o10000' };
describe('qzone / buildQzoneUpdatePayload', () => {
it('rebuilds a text-only payload with ugcright_id defaulting to tid', () => {
const body = buildQzoneUpdatePayload(
{ tid: 'T1', uin: 10000, content: 'hello', ugc_right: 1 },
'10000',
);
expect(body.get('tid')).toBe('T1');
expect(body.get('con')).toBe('hello');
expect(body.get('richtype')).toBe('');
expect(body.get('richval')).toBe('');
expect(body.get('pic_bo')).toBe('');
expect(body.get('ugcright_id')).toBe('T1');
expect(body.get('hostuin')).toBe('10000');
expect(body.get('format')).toBe('fs');
});
it('rebuilds richval from pic_id and pic_bo from the bo= query param', () => {
const body = buildQzoneUpdatePayload(
{
tid: 'T2',
uin: 10000,
content: 'pics',
conlist: [{ con: 'pi' }, { con: 'cs' }],
richtype: 1,
pic: [
{
pic_id: 'X,ALBUM1,LLOC1,extra',
pictype: 22,
height: 800,
width: 600,
url1: 'https://photo.example/a.jpg?bo=abc%2Cdef&x=1',
},
],
},
'10000',
);
expect(body.get('con')).toBe('pics');
expect(body.get('richtype')).toBe('1');
expect(body.get('richval')).toBe(',ALBUM1,LLOC1,LLOC1,22,800,600,,0,0');
expect(body.get('pic_bo')).toBe('abc,def\tabc,def');
});
it('throws when an image post detail carries unusable pic info', () => {
expect(() =>
buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [{ pic_id: 'broken' }] }, '10000'),
).toThrow('unsupported pic info');
expect(() => buildQzoneUpdatePayload({ tid: 'T3', richtype: 1, pic: [] }, '10000')).toThrow(
'missing pic info',
);
});
it('throws when the detail has no tid', () => {
expect(() => buildQzoneUpdatePayload({}, '10000')).toThrow('missing tid');
});
});
describe('qzone / updateQzoneMsgRight (HTTP layer)', () => {
afterEach(() => vi.restoreAllMocks());
const detailBody =
'_Callback({"code":0,"subcode":0,"tid":"T1","uin":10000,"content":"hello","ugc_right":1});';
it('GETs the detail then POSTs the rebuilt payload with the new ugc_right', async () => {
const spy = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce(detailBody)
.mockResolvedValueOnce('frameElement.callback({"code":0,"subcode":0,"ugc_right":64});');
const out = await updateQzoneMsgRight(cookies, '10000', 'T1', 64);
expect(out).toEqual({ ugc_right: 64 });
const [detailUrl, detailMethod] = spy.mock.calls[0]!;
expect(detailMethod).toBe('GET');
expect(detailUrl).toContain(
'https://h5.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msgdetail_v6?',
);
const dq = new URLSearchParams((detailUrl as string).split('?')[1]);
expect(dq.get('tid')).toBe('T1');
expect(dq.get('uin')).toBe('10000');
const [updateUrl, updateMethod, updateBody] = spy.mock.calls[1]!;
expect(updateMethod).toBe('POST');
expect(updateUrl).toContain(
'https://h5.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_update?',
);
const uq = new URLSearchParams(updateBody as string);
expect(uq.get('tid')).toBe('T1');
expect(uq.get('con')).toBe('hello');
expect(uq.get('ugc_right')).toBe('64');
expect(uq.get('allow_uins')).toBeNull();
});
it('sets allow_uins (deduped) for ugc_right 16 and requires it', async () => {
const spy = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce(detailBody)
.mockResolvedValueOnce('{"code":0,"subcode":0}');
await updateQzoneMsgRight(cookies, '10000', 'T1', 16, '10001|10001|10002');
const uq = new URLSearchParams(spy.mock.calls[1]![2] as string);
expect(uq.get('ugc_right')).toBe('16');
expect(uq.get('allow_uins')).toBe('10001|10002');
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 128)).rejects.toThrow(
'target_uins is required',
);
});
it('rejects an invalid ugc_right before any request', async () => {
const spy = vi.spyOn(RequestUtil, 'HttpGetText');
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 2)).rejects.toThrow(
'ugc_right must be one of',
);
expect(spy).not.toHaveBeenCalled();
});
it('throws on a non-zero detail code and skips the update POST', async () => {
const spy = vi
.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce('{"code":-3000,"subcode":-3000,"message":"need login"}');
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('code=-3000');
expect(spy).toHaveBeenCalledTimes(1);
});
it('throws on a non-zero update subcode', async () => {
vi.spyOn(RequestUtil, 'HttpGetText')
.mockResolvedValueOnce(detailBody)
.mockResolvedValueOnce('{"code":0,"subcode":-200,"message":"denied"}');
await expect(updateQzoneMsgRight(cookies, '10000', 'T1', 64)).rejects.toThrow('subcode=-200');
});
});
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/proton",
"version": "1.11.1",
"version": "1.11.2",
"private": true,
"type": "module",
"description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"license": "SEE LICENSE IN LICENSE",
"name": "@snowluma/runtime",
"version": "1.11.1",
"version": "1.11.2",
"private": true,
"type": "module",
"main": "index.mjs",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.11.1",
"version": "1.11.2",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",
+1 -1
View File
@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.11.1",
"version": "1.11.2",
"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.11.1",
"version": "1.11.2",
"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.11.1",
"version": "1.11.2",
"type": "module",
"scripts": {
"dev": "vite",
+36 -1
View File
@@ -20,6 +20,24 @@ export default function App() {
);
}
// #194: read a one-shot `?token=<password>` login param and immediately strip
// it from the URL (replaceState) so the credential doesn't linger in the
// address bar / browser history / Referer header. Named `token` to match the
// requested query key; the value is the WebUI login password.
function consumeUrlToken(): string | null {
if (typeof window === 'undefined') return null;
try {
const url = new URL(window.location.href);
const value = url.searchParams.get('token');
if (!value) return null;
url.searchParams.delete('token');
window.history.replaceState({}, '', `${url.pathname}${url.search}${url.hash}`);
return value;
} catch {
return null;
}
}
function AuthBoundary() {
const [authChecked, setAuthChecked] = useState(false);
const [authed, setAuthed] = useState(false);
@@ -60,11 +78,28 @@ function AuthBoundary() {
useEffect(() => {
(async () => {
const ok = await client.status();
let ok = await client.status();
// #194: `?token=<password>` in the URL logs in without typing the
// password. Only attempted when no stored token already authed us; the
// value is the WebUI login password (verified by /api/login server-side,
// so a wrong one just falls through to the login page). The param is
// consumed once and stripped from the URL first — a password in the
// address bar leaks via browser history / access logs / the Referer.
let urlPassword: string | undefined;
if (!ok) {
const pw = consumeUrlToken();
if (pw) {
const result = await client.login(pw);
if (result.ok) { ok = true; urlPassword = pw; }
}
}
if (ok) {
setAuthed(true);
setStatus('已连接');
setMustChange(await client.mustChangePassword());
// Carry the URL password into the forced change-password gate so it
// needn't re-prompt for the old password (matches the login flow).
if (urlPassword) setLoginPassword(urlPassword);
await refreshAgreements();
}
setAuthChecked(true);
@@ -25,6 +25,9 @@ const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2p
// positives just add one extra click; false negatives skip a confirm — both low
// stakes (the amber banner already warns that any write is real).
const DESTRUCTIVE_RE = /(kick|ban|mute|recall|withdraw|delete|del_|dismiss|disband|leave|quit|remove|revoke)/i;
// Cap retained stream frames so a long-running / runaway stream can't grow the
// array and DOM without bound. Generous enough to keep a full normal stream.
const MAX_STREAM_FRAMES = 2000;
function qqAvatarUrl(uin: string) {
return `/avatar/${encodeURIComponent(uin)}`;
@@ -136,7 +139,7 @@ export function ActionTester({ accounts, docs, presetAction }: { accounts: QQInf
try {
await api.debug.invokeStream(uin, actionName.trim(), params, (frame) => {
last = frame;
setFrames((prev) => [...prev, frame]);
setFrames((prev) => (prev.length >= MAX_STREAM_FRAMES ? [...prev.slice(-(MAX_STREAM_FRAMES - 1)), frame] : [...prev, frame]));
const d = frame.data as { type?: string; progress?: number; transferred?: number; total?: number } | undefined;
if (d && typeof d.progress === 'number') tasks.update(taskId, { progress: d.progress });
else if (d && typeof d.transferred === 'number' && typeof d.total === 'number' && d.total > 0) tasks.update(taskId, { progress: d.transferred / d.total });
@@ -14,7 +14,7 @@ import type { DebugStreamMessage } from '@/types';
const STREAM_CAP = 300;
const cardCls = 'rounded-2xl border border-border/60 bg-card/80 shadow-[0_1px_2px_rgb(0_0_0/0.04),0_8px_24px_-12px_rgb(0_0_0/0.10)] backdrop-blur-sm';
interface StreamRow { id: number; at: number; msg: Extract<DebugStreamMessage, { kind: 'event' | 'action' | 'dropped' }> }
interface StreamRow { id: number; at: number; msg: Extract<DebugStreamMessage, { kind: 'event' | 'action' | 'dropped' }>; search: string }
function IconBtn({ onClick, title, children }: { onClick: () => void; title: string; children: ReactNode }) {
return (
@@ -103,7 +103,9 @@ export function LiveActivity() {
(m) => {
if (m.kind === 'ready' || pausedRef.current) return;
setRows((prev) => {
const next = [{ id: idRef.current++, at: Date.now(), msg: m }, ...prev];
// Precompute the search haystack once at enqueue, so filtering never
// re-stringifies every row on each keystroke.
const next = [{ id: idRef.current++, at: Date.now(), msg: m, search: JSON.stringify(m).toLowerCase() }, ...prev];
return next.length > STREAM_CAP ? next.slice(0, STREAM_CAP) : next;
});
},
@@ -119,7 +121,7 @@ export function LiveActivity() {
if (!q) return true;
if (r.msg.kind === 'dropped') return false;
const { label } = rowLabel(r.msg);
return label.toLowerCase().includes(q) || r.msg.uin.includes(q) || JSON.stringify(r.msg).toLowerCase().includes(q);
return label.toLowerCase().includes(q) || r.msg.uin.includes(q) || r.search.includes(q);
});
}, [rows, kindFilter, query]);
@@ -13,13 +13,17 @@ import { useApi } from '@/lib/api';
import { useTheme } from '@/contexts/ThemeContext';
import { useLayout } from '@/contexts/LayoutContext';
// Dedicated log-level text tokens (see index.css): the app accent colors are
// too light as small text on the light canvas (WCAG AA fails), so these hit
// >=4.5:1 in light mode while keeping the bright values in dark. trace stays the
// faintest level (dimmer than debug) but at /90 it now also clears AA.
const levelClass: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
trace: 'text-muted-foreground/90',
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
warn: 'text-warning',
error: 'text-destructive',
info: 'text-log-info',
success: 'text-log-success',
warn: 'text-log-warn',
error: 'text-log-error',
};
const LEVELS: LogLevel[] = ['trace', 'debug', 'info', 'success', 'warn', 'error'];
@@ -141,9 +145,27 @@ export function LogsPage() {
}, [api, serverLevel, levelBusy]);
useEffect(() => {
return api.logs.stream({
// Batch incoming lines: buffer in a ref and flush on a ~80ms timer instead
// of a per-line setState. Under a high log rate this turns N O(n) array
// copies + N React commits per window into one. Dedup-by-id and the
// maxLines cap are preserved (a reconnect can replay recent ids).
let pending: LogEntry[] = [];
let flushTimer: number | null = null;
const flush = () => {
flushTimer = null;
if (pending.length === 0) return;
const batchMap = new Map(pending.map((e) => [e.id, e] as const));
pending = [];
setLogs((prev) => {
const kept = prev.length ? prev.filter((it) => !batchMap.has(it.id)) : prev;
const merged = kept.length ? [...kept, ...batchMap.values()] : [...batchMap.values()];
return merged.length > maxLinesRef.current ? merged.slice(-maxLinesRef.current) : merged;
});
};
const dispose = api.logs.stream({
onLine: (entry) => {
setLogs((prev) => [...prev.filter((it) => it.id !== entry.id), entry].slice(-maxLinesRef.current));
pending.push(entry);
if (flushTimer == null) flushTimer = window.setTimeout(flush, 80);
},
onStatus: (s) => {
if (s === 'open') setStreamStatus('实时');
@@ -151,6 +173,10 @@ export function LogsPage() {
else setStreamStatus('已断开');
},
});
return () => {
dispose();
if (flushTimer != null) clearTimeout(flushTimer);
};
}, [api]);
useEffect(() => {
@@ -889,13 +889,16 @@ function AccountWidget({ config }: { config: AccountConfig }) {
// ─────────────── recent alerts ───────────────
// Same WCAG-tuned log-level text tokens as the logs page (see index.css / the
// levelClass note there): the raw accent colors fail AA as small text on the
// light canvas.
const ALERT_LEVEL_CLASS: Record<LogLevel, string> = {
trace: 'text-muted-foreground/60',
trace: 'text-muted-foreground/90',
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
warn: 'text-warning',
error: 'text-destructive',
info: 'text-log-info',
success: 'text-log-success',
warn: 'text-log-warn',
error: 'text-log-error',
};
function RecentAlertsCard({ config }: { config: AlertsConfig }) {
+18 -10
View File
@@ -66,12 +66,18 @@ function Node({ k, value, depth, defaultOpen }: { k?: string; value: unknown; de
);
}
const entries = Array.isArray(value)
? value.map((v, i) => [String(i), v] as const)
: Object.entries(value as Record<string, unknown>);
const openB = Array.isArray(value) ? '[' : '{';
const closeB = Array.isArray(value) ? ']' : '}';
const shown = open ? Math.min(entries.length, limit) : 0;
const isArr = Array.isArray(value);
const count = isArr ? (value as unknown[]).length : Object.keys(value as object).length;
const openB = isArr ? '[' : '{';
const closeB = isArr ? ']' : '}';
const shown = open ? Math.min(count, limit) : 0;
// Only materialise child entries when expanded — a deep tree has many
// collapsed nodes, and enumerating each on every render is wasted work.
const entries: ReadonlyArray<readonly [string, unknown]> = open
? (isArr
? (value as unknown[]).map((v, i) => [String(i), v] as const)
: Object.entries(value as Record<string, unknown>))
: [];
return (
<div>
@@ -84,21 +90,21 @@ function Node({ k, value, depth, defaultOpen }: { k?: string; value: unknown; de
<ChevronRight className={cn('h-3 w-3 shrink-0 text-muted-foreground/60 transition-transform', open && 'rotate-90')} />
{keyLabel}
<Punct>{openB}</Punct>
{!open && <span className="text-muted-foreground/50">{entries.length}{Array.isArray(value) ? '' : ' keys'}<Punct>{closeB}</Punct></span>}
{!open && <span className="text-muted-foreground/50">{count}{isArr ? '' : ' keys'}<Punct>{closeB}</Punct></span>}
</button>
{open && (
<>
{entries.slice(0, shown).map(([ck, cv]) => (
<Node key={ck} k={Array.isArray(value) ? undefined : ck} value={cv} depth={depth + 1} defaultOpen={depth < 1} />
))}
{entries.length > shown && (
{count > shown && (
<button
type="button"
onClick={() => setLimit((l) => l + 500)}
className="py-0.5 text-[11px] text-primary hover:underline"
style={{ paddingLeft: `${depth * 0.9 + 1.1}rem` }}
>
还有 {entries.length - shown} 项,点击展开…
还有 {count - shown} 项,点击展开…
</button>
)}
<div style={{ paddingLeft: `${depth * 0.9 + 0.9}rem` }}><Punct>{closeB}</Punct></div>
@@ -110,9 +116,11 @@ function Node({ k, value, depth, defaultOpen }: { k?: string; value: unknown; de
export function JsonTree({ data, className, maxHeight = '20rem' }: { data: unknown; className?: string; maxHeight?: string }) {
const [copied, setCopied] = useState(false);
const text = (() => { try { return JSON.stringify(data, null, 2); } catch { return String(data); } })();
const copy = async () => {
// Stringify lazily, only on an actual copy — not on every render (a large
// payload would otherwise re-serialise the whole tree each commit).
const text = (() => { try { return JSON.stringify(data, null, 2); } catch { return String(data); } })();
try {
if (navigator.clipboard?.writeText) {
await navigator.clipboard.writeText(text);
+21
View File
@@ -37,6 +37,16 @@
--success: oklch(70% 0.15 160);
--warning: oklch(78% 0.16 80);
/* Log-level TEXT colors. The accent tokens above are tuned as fills (white
text on them passes AA); as small text on the light canvas they fail WCAG
AA (info 2.6:1, success 2.4:1, warn 2.0:1, error 4.3:1). These darker
variants restore >=4.5:1 for the log viewer without darkening the app-wide
accent. Dark theme keeps the bright values (they already pass on dark). */
--log-info: oklch(50% 0.155 230);
--log-success: oklch(50% 0.15 160);
--log-warn: oklch(52% 0.16 80);
--log-error: oklch(55% 0.22 27);
--border: oklch(92% 0.01 240);
--input: oklch(94% 0.012 240);
--ring: oklch(68.5% 0.155 230);
@@ -79,6 +89,13 @@
--success: oklch(72% 0.15 160);
--warning: oklch(80% 0.16 80);
/* On the dark canvas the bright accents already clear AA as text, so the
log-level text tokens mirror them (see the :root note above). */
--log-info: oklch(75% 0.14 230);
--log-success: oklch(72% 0.15 160);
--log-warn: oklch(80% 0.16 80);
--log-error: oklch(62% 0.2 27);
--border: oklch(28% 0.02 250);
--input: oklch(26% 0.02 250);
--ring: oklch(75% 0.14 230);
@@ -112,6 +129,10 @@
--color-destructive-foreground: var(--destructive-foreground);
--color-success: var(--success);
--color-warning: var(--warning);
--color-log-info: var(--log-info);
--color-log-success: var(--log-success);
--color-log-warn: var(--log-warn);
--color-log-error: var(--log-error);
--color-border: var(--border);
--color-input: var(--input);
--color-ring: var(--ring);
+30 -6
View File
@@ -140,18 +140,31 @@ export function AppLayout() {
useEffect(() => {
if (pollInterval <= 0) return;
let cancelled = false;
let running = false;
const reconcileMs = Math.max(pollInterval * 10, 10_000);
const tick = async () => {
if (cancelled) return;
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
// Skip while the tab is hidden — SSE already carries live updates, and a
// backgrounded tab has no UI to refresh. Re-tick on becoming visible.
// `running` drops a tick while the previous refresh is still in flight,
// so a slow backend can't stack overlapping requests.
if (cancelled || document.hidden || running) return;
running = true;
try {
await Promise.all([refreshQqList(), refreshProcesses(), refreshConnections()]);
} finally {
running = false;
}
};
// Initial tick primes the lists before the SSE handshake completes
// (avoids a flash of empty state in the chrome).
tick();
const interval = setInterval(tick, reconcileMs);
const onVisible = () => { if (!document.hidden) void tick(); };
document.addEventListener('visibilitychange', onVisible);
return () => {
cancelled = true;
clearInterval(interval);
document.removeEventListener('visibilitychange', onVisible);
};
}, [pollInterval, refreshQqList, refreshProcesses, refreshConnections]);
@@ -163,15 +176,20 @@ export function AppLayout() {
useEffect(() => {
if (pollInterval <= 0) return;
let cancelled = false;
let running = false;
const tick = async () => {
if (cancelled) return;
await refreshSystem();
if (cancelled || document.hidden || running) return;
running = true;
try { await refreshSystem(); } finally { running = false; }
};
tick();
const interval = setInterval(tick, pollInterval);
const onVisible = () => { if (!document.hidden) void tick(); };
document.addEventListener('visibilitychange', onVisible);
return () => {
cancelled = true;
clearInterval(interval);
document.removeEventListener('visibilitychange', onVisible);
};
}, [pollInterval, refreshSystem]);
@@ -179,8 +197,14 @@ export function AppLayout() {
// list-polling above — GitHub's API is rate-limited, the result rarely
// changes, and the server caches it anyway, so this is cheap.
useEffect(() => {
refreshUpdate();
const id = setInterval(() => refreshUpdate(), 6 * 60 * 60 * 1000);
let running = false;
const tick = async () => {
if (running) return;
running = true;
try { await refreshUpdate(); } finally { running = false; }
};
tick();
const id = setInterval(tick, 6 * 60 * 60 * 1000);
return () => clearInterval(id);
}, [refreshUpdate]);
+276 -244
View File
File diff suppressed because it is too large. Load diff