diff --git a/.github/workflows/dev-build.yml b/.github/workflows/dev-build.yml index 4a46e070..5ee803e0 100644 --- a/.github/workflows/dev-build.yml +++ b/.github/workflows/dev-build.yml @@ -143,6 +143,9 @@ jobs: working-directory: dist run: npm install --omit=dev + - name: Verify release layout + run: pnpm check:release-layout + # Naming convention: # SnowLuma-dev-.zip|tar.gz – zero-install (node bundled) # SnowLuma-dev--lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+) diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e9f9a78f..0b931d7e 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -96,6 +96,9 @@ jobs: working-directory: dist run: npm install --omit=dev + - name: Verify release layout + run: pnpm check:release-layout + # Naming convention: # SnowLuma--.zip|tar.gz – zero-install (node bundled) # SnowLuma---lite.zip|tar.gz – user provides Node 22.13+ (23.x requires 23.4+) diff --git a/package.json b/package.json index 10949c9b..047520bc 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "snowluma-monorepo", - "version": "1.14.0", + "version": "1.14.1", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", @@ -11,6 +11,7 @@ "build:webui": "pnpm --filter webui build", "build:mcp": "pnpm --filter @snowluma/mcp build", "build:all": "pnpm --filter @snowluma/core build:all && pnpm --filter @snowluma/sdk build && pnpm --filter @snowluma/mcp build && pnpm --filter @snowluma/ui build && pnpm --filter webui build", + "check:release-layout": "node tools/check-release-layout.mjs", "dev": "pnpm --filter @snowluma/core dev", "dev:mode": "cd dist && cross-env SNOWLUMA_DEV_MODE=1 SNOWLUMA_DEV_WEBUI=1 node index.mjs", "dev:web": "pnpm --filter webui dev", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index d11c54c8..5212bf77 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/bridge", - "version": "1.14.0", + "version": "1.14.1", "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).", diff --git a/packages/common/package.json b/packages/common/package.json index 400e264a..88ad5c23 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/common", - "version": "1.14.0", + "version": "1.14.1", "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).", diff --git a/packages/core/package.json b/packages/core/package.json index 9f30c186..f30703ec 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/core", - "version": "1.14.0", + "version": "1.14.1", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/core/src/bridge/apis/contacts.ts b/packages/core/src/bridge/apis/contacts.ts index 94ae7a0c..861ce2f8 100644 --- a/packages/core/src/bridge/apis/contacts.ts +++ b/packages/core/src/bridge/apis/contacts.ts @@ -293,6 +293,7 @@ export class ContactsApi { // 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 || '', + allMuted: (raw.info?.shutUpAllTimestamp ?? 0) > 0, }); } this.ctx.identity.rememberGroups(groups); @@ -323,6 +324,7 @@ export class ContactsApi { createTime: Number(r.createTime ?? 0n), level: Number(r.level ?? 0n), memo: r.noticePreview ?? '', + allMuted: (r.shutUpAllTimestamp ?? 0) > 0, }; } diff --git a/packages/core/src/bridge/apis/index.ts b/packages/core/src/bridge/apis/index.ts index 91aa3898..acd37f31 100644 --- a/packages/core/src/bridge/apis/index.ts +++ b/packages/core/src/bridge/apis/index.ts @@ -14,6 +14,7 @@ import { MiscApi } from './misc'; import { ProfileApi } from './profile'; import { QzoneApi } from './qzone'; import { WebApi } from './web'; +import { SystemFaceApi } from './system-face'; export interface ApiHub { /** Personal QQ collections: authenticated list retrieval and pagination. */ @@ -46,6 +47,8 @@ export interface ApiHub { readonly extras: ExtrasApi; /** Cookie-backed HTTP: essence / honor / notice / client-key / csrf-token. */ readonly web: WebApi; + /** QQ system-face directory: durable catalog, id lookup, and search. */ + readonly systemFace: SystemFaceApi; } /** @@ -73,6 +76,7 @@ export function buildApiHub(ctx: BridgeContext): ApiHub { misc: new MiscApi(ctx), extras: new ExtrasApi(ctx), web: new WebApi(ctx), + systemFace: new SystemFaceApi(ctx), }; } @@ -101,3 +105,4 @@ export { ProfileApi } from './profile'; export { QzoneApi } from './qzone'; export { FlashTransferApi, type FlashFileInfo } from './flash-transfer'; export { WebApi } from './web'; +export { SystemFaceApi } from './system-face'; diff --git a/packages/core/src/bridge/apis/system-face.ts b/packages/core/src/bridge/apis/system-face.ts new file mode 100644 index 00000000..6a1964be --- /dev/null +++ b/packages/core/src/bridge/apis/system-face.ts @@ -0,0 +1,35 @@ +import { + sysFaceStore, + type SysFaceEntry, + type SysFacePackEntry, +} from '@snowluma/protocol/sys-face-store'; +import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces'; +import type { BridgeContext } from '../bridge-context'; + +/** QQ's account-independent system-face directory. The shared store owns + * persistence and refresh coalescing; this API binds it to one live sender. */ +export class SystemFaceApi { + constructor(private readonly ctx: BridgeContext) {} + + fetchCatalog(refresh = false): Promise { + return sysFaceStore.getCatalog(this.ctx, refresh); + } + + async fetchFace(faceId: number, refresh = false): Promise { + if (refresh) { + await sysFaceStore.refresh(this.ctx); + return sysFaceStore.lookup(faceId); + } + return sysFaceStore.resolve(this.ctx, faceId); + } + + async search(query: string): Promise { + await sysFaceStore.ensureReady(this.ctx); + return sysFaceStore.search(query); + } + + async isSuper(faceId: number, refresh = false): Promise { + const face = await this.fetchFace(faceId, refresh); + return face !== null && isSuperFaceEntry(face); + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 46484b55..fc6258dc 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -18,6 +18,7 @@ import { workerData } from 'node:worker_threads'; import { BridgeManager } from './bridge/manager'; import { createNotificationManager } from './notifications/manager'; import { createStateWiring } from './webui/state-wiring'; +import { bindSystemFaceCatalog } from './sys-face-catalog'; const log = createLogger('App'); @@ -57,6 +58,7 @@ async function main() { cleanupInvalidPerUinConfigs(); const bridgeManager = new BridgeManager(); + bindSystemFaceCatalog(bridgeManager); const oneBotManager = new OneBotManager(); const autoLoadOnDiscovery = resolveAutoLoad(runtimeConfig.hookAutoLoad); diff --git a/packages/core/src/sys-face-catalog.ts b/packages/core/src/sys-face-catalog.ts new file mode 100644 index 00000000..e04a9f6f --- /dev/null +++ b/packages/core/src/sys-face-catalog.ts @@ -0,0 +1,40 @@ +import path from 'node:path'; +import { createLogger } from '@snowluma/common/logger'; +import { + SysFaceStore, + sysFaceStore, + type SysFaceCatalogStorage, +} from '@snowluma/protocol/sys-face-store'; +import { JsonSysFaceCatalogStorage } from '@snowluma/protocol/sys-face-storage'; +import type { BridgeManager } from './bridge/manager'; + +const log = createLogger('SysFace'); + +export interface SystemFaceCatalogBindingOptions { + store?: SysFaceStore; + storage?: SysFaceCatalogStorage; + dataRoot?: string; +} + +/** Attach the shared system-face catalog to Bridge login edges. The first + * account restores + refreshes it; later accounts reuse the same result. */ +export function bindSystemFaceCatalog( + manager: BridgeManager, + options: SystemFaceCatalogBindingOptions = {}, +): void { + const store = options.store ?? sysFaceStore; + const storage = options.storage ?? new JsonSysFaceCatalogStorage( + path.join(options.dataRoot ?? 'data', 'sys-face-catalog.json'), + ); + store.configureStorage(storage); + + manager.addSessionStartedListener((uin, bridge) => { + void store.prewarm(bridge).catch((error) => { + log.error( + 'system face catalog login prewarm failed: uin=%s error=%s', + uin, + error instanceof Error ? (error.stack ?? error.message) : String(error), + ); + }); + }); +} diff --git a/packages/core/src/webui/debug-tools.ts b/packages/core/src/webui/debug-tools.ts index 05cfd59e..66a62030 100644 --- a/packages/core/src/webui/debug-tools.ts +++ b/packages/core/src/webui/debug-tools.ts @@ -23,7 +23,7 @@ import { traceWebuiMutationRequestChunk } from './mutation-trace'; /** Temp dir for browser→server uploads. Siblings the Stream API's temp root but * kept distinct so the two cleanup stories don't entangle. */ -export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'snowluma-debug-upload'); +export const DEBUG_UPLOAD_DIR = path.join(os.tmpdir(), 'webui-upload'); /** Hard ceiling on a single upload. Mirrors the Stream API's upload cap. */ export const MAX_UPLOAD_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB diff --git a/packages/core/tests/actions/contacts.test.ts b/packages/core/tests/actions/contacts.test.ts index 8c15cf1f..92a7fec5 100644 --- a/packages/core/tests/actions/contacts.test.ts +++ b/packages/core/tests/actions/contacts.test.ts @@ -7,6 +7,7 @@ import type { OidbFriend, OidbFriendCategory, OidbRobotUinRangeResponse, + OidbSvcTrpcTcp0x88D_0Response, OidbSvcTrpcTcp0xFD4_1Response, OidbSvcTrpcTcp0xFE5_2Response, OidbSvcTrpcTcp0xFE7_3Response, @@ -99,6 +100,18 @@ function groupListPacket(body: OidbSvcTrpcTcp0xFE5_2Response): SendPacketResult }; } +function groupDetailPacket(body: OidbSvcTrpcTcp0x88D_0Response): SendPacketResult { + return { + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData: Buffer.from( + protobuf_encode>({ body }), + ), + }; +} + function apiForPages(pages: OidbSvcTrpcTcp0xFD4_1Response[]) { let index = 0; const sendRawPacket = vi.fn(async ( @@ -150,7 +163,12 @@ describe('apis/contacts / group roster', () => { const sendRawPacket = vi.fn(async () => groupListPacket({ groups: [{ groupUin: 123456789, - info: { groupName: 'Project', memberCount: 42, memberMax: 500 }, + info: { + groupName: 'Project', + memberCount: 42, + memberMax: 500, + shutUpAllTimestamp: 4_294_967_295, + }, customInfo: { remark: ' My Project ' }, }], })); @@ -167,9 +185,31 @@ describe('apis/contacts / group roster', () => { remark: ' My Project ', memberCount: 42, memberMax: 500, + allMuted: true, })]); expect(rememberGroups).toHaveBeenCalledWith(groups); }); + + it('maps the group-wide mute timestamp from a single-group detail', async () => { + const sendRawPacket = vi.fn(async () => groupDetailPacket({ + groupInfo: { + uin: 123456789n, + results: { + name: 'Muted Group', + shutUpAllTimestamp: 4_294_967_295, + }, + }, + })); + const api = new ContactsApi({ sendRawPacket, identity: {} } as any); + + const detail = await api.fetchGroupDetail(123456789); + + expect(detail).toEqual(expect.objectContaining({ + groupId: 123456789, + groupName: 'Muted Group', + allMuted: true, + })); + }); }); describe('apis/contacts / categorized friend roster', () => { diff --git a/packages/core/tests/element-builder.test.ts b/packages/core/tests/element-builder.test.ts index 088a7c2e..59da85b6 100644 --- a/packages/core/tests/element-builder.test.ts +++ b/packages/core/tests/element-builder.test.ts @@ -30,6 +30,7 @@ vi.mock('@snowluma/protocol/highway/video-upload', () => ({ import { buildSendElems } from '@snowluma/protocol/element-builder'; import { MessageElementValidationError } from '@snowluma/protocol/element-manifest'; import { uploadImageMsgInfo } from '@snowluma/protocol/highway/image-upload'; +import { uploadVideoMsgInfo } from '@snowluma/protocol/highway/video-upload'; const fakeBridge = {} as any; @@ -168,6 +169,63 @@ describe('element-builder / commonElem.businessType per scene', () => { }); describe('element-builder / all-message validation preflight', () => { + it('rejects hidden siblings and duplicate videos before uploading', async () => { + vi.mocked(uploadVideoMsgInfo).mockClear(); + + await expect(buildSendElems([ + { type: 'video', url: 'file:///tmp/clip.mp4' }, + { type: 'text', text: 'must not become hidden content' }, + ], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'video', + message: expect.stringContaining('only segment'), + }); + + await expect(buildSendElems([ + { type: 'video', url: 'file:///tmp/first.mp4' }, + { type: 'video', url: 'file:///tmp/second.mp4' }, + ], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'video', + message: expect.stringContaining('only once'), + }); + + expect(uploadVideoMsgInfo).not.toHaveBeenCalled(); + }); + + it('keeps empty canonical text invalid instead of sending it beside a video', async () => { + vi.mocked(uploadVideoMsgInfo).mockClear(); + + await expect(buildSendElems([ + { type: 'text', text: '' }, + { type: 'video', url: 'file:///tmp/clip.mp4' }, + ], { bridge: fakeBridge, groupId: 12345 })).rejects.toMatchObject({ + code: 'INVALID_FIELD', + elementType: 'text', + }); + + expect(uploadVideoMsgInfo).not.toHaveBeenCalled(); + }); + + it('applies standalone-video validation to forward nodes', async () => { + vi.mocked(uploadVideoMsgInfo).mockClear(); + + await expect(buildSendElems([ + { type: 'video', url: 'file:///tmp/clip.mp4' }, + { type: 'text', text: 'must not survive bot forwarding' }, + ], { + bridge: fakeBridge, + groupId: 12345, + forwardFake: true, + scene: 'forward', + })).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'video', + }); + + expect(uploadVideoMsgInfo).not.toHaveBeenCalled(); + }); + it('does not upload an early image when a later segment is unsendable', async () => { vi.mocked(uploadImageMsgInfo).mockClear(); diff --git a/packages/core/tests/sys-face-catalog.test.ts b/packages/core/tests/sys-face-catalog.test.ts new file mode 100644 index 00000000..ce0f68dc --- /dev/null +++ b/packages/core/tests/sys-face-catalog.test.ts @@ -0,0 +1,38 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SysFaceStore, type SysFaceCatalogStorage } from '@snowluma/protocol/sys-face-store'; +import { BridgeManager } from '../src/bridge/manager'; +import { bindSystemFaceCatalog } from '../src/sys-face-catalog'; + +const storage: SysFaceCatalogStorage = { + load: async () => null, + save: async () => {}, +}; + +describe('bindSystemFaceCatalog', () => { + it('starts one shared catalog prewarm from the first logged-in account', async () => { + let fetches = 0; + const store = new SysFaceStore({ + fetchCatalog: async () => { + fetches += 1; + return [{ + packName: '经典', + emojis: [{ + qSid: '14', qDes: '/微笑', emCode: '14', qCid: null, + aniStickerType: null, aniStickerPackId: null, aniStickerId: null, + url: null, emojiNameAlias: [], + aniStickerWidth: null, aniStickerHeight: null, + }], + }]; + }, + }); + const manager = new BridgeManager(); + bindSystemFaceCatalog(manager, { store, storage }); + + const packetSender = { sendPacket: vi.fn() } as never; + manager.onHookLogin(101, '10001', packetSender); + manager.onHookLogin(202, '20002', packetSender); + + await vi.waitFor(() => expect(fetches).toBe(1)); + expect(store.lookup(14)?.qDes).toBe('/微笑'); + }); +}); diff --git a/packages/core/tests/webui-debug-tools.test.ts b/packages/core/tests/webui-debug-tools.test.ts index aa63d7ea..8ac5076d 100644 --- a/packages/core/tests/webui-debug-tools.test.ts +++ b/packages/core/tests/webui-debug-tools.test.ts @@ -51,6 +51,10 @@ describe('safeUploadName', () => { }); describe('uploadDestPath', () => { + it('uses a neutral temporary directory name', () => { + expect(path.basename(DEBUG_UPLOAD_DIR)).toBe('webui-upload'); + }); + it('produces a unique path inside the upload dir', () => { const a = uploadDestPath('pic.png'); const b = uploadDestPath('pic.png'); diff --git a/packages/mcp/README.md b/packages/mcp/README.md index 92bea428..0d30b193 100644 --- a/packages/mcp/README.md +++ b/packages/mcp/README.md @@ -56,7 +56,7 @@ reported as MCP errors because they mean no complete stream result was committed | `SNOWLUMA_MCP_TOKEN` | Access token (sent as `Authorization: Bearer …`), if the endpoint requires one. | | `SNOWLUMA_MCP_TIMEOUT_MS` | Ordinary-action request timeout; for Stream Actions, connection timeout **and per-read idle timeout** (the idle deadline resets after every body read). Default `30000`. Invalid values fail startup. | | `SNOWLUMA_MCP_MODE` | `docs` \| `read` \| `write`. Default: `read` when an endpoint is set, else `docs`. Invalid values fail startup. | -| `SNOWLUMA_MCP_STREAM_DIR` | Directory on the MCP host for completed Stream Action downloads. Created and validated at startup. Default: `os.tmpdir()/snowluma-mcp/downloads`. | +| `SNOWLUMA_MCP_STREAM_DIR` | Directory on the MCP host for completed Stream Action downloads. Created and validated at startup. Default: `os.tmpdir()/onebot-mcp-downloads`. | | `SNOWLUMA_MCP_UPLOAD_ROOT` | Existing directory on the MCP host from which automatic uploads may read. Automatic upload is disabled when absent. | | `SNOWLUMA_MCP_MAX_STREAM_BYTES` | Per-file download/upload ceiling in bytes. Positive integer up to 4 GiB; default `4294967296`. Invalid values fail server startup. | @@ -90,7 +90,7 @@ groups, etc.). Enable deliberately: "SNOWLUMA_MCP_ENDPOINT": "http://127.0.0.1:3000/", "SNOWLUMA_MCP_TOKEN": "your-access-token", "SNOWLUMA_MCP_MODE": "write", - "SNOWLUMA_MCP_STREAM_DIR": "/var/tmp/snowluma-mcp-downloads", + "SNOWLUMA_MCP_STREAM_DIR": "/var/tmp/onebot-mcp-downloads", "SNOWLUMA_MCP_UPLOAD_ROOT": "/home/me/mcp-share" } } diff --git a/packages/mcp/package.json b/packages/mcp/package.json index b7f1be20..970e46c3 100644 --- a/packages/mcp/package.json +++ b/packages/mcp/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/mcp", - "version": "1.14.0", + "version": "1.14.1", "description": "MCP server exposing the SnowLuma OneBot action catalog (docs + JSON Schemas) and optional execution to LLM clients.", "repository": { "type": "git", diff --git a/packages/mcp/src/client.ts b/packages/mcp/src/client.ts index c80b0595..e4d6abf2 100644 --- a/packages/mcp/src/client.ts +++ b/packages/mcp/src/client.ts @@ -15,7 +15,7 @@ import { createHash, randomUUID } from 'node:crypto'; const DEFAULT_TIMEOUT_MS = 30_000; const DEFAULT_MAX_STREAM_BYTES = 4 * 1024 * 1024 * 1024; -const DEFAULT_STREAM_DIR = path.join(os.tmpdir(), 'snowluma-mcp', 'downloads'); +const DEFAULT_STREAM_DIR = path.join(os.tmpdir(), 'onebot-mcp-downloads'); const MAX_GENERIC_FRAMES = 256; const MAX_GENERIC_TEXT_BYTES = 256 * 1024; // OneBot permits a 16 MiB decoded download chunk. Base64 expands that to diff --git a/packages/mcp/src/generated/catalog.json b/packages/mcp/src/generated/catalog.json index 76014256..d3e98a53 100644 --- a/packages/mcp/src/generated/catalog.json +++ b/packages/mcp/src/generated/catalog.json @@ -2030,6 +2030,147 @@ }, "category": "扩展" }, + { + "name": "fetch_face_entity", + "aliases": [], + "summary": "按编号查询 QQ 系统表情", + "returns": "表情详情;编号不存在时返回 null。", + "returnsSchema": { + "anyOf": [ + { + "type": "object", + "properties": { + "q_sid": { + "type": "string", + "description": "表情编号" + }, + "q_des": { + "type": "string", + "description": "表情描述" + }, + "em_code": { + "type": "string" + }, + "q_cid": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_type": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_pack_id": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_id": { + "type": [ + "integer", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "emoji_name_alias": { + "type": "array", + "items": { + "type": "string" + } + }, + "ani_sticker_width": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_height": { + "type": [ + "integer", + "null" + ] + }, + "is_super": { + "type": "boolean", + "description": "是否使用超级表情格式" + } + }, + "required": [ + "q_sid", + "q_des", + "em_code", + "q_cid", + "ani_sticker_type", + "ani_sticker_pack_id", + "ani_sticker_id", + "url", + "emoji_name_alias", + "ani_sticker_width", + "ani_sticker_height", + "is_super" + ] + }, + { + "type": "null" + } + ] + }, + "readOnly": true, + "params": [ + { + "name": "face_id", + "type": "int", + "required": true, + "role": "face_id", + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "QQ 系统表情编号" + }, + { + "name": "refresh", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否强制从 QQ 刷新目录" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "face_id": { + "type": "integer", + "minimum": 0, + "description": "QQ 系统表情编号", + "x-role": "face_id" + }, + "refresh": { + "type": "boolean", + "description": "是否强制从 QQ 刷新目录", + "default": false + } + }, + "required": [ + "face_id" + ], + "additionalProperties": true + }, + "category": "系统表情" + }, { "name": "fetch_ptt_text", "aliases": [ @@ -2077,6 +2218,209 @@ }, "category": "扩展" }, + { + "name": "fetch_super_face_id", + "aliases": [], + "summary": "判断 QQ 系统表情是否使用超级表情格式", + "returns": "是否使用超级表情格式。", + "returnsSchema": { + "type": "object", + "properties": { + "is_super": { + "type": "boolean" + } + }, + "required": [ + "is_super" + ] + }, + "readOnly": true, + "params": [ + { + "name": "face_id", + "type": "int", + "required": true, + "role": "face_id", + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "QQ 系统表情编号" + }, + { + "name": "refresh", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否强制从 QQ 刷新目录" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "face_id": { + "type": "integer", + "minimum": 0, + "description": "QQ 系统表情编号", + "x-role": "face_id" + }, + "refresh": { + "type": "boolean", + "description": "是否强制从 QQ 刷新目录", + "default": false + } + }, + "required": [ + "face_id" + ], + "additionalProperties": true + }, + "category": "系统表情" + }, + { + "name": "fetch_sys_faces", + "aliases": [], + "summary": "获取 QQ 系统表情目录", + "returns": "按分组返回完整的 QQ 系统表情映射。", + "returnsSchema": { + "type": "object", + "properties": { + "packs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "pack_name": { + "type": "string" + }, + "emojis": { + "type": "array", + "items": { + "type": "object", + "properties": { + "q_sid": { + "type": "string", + "description": "表情编号" + }, + "q_des": { + "type": "string", + "description": "表情描述" + }, + "em_code": { + "type": "string" + }, + "q_cid": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_type": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_pack_id": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_id": { + "type": [ + "integer", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "emoji_name_alias": { + "type": "array", + "items": { + "type": "string" + } + }, + "ani_sticker_width": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_height": { + "type": [ + "integer", + "null" + ] + }, + "is_super": { + "type": "boolean", + "description": "是否使用超级表情格式" + } + }, + "required": [ + "q_sid", + "q_des", + "em_code", + "q_cid", + "ani_sticker_type", + "ani_sticker_pack_id", + "ani_sticker_id", + "url", + "emoji_name_alias", + "ani_sticker_width", + "ani_sticker_height", + "is_super" + ] + } + } + }, + "required": [ + "pack_name", + "emojis" + ] + } + } + }, + "required": [ + "packs" + ] + }, + "readOnly": true, + "params": [ + { + "name": "refresh", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否强制从 QQ 刷新目录" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "refresh": { + "type": "boolean", + "description": "是否强制从 QQ 刷新目录", + "default": false + } + }, + "additionalProperties": true + }, + "category": "系统表情" + }, { "name": "forward_friend_single_msg", "aliases": [], @@ -3799,6 +4143,59 @@ "name": "get_group_detail_info", "aliases": [], "summary": "获取群详细信息", + "returnsSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "description": "群号" + }, + "group_name": { + "type": "string", + "description": "群名" + }, + "group_remark": { + "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": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" + } + }, + "required": [ + "group_id", + "group_name", + "group_remark", + "member_count", + "max_member_count", + "group_all_shut" + ] + }, "readOnly": true, "params": [ { @@ -3810,6 +4207,15 @@ "type": "integer", "minimum": 1 } + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false } ], "invariants": [], @@ -3820,6 +4226,10 @@ "type": "integer", "minimum": 1, "x-role": "group_id" + }, + "no_cache": { + "type": "boolean", + "default": false } }, "required": [ @@ -4371,6 +4781,14 @@ "group_memo": { "type": "string", "description": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" } }, "required": [ @@ -4378,7 +4796,8 @@ "group_name", "group_remark", "member_count", - "max_member_count" + "max_member_count", + "group_all_shut" ] }, "readOnly": true, @@ -4430,6 +4849,59 @@ "name": "get_group_info_ex", "aliases": [], "summary": "获取群信息(扩展)", + "returnsSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "description": "群号" + }, + "group_name": { + "type": "string", + "description": "群名" + }, + "group_remark": { + "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": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" + } + }, + "required": [ + "group_id", + "group_name", + "group_remark", + "member_count", + "max_member_count", + "group_all_shut" + ] + }, "readOnly": true, "params": [ { @@ -4441,6 +4913,15 @@ "type": "integer", "minimum": 1 } + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false } ], "invariants": [], @@ -4451,6 +4932,10 @@ "type": "integer", "minimum": 1, "x-role": "group_id" + }, + "no_cache": { + "type": "boolean", + "default": false } }, "required": [ @@ -4501,6 +4986,14 @@ "group_memo": { "type": "string", "description": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" } }, "required": [ @@ -4508,7 +5001,8 @@ "group_name", "group_remark", "member_count", - "max_member_count" + "max_member_count", + "group_all_shut" ] } }, @@ -4586,6 +5080,10 @@ "type": "integer", "description": "最后发言时间戳(秒)" }, + "shut_up_timestamp": { + "type": "integer", + "description": "禁言结束时间戳(秒,未禁言时为 0)" + }, "level": { "type": "string", "description": "群等级" @@ -4741,6 +5239,10 @@ "type": "integer", "description": "最后发言时间戳(秒)" }, + "shut_up_timestamp": { + "type": "integer", + "description": "禁言结束时间戳(秒,未禁言时为 0)" + }, "level": { "type": "string", "description": "群等级" @@ -7373,6 +7875,134 @@ }, "category": "扩展" }, + { + "name": "search_sys_faces", + "aliases": [], + "summary": "搜索 QQ 系统表情", + "returns": "匹配编号、名称、别名或分组名的表情列表。", + "returnsSchema": { + "type": "object", + "properties": { + "faces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "q_sid": { + "type": "string", + "description": "表情编号" + }, + "q_des": { + "type": "string", + "description": "表情描述" + }, + "em_code": { + "type": "string" + }, + "q_cid": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_type": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_pack_id": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_id": { + "type": [ + "integer", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "emoji_name_alias": { + "type": "array", + "items": { + "type": "string" + } + }, + "ani_sticker_width": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_height": { + "type": [ + "integer", + "null" + ] + }, + "is_super": { + "type": "boolean", + "description": "是否使用超级表情格式" + } + }, + "required": [ + "q_sid", + "q_des", + "em_code", + "q_cid", + "ani_sticker_type", + "ani_sticker_pack_id", + "ani_sticker_id", + "url", + "emoji_name_alias", + "ani_sticker_width", + "ani_sticker_height", + "is_super" + ] + } + } + }, + "required": [ + "faces" + ] + }, + "readOnly": true, + "params": [ + { + "name": "query", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + }, + "desc": "编号、名称、别名或分组名" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "description": "编号、名称、别名或分组名" + } + }, + "required": [ + "query" + ], + "additionalProperties": true + }, + "category": "系统表情" + }, { "name": "send_ark_share", "aliases": [], @@ -11049,6 +11679,10 @@ "category": "空间", "count": 9 }, + { + "category": "系统表情", + "count": 4 + }, { "category": "流式接口", "count": 6 diff --git a/packages/mcp/src/generated/catalog.ts b/packages/mcp/src/generated/catalog.ts index 74bcd7d2..1825618e 100644 --- a/packages/mcp/src/generated/catalog.ts +++ b/packages/mcp/src/generated/catalog.ts @@ -2033,6 +2033,147 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "fetch_face_entity", + "aliases": [], + "summary": "按编号查询 QQ 系统表情", + "returns": "表情详情;编号不存在时返回 null。", + "returnsSchema": { + "anyOf": [ + { + "type": "object", + "properties": { + "q_sid": { + "type": "string", + "description": "表情编号" + }, + "q_des": { + "type": "string", + "description": "表情描述" + }, + "em_code": { + "type": "string" + }, + "q_cid": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_type": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_pack_id": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_id": { + "type": [ + "integer", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "emoji_name_alias": { + "type": "array", + "items": { + "type": "string" + } + }, + "ani_sticker_width": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_height": { + "type": [ + "integer", + "null" + ] + }, + "is_super": { + "type": "boolean", + "description": "是否使用超级表情格式" + } + }, + "required": [ + "q_sid", + "q_des", + "em_code", + "q_cid", + "ani_sticker_type", + "ani_sticker_pack_id", + "ani_sticker_id", + "url", + "emoji_name_alias", + "ani_sticker_width", + "ani_sticker_height", + "is_super" + ] + }, + { + "type": "null" + } + ] + }, + "readOnly": true, + "params": [ + { + "name": "face_id", + "type": "int", + "required": true, + "role": "face_id", + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "QQ 系统表情编号" + }, + { + "name": "refresh", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否强制从 QQ 刷新目录" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "face_id": { + "type": "integer", + "minimum": 0, + "description": "QQ 系统表情编号", + "x-role": "face_id" + }, + "refresh": { + "type": "boolean", + "description": "是否强制从 QQ 刷新目录", + "default": false + } + }, + "required": [ + "face_id" + ], + "additionalProperties": true + }, + "category": "系统表情" + }, { "name": "fetch_ptt_text", "aliases": [ @@ -2080,6 +2221,209 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "fetch_super_face_id", + "aliases": [], + "summary": "判断 QQ 系统表情是否使用超级表情格式", + "returns": "是否使用超级表情格式。", + "returnsSchema": { + "type": "object", + "properties": { + "is_super": { + "type": "boolean" + } + }, + "required": [ + "is_super" + ] + }, + "readOnly": true, + "params": [ + { + "name": "face_id", + "type": "int", + "required": true, + "role": "face_id", + "schema": { + "type": "integer", + "minimum": 0 + }, + "desc": "QQ 系统表情编号" + }, + { + "name": "refresh", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否强制从 QQ 刷新目录" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "face_id": { + "type": "integer", + "minimum": 0, + "description": "QQ 系统表情编号", + "x-role": "face_id" + }, + "refresh": { + "type": "boolean", + "description": "是否强制从 QQ 刷新目录", + "default": false + } + }, + "required": [ + "face_id" + ], + "additionalProperties": true + }, + "category": "系统表情" + }, + { + "name": "fetch_sys_faces", + "aliases": [], + "summary": "获取 QQ 系统表情目录", + "returns": "按分组返回完整的 QQ 系统表情映射。", + "returnsSchema": { + "type": "object", + "properties": { + "packs": { + "type": "array", + "items": { + "type": "object", + "properties": { + "pack_name": { + "type": "string" + }, + "emojis": { + "type": "array", + "items": { + "type": "object", + "properties": { + "q_sid": { + "type": "string", + "description": "表情编号" + }, + "q_des": { + "type": "string", + "description": "表情描述" + }, + "em_code": { + "type": "string" + }, + "q_cid": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_type": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_pack_id": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_id": { + "type": [ + "integer", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "emoji_name_alias": { + "type": "array", + "items": { + "type": "string" + } + }, + "ani_sticker_width": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_height": { + "type": [ + "integer", + "null" + ] + }, + "is_super": { + "type": "boolean", + "description": "是否使用超级表情格式" + } + }, + "required": [ + "q_sid", + "q_des", + "em_code", + "q_cid", + "ani_sticker_type", + "ani_sticker_pack_id", + "ani_sticker_id", + "url", + "emoji_name_alias", + "ani_sticker_width", + "ani_sticker_height", + "is_super" + ] + } + } + }, + "required": [ + "pack_name", + "emojis" + ] + } + } + }, + "required": [ + "packs" + ] + }, + "readOnly": true, + "params": [ + { + "name": "refresh", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false, + "desc": "是否强制从 QQ 刷新目录" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "refresh": { + "type": "boolean", + "description": "是否强制从 QQ 刷新目录", + "default": false + } + }, + "additionalProperties": true + }, + "category": "系统表情" + }, { "name": "forward_friend_single_msg", "aliases": [], @@ -3802,6 +4146,59 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_detail_info", "aliases": [], "summary": "获取群详细信息", + "returnsSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "description": "群号" + }, + "group_name": { + "type": "string", + "description": "群名" + }, + "group_remark": { + "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": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" + } + }, + "required": [ + "group_id", + "group_name", + "group_remark", + "member_count", + "max_member_count", + "group_all_shut" + ] + }, "readOnly": true, "params": [ { @@ -3813,6 +4210,15 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 1 } + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false } ], "invariants": [], @@ -3823,6 +4229,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 1, "x-role": "group_id" + }, + "no_cache": { + "type": "boolean", + "default": false } }, "required": [ @@ -4374,6 +4784,14 @@ export const ACTIONS: CatalogAction[] = [ "group_memo": { "type": "string", "description": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" } }, "required": [ @@ -4381,7 +4799,8 @@ export const ACTIONS: CatalogAction[] = [ "group_name", "group_remark", "member_count", - "max_member_count" + "max_member_count", + "group_all_shut" ] }, "readOnly": true, @@ -4433,6 +4852,59 @@ export const ACTIONS: CatalogAction[] = [ "name": "get_group_info_ex", "aliases": [], "summary": "获取群信息(扩展)", + "returnsSchema": { + "type": "object", + "properties": { + "group_id": { + "type": "integer", + "description": "群号" + }, + "group_name": { + "type": "string", + "description": "群名" + }, + "group_remark": { + "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": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" + } + }, + "required": [ + "group_id", + "group_name", + "group_remark", + "member_count", + "max_member_count", + "group_all_shut" + ] + }, "readOnly": true, "params": [ { @@ -4444,6 +4916,15 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 1 } + }, + { + "name": "no_cache", + "type": "bool", + "required": false, + "schema": { + "type": "boolean" + }, + "default": false } ], "invariants": [], @@ -4454,6 +4935,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "minimum": 1, "x-role": "group_id" + }, + "no_cache": { + "type": "boolean", + "default": false } }, "required": [ @@ -4504,6 +4989,14 @@ export const ACTIONS: CatalogAction[] = [ "group_memo": { "type": "string", "description": "群简介 / 公告预览" + }, + "group_all_shut": { + "type": "integer", + "enum": [ + -1, + 0 + ], + "description": "是否开启全员禁言(-1 开启,0 关闭)" } }, "required": [ @@ -4511,7 +5004,8 @@ export const ACTIONS: CatalogAction[] = [ "group_name", "group_remark", "member_count", - "max_member_count" + "max_member_count", + "group_all_shut" ] } }, @@ -4589,6 +5083,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "description": "最后发言时间戳(秒)" }, + "shut_up_timestamp": { + "type": "integer", + "description": "禁言结束时间戳(秒,未禁言时为 0)" + }, "level": { "type": "string", "description": "群等级" @@ -4744,6 +5242,10 @@ export const ACTIONS: CatalogAction[] = [ "type": "integer", "description": "最后发言时间戳(秒)" }, + "shut_up_timestamp": { + "type": "integer", + "description": "禁言结束时间戳(秒,未禁言时为 0)" + }, "level": { "type": "string", "description": "群等级" @@ -7376,6 +7878,134 @@ export const ACTIONS: CatalogAction[] = [ }, "category": "扩展" }, + { + "name": "search_sys_faces", + "aliases": [], + "summary": "搜索 QQ 系统表情", + "returns": "匹配编号、名称、别名或分组名的表情列表。", + "returnsSchema": { + "type": "object", + "properties": { + "faces": { + "type": "array", + "items": { + "type": "object", + "properties": { + "q_sid": { + "type": "string", + "description": "表情编号" + }, + "q_des": { + "type": "string", + "description": "表情描述" + }, + "em_code": { + "type": "string" + }, + "q_cid": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_type": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_pack_id": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_id": { + "type": [ + "integer", + "null" + ] + }, + "url": { + "type": [ + "string", + "null" + ] + }, + "emoji_name_alias": { + "type": "array", + "items": { + "type": "string" + } + }, + "ani_sticker_width": { + "type": [ + "integer", + "null" + ] + }, + "ani_sticker_height": { + "type": [ + "integer", + "null" + ] + }, + "is_super": { + "type": "boolean", + "description": "是否使用超级表情格式" + } + }, + "required": [ + "q_sid", + "q_des", + "em_code", + "q_cid", + "ani_sticker_type", + "ani_sticker_pack_id", + "ani_sticker_id", + "url", + "emoji_name_alias", + "ani_sticker_width", + "ani_sticker_height", + "is_super" + ] + } + } + }, + "required": [ + "faces" + ] + }, + "readOnly": true, + "params": [ + { + "name": "query", + "type": "string", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + }, + "desc": "编号、名称、别名或分组名" + } + ], + "invariants": [], + "inputSchema": { + "type": "object", + "properties": { + "query": { + "type": "string", + "minLength": 1, + "description": "编号、名称、别名或分组名" + } + }, + "required": [ + "query" + ], + "additionalProperties": true + }, + "category": "系统表情" + }, { "name": "send_ark_share", "aliases": [], @@ -11053,6 +11683,10 @@ export const CATEGORIES: CatalogCategory[] = [ "category": "空间", "count": 9 }, + { + "category": "系统表情", + "count": 4 + }, { "category": "流式接口", "count": 6 diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 2cdf97ef..1736f0e1 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/onebot", - "version": "1.14.0", + "version": "1.14.1", "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..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/'` collapses to `import { … } from '@snowluma/onebot/'`.", diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index fe55263b..4c0a867e 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -16,6 +16,7 @@ import { type MessageMeta, } from '../types'; import { defineAction, groupAction, groupUserAction, f } from '../action-kit'; +import { groupInfoReturnsSchema } from './group-info'; import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../message-id'; const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB @@ -1852,10 +1853,14 @@ export const actions = [ name: 'get_group_info_ex', summary: '获取群信息(扩展)', readOnly: true, - params: { group_id: f.groupId() }, + returnsSchema: groupInfoReturnsSchema, + params: { + group_id: f.groupId(), + no_cache: f.bool().default(false), + }, run: async (p, ctx) => { if (ctx.getGroupInfo) { - return okResponse(await ctx.getGroupInfo(p.group_id)); + return okResponse(await ctx.getGroupInfo(p.group_id, p.no_cache)); } return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); }, @@ -1865,10 +1870,14 @@ export const actions = [ name: 'get_group_detail_info', summary: '获取群详细信息', readOnly: true, - params: { group_id: f.groupId() }, + returnsSchema: groupInfoReturnsSchema, + params: { + group_id: f.groupId(), + no_cache: f.bool().default(false), + }, run: async (p, ctx) => { if (ctx.getGroupInfo) { - return okResponse(await ctx.getGroupInfo(p.group_id)); + return okResponse(await ctx.getGroupInfo(p.group_id, p.no_cache)); } return failedResponse(RETCODE.ACTION_FAILED, 'not implemented'); }, diff --git a/packages/onebot/src/actions/group-file.ts b/packages/onebot/src/actions/group-file.ts index 8853181f..499fd750 100644 --- a/packages/onebot/src/actions/group-file.ts +++ b/packages/onebot/src/actions/group-file.ts @@ -49,7 +49,30 @@ export const actions = [ upload_file: f.bool().default(true), }, run: async (p, ctx) => { - const result = await ctx.bridge.apis.groupFile.uploadPrivate(p.user_id, p.file, p.name, p.upload_file); + const result = await ctx.bridge.apis.groupFile.uploadPrivate( + p.user_id, + p.file, + p.name, + p.upload_file, + false, + ); + if (p.upload_file) { + if (!result.fileId) throw new Error('private file upload returned no file_id'); + const uploaded = ctx.bridge.recallUploadedFile(result.fileId); + if (!uploaded || uploaded.scope !== 'private' || uploaded.userId !== p.user_id) { + throw new Error(`private file upload metadata missing for file_id ${result.fileId}`); + } + await ctx.sendPrivateMessage(p.user_id, [{ + type: 'file', + data: { + file_id: result.fileId, + name: uploaded.fileName, + file_size: uploaded.fileSize, + md5: Buffer.from(uploaded.fileMd5).toString('hex'), + file_hash: result.fileHash ?? uploaded.fileHash ?? '', + }, + }], false); + } return okResponse({ file_id: result.fileId }); }, }), diff --git a/packages/onebot/src/actions/group-info.ts b/packages/onebot/src/actions/group-info.ts index 84de2d78..3df2324f 100644 --- a/packages/onebot/src/actions/group-info.ts +++ b/packages/onebot/src/actions/group-info.ts @@ -3,6 +3,25 @@ import { asString } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; import { WebHonorType } from '@snowluma/protocol/web/group-honor'; +export const groupInfoReturnsSchema = { + type: 'object', + properties: { + group_id: { type: 'integer', description: '群号' }, + group_name: { type: 'string', description: '群名' }, + group_remark: { 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: '群简介 / 公告预览' }, + group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' }, + }, + required: [ + 'group_id', 'group_name', 'group_remark', 'member_count', + 'max_member_count', 'group_all_shut', + ], +}; + export const actions = [ defineAction({ name: 'get_group_list', @@ -22,8 +41,12 @@ export const actions = [ group_create_time: { type: 'integer', description: '建群时间戳(秒)' }, group_level: { type: 'integer', description: '群等级(列表批量场景恒 0,详见 get_group_info)' }, group_memo: { type: 'string', description: '群简介 / 公告预览' }, + group_all_shut: { type: 'integer', enum: [-1, 0], description: '是否开启全员禁言(-1 开启,0 关闭)' }, }, - required: ['group_id', 'group_name', 'group_remark', 'member_count', 'max_member_count'], + required: [ + 'group_id', 'group_name', 'group_remark', 'member_count', + 'max_member_count', 'group_all_shut', + ], }, }, params: { no_cache: f.bool().default(false) }, @@ -41,20 +64,7 @@ export const actions = [ summary: '获取群信息', readOnly: true, returns: '群信息对象。', - returnsSchema: { - type: 'object', - properties: { - group_id: { type: 'integer', description: '群号' }, - group_name: { type: 'string', description: '群名' }, - group_remark: { 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', 'group_remark', 'member_count', 'max_member_count'], - }, + returnsSchema: groupInfoReturnsSchema, params: { no_cache: f.bool().default(false) }, run: async (p, ctx) => { const groupId = p.group_id; @@ -68,6 +78,7 @@ export const actions = [ group_create_time: 0, group_level: 0, group_memo: '', + group_all_shut: 0, }; if (ctx.getGroupInfo) { const info = await ctx.getGroupInfo(groupId, noCache); @@ -96,6 +107,7 @@ export const actions = [ age: { type: 'integer', description: '年龄' }, join_time: { type: 'integer', description: '入群时间戳(秒)' }, last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' }, + shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' }, level: { type: 'string', description: '群等级' }, role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' }, title: { type: 'string', description: '专属头衔' }, @@ -135,6 +147,7 @@ export const actions = [ age: { type: 'integer', description: '年龄' }, join_time: { type: 'integer', description: '入群时间戳(秒)' }, last_sent_time: { type: 'integer', description: '最后发言时间戳(秒)' }, + shut_up_timestamp: { type: 'integer', description: '禁言结束时间戳(秒,未禁言时为 0)' }, level: { type: 'string', description: '群等级' }, role: { type: 'string', enum: ['owner', 'admin', 'member'], description: '角色' }, title: { type: 'string', description: '专属头衔' }, @@ -156,6 +169,7 @@ export const actions = [ group_id: groupId, user_id: userId, nickname: '', card: '', is_robot: false, sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, + shut_up_timestamp: 0, level: '0', role: 'member', title: '', }); } @@ -163,6 +177,7 @@ export const actions = [ group_id: groupId, user_id: userId, nickname: '', card: '', is_robot: false, sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0, + shut_up_timestamp: 0, level: '0', role: 'member', title: '', }); }, diff --git a/packages/onebot/src/actions/index.ts b/packages/onebot/src/actions/index.ts index 3a79035f..ef74f9a6 100644 --- a/packages/onebot/src/actions/index.ts +++ b/packages/onebot/src/actions/index.ts @@ -20,6 +20,7 @@ import { actions as groupAlbumActions } from './group-album'; import { actions as qzoneActions } from './qzone'; import { actions as streamFileActions } from './stream-file'; import { actions as streamDownloadActions } from './stream-download'; +import { actions as systemFaceActions } from './system-face'; export interface ActionGroup { /** Domain category (= source file), surfaced to the MCP / UI for grouping. */ @@ -196,6 +197,7 @@ export const ACTION_GROUPS: readonly ActionGroup[] = [ { category: '扩展', actions: extendedActions }, { category: '群相册', actions: groupAlbumActions }, { category: '空间', actions: qzoneActions }, + { category: '系统表情', actions: systemFaceActions }, { category: '流式接口', actions: [...streamFileActions, ...streamDownloadActions] }, ]; diff --git a/packages/onebot/src/actions/system-face.ts b/packages/onebot/src/actions/system-face.ts new file mode 100644 index 00000000..67e7d900 --- /dev/null +++ b/packages/onebot/src/actions/system-face.ts @@ -0,0 +1,137 @@ +import { isSuperFaceEntry } from '@snowluma/protocol/oidb-services/sys-faces/fetch-sys-faces'; +import type { SysFaceEntry } from '@snowluma/protocol/sys-face-store'; +import { defineAction, f } from '../action-kit'; +import { okResponse, type JsonObject } from '../types'; + +function faceEntry(face: SysFaceEntry): JsonObject { + return { + q_sid: face.qSid, + q_des: face.qDes, + em_code: face.emCode, + q_cid: face.qCid, + ani_sticker_type: face.aniStickerType, + ani_sticker_pack_id: face.aniStickerPackId, + ani_sticker_id: face.aniStickerId, + url: face.url, + emoji_name_alias: face.emojiNameAlias, + ani_sticker_width: face.aniStickerWidth, + ani_sticker_height: face.aniStickerHeight, + is_super: isSuperFaceEntry(face), + }; +} + +const refreshField = () => f.bool().default(false).describe('是否强制从 QQ 刷新目录'); +const faceIdField = () => f.faceId().describe('QQ 系统表情编号'); +const nullableInteger = { type: ['integer', 'null'] }; +const nullableString = { type: ['string', 'null'] }; +const faceSchema = { + type: 'object', + properties: { + q_sid: { type: 'string', description: '表情编号' }, + q_des: { type: 'string', description: '表情描述' }, + em_code: { type: 'string' }, + q_cid: nullableInteger, + ani_sticker_type: nullableInteger, + ani_sticker_pack_id: nullableInteger, + ani_sticker_id: nullableInteger, + url: nullableString, + emoji_name_alias: { type: 'array', items: { type: 'string' } }, + ani_sticker_width: nullableInteger, + ani_sticker_height: nullableInteger, + is_super: { type: 'boolean', description: '是否使用超级表情格式' }, + }, + required: [ + 'q_sid', 'q_des', 'em_code', 'q_cid', 'ani_sticker_type', + 'ani_sticker_pack_id', 'ani_sticker_id', 'url', 'emoji_name_alias', + 'ani_sticker_width', 'ani_sticker_height', 'is_super', + ], +}; + +export const actions = [ + defineAction({ + name: 'fetch_sys_faces', + summary: '获取 QQ 系统表情目录', + readOnly: true, + returns: '按分组返回完整的 QQ 系统表情映射。', + returnsSchema: { + type: 'object', + properties: { + packs: { + type: 'array', + items: { + type: 'object', + properties: { + pack_name: { type: 'string' }, + emojis: { type: 'array', items: faceSchema }, + }, + required: ['pack_name', 'emojis'], + }, + }, + }, + required: ['packs'], + }, + params: { refresh: refreshField() }, + run: async (params, ctx) => { + const packs = await ctx.bridge.apis.systemFace.fetchCatalog(params.refresh); + return okResponse({ + packs: packs.map((pack) => ({ + pack_name: pack.packName, + emojis: pack.emojis.map(faceEntry), + })), + }); + }, + }), + + defineAction({ + name: 'fetch_face_entity', + summary: '按编号查询 QQ 系统表情', + readOnly: true, + returns: '表情详情;编号不存在时返回 null。', + returnsSchema: { anyOf: [faceSchema, { type: 'null' }] }, + params: { + face_id: faceIdField(), + refresh: refreshField(), + }, + run: async (params, ctx) => { + const face = await ctx.bridge.apis.systemFace.fetchFace(params.face_id, params.refresh); + return okResponse(face ? faceEntry(face) : null); + }, + }), + + defineAction({ + name: 'search_sys_faces', + summary: '搜索 QQ 系统表情', + readOnly: true, + returns: '匹配编号、名称、别名或分组名的表情列表。', + returnsSchema: { + type: 'object', + properties: { faces: { type: 'array', items: faceSchema } }, + required: ['faces'], + }, + params: { + query: f.string({ allowEmpty: false }).describe('编号、名称、别名或分组名'), + }, + run: async (params, ctx) => okResponse({ + faces: (await ctx.bridge.apis.systemFace.search(params.query)).map(faceEntry), + }), + }), + + defineAction({ + name: 'fetch_super_face_id', + summary: '判断 QQ 系统表情是否使用超级表情格式', + readOnly: true, + returns: '是否使用超级表情格式。', + returnsSchema: { + type: 'object', + properties: { is_super: { type: 'boolean' } }, + required: ['is_super'], + }, + params: { + face_id: faceIdField(), + refresh: refreshField(), + }, + run: async (params, ctx) => okResponse({ + is_super: await ctx.bridge.apis.systemFace.isSuper(params.face_id, params.refresh), + }), + }), +]; diff --git a/packages/onebot/src/message-parser.ts b/packages/onebot/src/message-parser.ts index c1cb8074..87bab01f 100644 --- a/packages/onebot/src/message-parser.ts +++ b/packages/onebot/src/message-parser.ts @@ -1,6 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { MessageElement } from '@snowluma/protocol/events'; import { + assertVideoSendPolicy, assertWindowShakeSendPolicy, assertValidMessageElement, ELEMENT_MANIFEST, @@ -68,9 +69,22 @@ function normalizeSegmentType(type: string): string { return type.toLowerCase(); } -function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): string[] { +interface OutboundInputSegmentSummary { + rawTypes: string[]; + effectiveVideoTypes: string[]; +} + +function isExplicitEmptyTextPlaceholder(segment: MessageSegment): boolean { + return normalizeSegmentType(segment.type) === 'text' + && segmentPayload(segment).text === ''; +} + +function outboundInputSegmentSummary( + message: JsonValue, + autoEscape: boolean, +): OutboundInputSegmentSummary { if (typeof message === 'string') { - if (autoEscape) return ['text']; + if (autoEscape) return { rawTypes: ['text'], effectiveVideoTypes: ['text'] }; const types: string[] = []; let lastIndex = 0; for (const match of message.matchAll(CQ_REGEX)) { @@ -79,34 +93,48 @@ function outboundInputSegmentTypes(message: JsonValue, autoEscape: boolean): str lastIndex = match.index! + match[0].length; } if (lastIndex < message.length) types.push('text'); - return types; + return { rawTypes: types, effectiveVideoTypes: types }; } if (Array.isArray(message)) { - return message.flatMap((item) => { - if (typeof item !== 'object' || item === null || Array.isArray(item)) return []; + const rawTypes: string[] = []; + const effectiveVideoTypes: string[] = []; + for (const item of message) { + if (typeof item !== 'object' || item === null || Array.isArray(item)) continue; const type = (item as { type?: unknown }).type; - return typeof type === 'string' ? [normalizeSegmentType(type)] : []; - }); + if (typeof type !== 'string') continue; + const normalizedType = normalizeSegmentType(type); + rawTypes.push(normalizedType); + if (!isExplicitEmptyTextPlaceholder(item as MessageSegment)) { + effectiveVideoTypes.push(normalizedType); + } + } + return { rawTypes, effectiveVideoTypes }; } if (typeof message === 'object' && message !== null) { const type = (message as { type?: unknown }).type; - return typeof type === 'string' ? [normalizeSegmentType(type)] : []; + const types = typeof type === 'string' ? [normalizeSegmentType(type)] : []; + return { rawTypes: types, effectiveVideoTypes: types }; } - return []; + return { rawTypes: [], effectiveVideoTypes: [] }; } /** - * Reject unsupported window-shake inputs before parsers can resolve identities, - * fetch cards, sign music, or perform any other externally visible work. + * Reject unsupported message combinations before parsers can resolve + * identities, fetch cards, sign music, or perform any other externally + * visible work. */ -export function assertWindowShakeMessageInput( +export function assertOutboundMessageInput( message: JsonValue, autoEscape: boolean, scene: OutboundMessageScene, ): void { - const types = outboundInputSegmentTypes(message, autoEscape); - const shakeCount = types.filter((type) => type === 'poke' || type === 'shake').length; - assertWindowShakeSendPolicy(shakeCount, types.length, scene); + const { rawTypes, effectiveVideoTypes } = outboundInputSegmentSummary(message, autoEscape); + assertVideoSendPolicy( + effectiveVideoTypes.filter((type) => type === 'video').length, + effectiveVideoTypes.length, + ); + const shakeCount = rawTypes.filter((type) => type === 'poke' || type === 'shake').length; + assertWindowShakeSendPolicy(shakeCount, rawTypes.length, scene); } function invalidMessageShape(message: string): MessageElementValidationError { @@ -415,7 +443,7 @@ export async function parseMessage(message: JsonValue, autoEscape: boolean, opti // Some OneBot clients insert empty text between media as a separator. // Only the exact empty string is a no-op; malformed and whitespace text // must still pass through strict element validation. - if (normalizeSegmentType(seg.type) === 'text' && data.text === '') { + if (isExplicitEmptyTextPlaceholder(seg)) { log.debug('ignored explicit empty text placeholder in message segment array'); continue; } diff --git a/packages/onebot/src/modules/contact-actions.ts b/packages/onebot/src/modules/contact-actions.ts index 4f5db86e..71625b1e 100644 --- a/packages/onebot/src/modules/contact-actions.ts +++ b/packages/onebot/src/modules/contact-actions.ts @@ -68,8 +68,13 @@ export async function getGroupList( if (noCache || bridge.identity.groups.length === 0) { await bridge.apis.contacts.fetchGroupList(); } - } catch { - // Use cached data. + } catch (err) { + if (noCache) throw err; + log.warn( + 'group list refresh failed, using cached roster: uin=%s err=%s', + bridge.identity.uin, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); } return bridge.identity.groups.map(g => ({ group_id: g.groupId, @@ -83,24 +88,36 @@ export async function getGroupList( group_create_time: g.createTime ?? 0, group_level: g.level ?? 0, group_memo: g.memo ?? '', + group_all_shut: g.allMuted ? -1 : 0, })); } -// 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). +// group_level lives only in the per-group detail response. Keep its existing +// short cache, but read mutable group state from the roster refreshed above. const GROUP_LEVEL_TTL_MS = 5 * 60 * 1000; const groupLevelCache = new Map(); -async function getGroupLevel(bridge: BridgeInterface, groupId: number, noCache?: boolean): Promise { +async function getGroupLevel( + bridge: BridgeInterface, + groupId: number, + noCache?: boolean, +): Promise { if (!noCache) { - const c = groupLevelCache.get(groupId); - if (c && Date.now() - c.at < GROUP_LEVEL_TTL_MS) return c.level; + const cached = groupLevelCache.get(groupId); + if (cached && Date.now() - cached.at < GROUP_LEVEL_TTL_MS) return cached.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 { + } catch (err) { + if (noCache) throw err; + log.warn( + 'group detail refresh failed, using roster metadata: uin=%s group=%d err=%s', + bridge.identity.uin, + groupId, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); return 0; } } @@ -110,7 +127,11 @@ async function getGroupLevel(bridge: BridgeInterface, groupId: number, noCache?: // here; this only memoizes the per-id server query so a burst of invites for the // same group doesn't hammer 0x88D_0 (which would risk a rate-limit / kick). const NON_MEMBER_GROUP_TTL_MS = 5 * 60 * 1000; -const nonMemberGroupCache = new Map(); +const nonMemberGroupCache = new Map(); + +function nonMemberGroupCacheKey(bridge: BridgeInterface, groupId: number): string { + return `${bridge.identity.uin}:${groupId}`; +} export async function getGroupInfo( bridge: BridgeInterface, @@ -120,8 +141,14 @@ export async function getGroupInfo( if (noCache || !bridge.identity.findGroup(groupId)) { try { await bridge.apis.contacts.fetchGroupList(); - } catch { - // Use cached data. + } catch (err) { + if (noCache) throw err; + log.warn( + 'group list refresh failed, using cached roster: uin=%s group=%d err=%s', + bridge.identity.uin, + groupId, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); } } const g = bridge.identity.findGroup(groupId); @@ -135,13 +162,15 @@ export async function getGroupInfo( group_create_time: g.createTime ?? 0, group_level: await getGroupLevel(bridge, groupId, noCache), group_memo: g.memo ?? '', + group_all_shut: g.allMuted ? -1 : 0, }; } // Not a joined group — fall back to the by-id server lookup so a group invite // can still resolve its name. Cached with a short TTL (skipped when noCache). + const cacheKey = nonMemberGroupCacheKey(bridge, groupId); if (!noCache) { - const cached = nonMemberGroupCache.get(groupId); + const cached = nonMemberGroupCache.get(cacheKey); if (cached && Date.now() - cached.at < NON_MEMBER_GROUP_TTL_MS) return { ...cached.info }; } try { @@ -156,12 +185,19 @@ export async function getGroupInfo( group_create_time: detail.createTime ?? 0, group_level: detail.level ?? 0, group_memo: detail.memo ?? '', + group_all_shut: detail.allMuted ? -1 : 0, }; - nonMemberGroupCache.set(groupId, { info, at: Date.now() }); + nonMemberGroupCache.set(cacheKey, { info, at: Date.now() }); return { ...info }; } - } catch { - // Server lookup failed (no such group / denied) — fall through to null. + } catch (err) { + if (noCache) throw err; + log.warn( + 'non-member group lookup failed: uin=%s group=%d err=%s', + bridge.identity.uin, + groupId, + err instanceof Error ? (err.stack ?? err.message) : String(err), + ); } return null; } @@ -395,6 +431,7 @@ function formatGroupMember( age: 0, join_time: member.joinTime, last_sent_time: member.lastSentTime, + shut_up_timestamp: member.shutUpTime, level: String(member.level), role: member.role, title: member.title, diff --git a/packages/onebot/src/modules/message-actions.ts b/packages/onebot/src/modules/message-actions.ts index 79cc626e..a02889d7 100644 --- a/packages/onebot/src/modules/message-actions.ts +++ b/packages/onebot/src/modules/message-actions.ts @@ -13,7 +13,7 @@ import { privateMessageEventName, } from '../message-id'; import { - assertWindowShakeMessageInput, + assertOutboundMessageInput, MessageElementValidationError, parseMessage, } from '../message-parser'; @@ -797,7 +797,7 @@ export async function sendPrivateMessage( if (tempGroupId !== undefined && !isTempReply) { throw new Error(`cannot send to user ${userId} in group ${tempGroupId}: no such temp session`); } - assertWindowShakeMessageInput( + assertOutboundMessageInput( message, autoEscape, tempGroupId === undefined ? 'direct-private' : 'group-temp', @@ -1034,7 +1034,7 @@ export async function sendGroupMessage( message: JsonValue, autoEscape: boolean, ): Promise { - assertWindowShakeMessageInput(message, autoEscape, 'group'); + assertOutboundMessageInput(message, autoEscape, 'group'); const elements = await parseMessage(message, autoEscape, { resolveReplySequence: (replyMessageId) => { return ref.messageStore.resolveReplySequence(true, groupId, replyMessageId); @@ -1232,6 +1232,7 @@ export async function forwardSingleMessage( if (!event) throw new Error(`message not found: ${messageId}`); const content = (event.message ?? event.raw_message ?? '') as JsonValue; + assertOutboundMessageInput(content, false, 'forward'); const parsed = await parseMessage(content, false); if (parsed.length === 0) throw new Error('message has no content'); @@ -1528,7 +1529,7 @@ function assertForwardNodeMetadataIsScalar( } } -function assertNoWindowShakeInForwardInput( +function assertForwardMessageInputPolicies( ref: OneBotInstanceContext, messages: JsonValue, depth = 0, @@ -1544,7 +1545,7 @@ function assertNoWindowShakeInForwardInput( if (messageId !== 0) { const event = ref.messageStore.findEvent(messageId); if (event) { - assertWindowShakeMessageInput( + assertOutboundMessageInput( (event.message ?? event.raw_message ?? '') as JsonValue, false, 'forward', @@ -1555,9 +1556,9 @@ function assertNoWindowShakeInForwardInput( const content = (nodeData.content ?? nodeData.message ?? '') as JsonValue; if (isNestedNodeArray(content)) { - assertNoWindowShakeInForwardInput(ref, content, depth + 1); + assertForwardMessageInputPolicies(ref, content, depth + 1); } else { - assertWindowShakeMessageInput(content, false, 'forward'); + assertOutboundMessageInput(content, false, 'forward'); } } } @@ -1655,9 +1656,10 @@ async function parseForwardNodes( }); // Scan the complete raw tree before parsing any earlier node. Some segment - // codecs perform identity lookups or HTTP signing, so discovering a later - // window-shake segment during the normal loop would already be too late. - assertNoWindowShakeInForwardInput(ref, messages, depth); + // codecs perform identity lookups or HTTP signing, so discovering an + // unsupported message combination during the normal loop would already be + // too late. + assertForwardMessageInputPolicies(ref, messages, depth); const nodes: ForwardNodePayload[] = []; for (const { nodeData } of prepared) { diff --git a/packages/onebot/src/network/utils.ts b/packages/onebot/src/network/utils.ts index 031c8f5a..de27b788 100644 --- a/packages/onebot/src/network/utils.ts +++ b/packages/onebot/src/network/utils.ts @@ -131,9 +131,6 @@ export function normalizePath(pathValue: string | undefined): string { } export function parseRequestPath(urlValue: string): string { - try { - return new URL(urlValue, 'ws://127.0.0.1').pathname; - } catch { - return '/'; - } + const queryIndex = urlValue.indexOf('?'); + return queryIndex === -1 ? urlValue : urlValue.slice(0, queryIndex); } diff --git a/packages/onebot/src/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts index 773f2019..2ce9b834 100644 --- a/packages/onebot/src/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -4,8 +4,11 @@ import type { IncomingMessage } from 'node:http'; import type { DispatchPayload } from '../event-filter'; import type { JsonObject, WsServerNetwork } from '../types'; import { IOneBotNetworkAdapter, type AdapterStatus, type NetworkAdapterContext } from './adapter'; -import { normalizePath } from './utils'; -import { WsServerConnections } from './ws-server-connections'; +import { normalizePath, parseRequestPath } from './utils'; +import { + WsServerConnections, + type WsServerConnectionConfig, +} from './ws-server-connections'; const moduleLog = createLogger('OneBot.WS-Server'); @@ -17,7 +20,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx, moduleLog); - this.connections = new WsServerConnections(name, config, ctx, this.log, { + this.connections = new WsServerConnections(name, standaloneConnectionConfig(config), ctx, this.log, { frame: (event, options) => this.metaFrame(event, options), bootstrap: (options) => this.bootstrapMetaFrames(options), }); @@ -90,7 +93,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { } protected override onConfigReplaced(next: WsServerNetwork): void { - this.connections.updateConfig(next); + this.connections.updateConfig(standaloneConnectionConfig(next)); } onEvent(_event: JsonObject, payload: DispatchPayload): void { @@ -105,9 +108,22 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { wss = new WebSocketServer({ host: this.config.host ?? '0.0.0.0', port: this.config.port, - path: normalizePath(this.config.path), - verifyClient: ({ req }: { req: IncomingMessage }) => - this.connections.authorizeUpgrade(req), + verifyClient: ( + { req }: { req: IncomingMessage }, + done: (allow: boolean, code?: number, message?: string) => void, + ) => { + const requestPath = parseRequestPath(req.url ?? '/'); + if (!this.connections.acceptsUpgradePath(requestPath)) { + this.log.debug('[%s] rejected unknown WebSocket path %s', this.name, requestPath); + done(false, 400, 'Bad path for WebSocket'); + return; + } + if (!this.connections.authorizeUpgrade(req)) { + done(false, 401, 'Unauthorized'); + return; + } + done(true); + }, }); } catch (error) { this.recordTransportFailure(error); @@ -170,3 +186,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { function isAlreadyClosedError(error: Error): boolean { return (error as NodeJS.ErrnoException).code === 'ERR_SERVER_NOT_RUNNING'; } + +function standaloneConnectionConfig(config: WsServerNetwork): WsServerConnectionConfig { + return { ...config, role: config.role ?? 'Universal' }; +} diff --git a/packages/onebot/src/network/ws-server-connections.ts b/packages/onebot/src/network/ws-server-connections.ts index ff362e6d..a0721429 100644 --- a/packages/onebot/src/network/ws-server-connections.ts +++ b/packages/onebot/src/network/ws-server-connections.ts @@ -11,6 +11,7 @@ import type { JsonObject, NetworkBase, WsRole } from '../types'; import type { NetworkAdapterContext } from './adapter'; import { isAuthorized, + normalizePath, parseRequestPath, rawDataToString, safeClose, @@ -27,7 +28,7 @@ const HEARTBEAT_INTERVAL_MS = 30_000; const HEARTBEAT_MAX_MISSED = 2; const HEARTBEAT_DEAD_AFTER_S = (HEARTBEAT_INTERVAL_MS * (HEARTBEAT_MAX_MISSED + 1)) / 1000; -export type WsServerConnectionConfig = NetworkBase & { role?: WsRole }; +export type WsServerConnectionConfig = NetworkBase & { path?: string; role?: WsRole }; interface ForwardConnection { socket: WebSocket; @@ -100,6 +101,10 @@ export class WsServerConnections { if (tokenChanged) this.disconnectAll(1008, 'access token changed'); } + acceptsUpgradePath(requestPath: string): boolean { + return resolveForwardRole(requestPath, this.config) !== null; + } + onEvent(payload: DispatchPayload): void { if (!this.acceptingActions || this.connections.size === 0) return; for (const connection of this.connections.values()) { @@ -128,7 +133,13 @@ export class WsServerConnections { return; } - const role = this.config.role ?? classifyForwardRole(request); + const requestPath = parseRequestPath(request.url ?? '/'); + const role = resolveForwardRole(requestPath, this.config); + if (role === null) { + this.log.warn('[%s] rejected WebSocket path after upgrade', this.name); + safeClose(socket, 1008, 'invalid path'); + return; + } const stopHeartbeat = startHeartbeat( socket, { intervalMs: HEARTBEAT_INTERVAL_MS, maxMissed: HEARTBEAT_MAX_MISSED }, @@ -252,8 +263,24 @@ export class WsServerConnections { } } -function classifyForwardRole(request: IncomingMessage): WsRole { - const path = parseRequestPath(request.url ?? '/'); +function resolveForwardRole(requestPath: string, config: WsServerConnectionConfig): WsRole | null { + if ( + config.role !== undefined + && (!requestPath.startsWith('/') || requestPath.startsWith('//')) + ) return null; + + const path = normalizePath(requestPath); + if (config.role === undefined) return classifyForwardRole(path); + + const basePath = normalizePath(config.path); + if (path === basePath) return config.role; + if (config.role !== 'Universal' || basePath !== '/') return null; + if (path === '/api') return 'Api'; + if (path === '/event') return 'Event'; + return null; +} + +function classifyForwardRole(path: string): WsRole { if (path.endsWith('/api')) return 'Api'; if (path.endsWith('/event')) return 'Event'; return 'Universal'; diff --git a/packages/onebot/src/stream-storage.ts b/packages/onebot/src/stream-storage.ts index 4dfd96ad..59196d23 100644 --- a/packages/onebot/src/stream-storage.ts +++ b/packages/onebot/src/stream-storage.ts @@ -273,7 +273,7 @@ function resolveManagedRoot(input: string): string { return path.join(fs.realpathSync(parent), path.basename(absolute)); } -export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'snowluma-stream')); +export const streamStorage = new StreamStorage(path.join(os.tmpdir(), 'onebot-stream')); export const STREAM_ROOT = streamStorage.root; export const STREAM_UPLOAD_DIR = streamStorage.uploadDir; export const STREAM_DOWNLOAD_DIR = streamStorage.downloadDir; diff --git a/packages/onebot/tests/action-registry.test.ts b/packages/onebot/tests/action-registry.test.ts index c0b2a026..045ac1ca 100644 --- a/packages/onebot/tests/action-registry.test.ts +++ b/packages/onebot/tests/action-registry.test.ts @@ -90,9 +90,9 @@ describe('compileActionRegistry namespace conflicts', () => { }); describe('compiled production Action registry', () => { - it('preserves all 181 canonical Action docs', () => { - expect(ACTION_REGISTRY.actions).toHaveLength(181); - expect(collectActionDocs()).toHaveLength(181); + it('preserves all 185 canonical Action docs', () => { + expect(ACTION_REGISTRY.actions).toHaveLength(185); + expect(collectActionDocs()).toHaveLength(185); }); it('resolves every executable name to exactly one canonical doc', () => { diff --git a/packages/onebot/tests/contact-actions.test.ts b/packages/onebot/tests/contact-actions.test.ts index e04ed3f0..1eaf80ac 100644 --- a/packages/onebot/tests/contact-actions.test.ts +++ b/packages/onebot/tests/contact-actions.test.ts @@ -202,7 +202,7 @@ describe('onebot/contact-actions / getGroupFiles', () => { describe('onebot/contact-actions / getGroupList', () => { it('triggers fetch when the in-memory roster is empty', async () => { - const fetched = [{ ...makeGroup(100, 'Group A'), remark: '工作群' }]; + const fetched = [{ ...makeGroup(100, 'Group A'), remark: '工作群', allMuted: true }]; // `groups` starts empty; the fetch callback flips it to mimic // bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups. let groups: QQGroupInfo[] = []; @@ -219,6 +219,7 @@ describe('onebot/contact-actions / getGroupList', () => { group_remark: '工作群', member_count: 0, max_member_count: 500, group_create_time: 0, group_level: 0, group_memo: '', + group_all_shut: -1, }]); }); @@ -242,14 +243,13 @@ describe('onebot/contact-actions / getGroupList', () => { expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce(); }); - it('serves the stale cache when the fetch path throws', async () => { + it('propagates fetch failures when noCache=true', async () => { const cached = [makeGroup(400, 'Group D')]; const bridge = fakeBridge({ fetchGroupList: vi.fn(async () => { throw new Error('boom'); }), identity: fakeIdentity({ groups: cached }), }); - const out = await getGroupList(bridge, true); - expect(out[0]).toMatchObject({ group_id: 400, group_name: 'Group D' }); + await expect(getGroupList(bridge, true)).rejects.toThrow('boom'); }); }); @@ -259,6 +259,7 @@ describe('onebot/contact-actions / getGroupInfo', () => { const findGroup = vi.fn((groupId: number) => groupId === 500 ? cached : null); const bridge = fakeBridge({ fetchGroupList: vi.fn(async () => []), + fetchGroupDetail: vi.fn(async () => cached), identity: fakeIdentity({ findGroup }), }); const out = await getGroupInfo(bridge, 500); @@ -270,6 +271,38 @@ describe('onebot/contact-actions / getGroupInfo', () => { expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled(); }); + it('keeps joined-group mute state on the roster source across level-cache hits', async () => { + const cached = { ...makeGroup(510, 'Muted Group'), allMuted: true }; + const fetchGroupDetail = vi.fn(async () => ({ + ...cached, + level: 6, + allMuted: false, + })); + const bridge = fakeBridge({ + fetchGroupList: vi.fn(async () => []), + fetchGroupDetail, + identity: fakeIdentity({ findGroup: (groupId: number) => groupId === 510 ? cached : null }), + }); + + const first = await getGroupInfo(bridge, 510); + const second = await getGroupInfo(bridge, 510); + + expect(first).toMatchObject({ group_level: 6, group_all_shut: -1 }); + expect(second).toMatchObject({ group_level: 6, group_all_shut: -1 }); + expect(fetchGroupDetail).toHaveBeenCalledTimes(1); + }); + + it('propagates detail refresh failures when noCache=true', async () => { + const cached = makeGroup(520, 'Refresh Group'); + const bridge = fakeBridge({ + fetchGroupList: vi.fn(async () => [cached]), + fetchGroupDetail: vi.fn(async () => { throw new Error('detail unavailable'); }), + identity: fakeIdentity({ findGroup: (groupId: number) => groupId === 520 ? cached : null }), + }); + + await expect(getGroupInfo(bridge, 520, true)).rejects.toThrow('detail unavailable'); + }); + it('triggers fetch when the group is unknown to the cache', async () => { const cached = makeGroup(600, 'Group F'); let known = false; @@ -277,6 +310,7 @@ describe('onebot/contact-actions / getGroupInfo', () => { const fetchGroupList = vi.fn(async () => { known = true; return [cached]; }); const bridge = fakeBridge({ fetchGroupList, + fetchGroupDetail: vi.fn(async () => cached), identity: fakeIdentity({ findGroup }), }); const out = await getGroupInfo(bridge, 600); @@ -294,7 +328,10 @@ describe('onebot/contact-actions / getGroupInfo', () => { }); it('resolves a non-member group via the by-id server lookup (e.g. a group invite name)', async () => { - const fetchGroupDetail = vi.fn(async () => makeGroup(7100, '邀请来的群')); + const fetchGroupDetail = vi.fn(async () => ({ + ...makeGroup(7100, '邀请来的群'), + allMuted: true, + })); const bridge = fakeBridge({ fetchGroupList: vi.fn(async () => []), fetchGroupDetail, @@ -306,6 +343,7 @@ describe('onebot/contact-actions / getGroupInfo', () => { group_id: 7100, group_name: '邀请来的群', group_remark: '', + group_all_shut: -1, }); }); @@ -334,6 +372,36 @@ describe('onebot/contact-actions / getGroupInfo', () => { await getGroupInfo(bridge, 7300, true); expect(fetchGroupDetail).toHaveBeenCalledTimes(2); }); + + it('isolates non-member group details between accounts', async () => { + const groupId = 7400; + const firstFetch = vi.fn(async () => ({ + ...makeGroup(groupId, 'Account A View'), + allMuted: true, + })); + const secondFetch = vi.fn(async () => ({ + ...makeGroup(groupId, 'Account B View'), + allMuted: false, + })); + const firstBridge = fakeBridge({ + fetchGroupList: vi.fn(async () => []), + fetchGroupDetail: firstFetch, + identity: fakeIdentity({ uin: '10001', findGroup: () => null }), + }); + const secondBridge = fakeBridge({ + fetchGroupList: vi.fn(async () => []), + fetchGroupDetail: secondFetch, + identity: fakeIdentity({ uin: '10002', findGroup: () => null }), + }); + + const first = await getGroupInfo(firstBridge, groupId); + const second = await getGroupInfo(secondBridge, groupId); + + expect(first).toMatchObject({ group_name: 'Account A View', group_all_shut: -1 }); + expect(second).toMatchObject({ group_name: 'Account B View', group_all_shut: 0 }); + expect(firstFetch).toHaveBeenCalledOnce(); + expect(secondFetch).toHaveBeenCalledOnce(); + }); }); describe('onebot/contact-actions / getGroupMemberList', () => { diff --git a/packages/onebot/tests/forward-nested.test.ts b/packages/onebot/tests/forward-nested.test.ts index e5d18dc9..a82b9bfa 100644 --- a/packages/onebot/tests/forward-nested.test.ts +++ b/packages/onebot/tests/forward-nested.test.ts @@ -17,6 +17,7 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import type { OneBotInstanceContext } from '../src/instance-context'; import { + forwardSingleMessage, sendGroupForwardMessage, sendPrivateForwardMessage, } from '../src/modules/message-actions'; @@ -209,6 +210,58 @@ describe('forward — nested {type:"node"} content', () => { expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]); }); + it('rejects video with hidden siblings before uploading a forward', async () => { + const uploadForwardNodes = vi.fn(async () => 'RES'); + const sendGroupMessage = vi.fn(); + const bridge = fakeBridge({ + apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } }, + } as any); + const ctx = makeCtx(bridge); + + await expect(sendGroupForwardMessage(ctx, 12345, [{ + type: 'node', + data: { + user_id: 111, + nickname: 'mixed-video', + content: [ + { type: 'video', data: { file: 'https://example.com/video.mp4' } }, + { type: 'text', data: { text: 'must not survive bot forwarding' } }, + ], + }, + }] as any)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'video', + }); + + expect(uploadForwardNodes).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + + it('rejects hidden siblings before forwarding a cached video message', async () => { + const sendGroupMessage = vi.fn(); + const findVideo = vi.fn(); + const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage } } } as any); + const ctx = makeCtx(bridge); + (ctx as any).messageStore = { + findEvent: () => ({ + message: [ + { type: 'video', data: { file: 'cached-video-id' } }, + { type: 'text', data: { text: 'must not survive bot forwarding' } }, + ], + }), + }; + (ctx as any).mediaStore = { findVideo }; + + await expect(forwardSingleMessage(ctx, 77, { groupId: 12345 })) + .rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'video', + }); + + expect(findVideo).not.toHaveBeenCalled(); + expect(sendGroupMessage).not.toHaveBeenCalled(); + }); + it('rejects an unknown top-level entry before uploading valid siblings', async () => { const uploadForwardNodes = vi.fn(async () => 'RES'); const sendGroupMessage = vi.fn(); diff --git a/packages/onebot/tests/group-info-actions.test.ts b/packages/onebot/tests/group-info-actions.test.ts new file mode 100644 index 00000000..da654995 --- /dev/null +++ b/packages/onebot/tests/group-info-actions.test.ts @@ -0,0 +1,119 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { GroupMemberInfo } from '@snowluma/protocol/qq-info'; + +import { ACTION_REGISTRY } from '../src/actions'; +import { + getGroupMemberInfo as readGroupMemberInfo, + getGroupMemberList as readGroupMemberList, +} from '../src/modules/contact-actions'; + +const getGroupInfo = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_info')?.spec; +const getGroupList = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_list')?.spec; +const getGroupInfoEx = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_info_ex')?.spec; +const getGroupDetailInfo = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_detail_info')?.spec; +const getGroupMemberList = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_member_list')?.spec; +const getGroupMemberInfo = ACTION_REGISTRY.actions.find(action => action.canonical === 'get_group_member_info')?.spec; +if ( + !getGroupInfo || !getGroupList || !getGroupInfoEx || !getGroupDetailInfo + || !getGroupMemberList || !getGroupMemberInfo +) { + throw new Error('group info actions missing'); +} + +function makeMember(overrides: Partial): GroupMemberInfo { + return { + uin: 654321, + uid: 'u_member', + nickname: 'Member', + card: '', + isRobot: false, + role: 'member', + level: 1, + title: '', + joinTime: 0, + lastSentTime: 0, + shutUpTime: 0, + ...overrides, + }; +} + +describe('group information actions', () => { + it('returns and documents the group-wide mute state', async () => { + const response = await getGroupInfo.toHandler({} as any)({ group_id: 123456 }); + const infoSchema = getGroupInfo.describe().returnsSchema; + const listSchema = getGroupList.describe().returnsSchema; + + expect(response).toMatchObject({ + status: 'ok', + data: { group_id: 123456, group_all_shut: 0 }, + }); + expect(infoSchema?.properties).toHaveProperty('group_all_shut'); + expect(infoSchema?.required).toContain('group_all_shut'); + expect(listSchema?.items?.properties).toHaveProperty('group_all_shut'); + expect(listSchema?.items?.required).toContain('group_all_shut'); + }); + + it.each([ + ['get_group_info_ex', getGroupInfoEx], + ['get_group_detail_info', getGroupDetailInfo], + ])('%s exposes the shared group information result', async (_name, action) => { + const getGroupInfoResult = { + group_id: 123456, + group_name: 'Muted Group', + group_all_shut: -1, + }; + const getGroupInfoProvider = vi.fn(async () => getGroupInfoResult); + const response = await action.toHandler({ + getGroupInfo: getGroupInfoProvider, + } as any)({ group_id: 123456, no_cache: true }); + + expect(response).toMatchObject({ status: 'ok', data: getGroupInfoResult }); + expect(getGroupInfoProvider).toHaveBeenCalledWith(123456, true); + expect(action.describe().returnsSchema?.properties).toHaveProperty('group_all_shut'); + }); + + it('returns and documents member mute expiry across member actions', async () => { + const mutedUntil = 2_000_000_000; + const member = makeMember({ nickname: 'Muted Member', shutUpTime: mutedUntil }); + const bridge = { + identity: { + uin: '123456', + findGroupMember: (groupId: number, userId: number) => + groupId === 123456 && userId === member.uin ? member : null, + }, + apis: { contacts: { fetchGroupMemberList: vi.fn(async () => [member]) } }, + } as any; + const listResponse = await getGroupMemberList.toHandler({ + getGroupMemberList: (groupId: number, noCache?: boolean) => + readGroupMemberList(bridge, groupId, noCache), + } as any)({ group_id: 123456 }); + const infoResponse = await getGroupMemberInfo.toHandler({ + getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => + readGroupMemberInfo(bridge, groupId, userId, noCache), + } as any)({ group_id: 123456, user_id: member.uin }); + + expect(listResponse).toMatchObject({ + status: 'ok', + data: [{ user_id: member.uin, shut_up_timestamp: mutedUntil }], + }); + expect(infoResponse).toMatchObject({ + status: 'ok', + data: { user_id: member.uin, shut_up_timestamp: mutedUntil }, + }); + expect(getGroupMemberList.describe().returnsSchema?.items?.properties) + .toHaveProperty('shut_up_timestamp'); + expect(getGroupMemberInfo.describe().returnsSchema?.properties) + .toHaveProperty('shut_up_timestamp'); + }); + + it('returns a zero mute expiry when the member is unavailable', async () => { + const response = await getGroupMemberInfo.toHandler({ + getGroupMemberInfo: vi.fn(async () => null), + } as any)({ group_id: 123456, user_id: 654323 }); + + expect(response).toMatchObject({ + status: 'ok', + data: { user_id: 654323, shut_up_timestamp: 0 }, + }); + }); +}); diff --git a/packages/onebot/tests/message-action-validation.test.ts b/packages/onebot/tests/message-action-validation.test.ts index 4c96d209..a3662c10 100644 --- a/packages/onebot/tests/message-action-validation.test.ts +++ b/packages/onebot/tests/message-action-validation.test.ts @@ -2,12 +2,20 @@ import { describe, expect, it, vi } from 'vitest'; import type { BridgeInterface } from '../../src/bridge/bridge-interface'; import { ApiHandler, type ApiActionContext } from '../src/api-handler'; import type { OneBotInstanceContext } from '../src/instance-context'; -import { deleteMessage, sendGroupMessage, setEssenceMessage } from '../src/modules/message-actions'; +import { + deleteMessage, + sendGroupMessage, + sendPrivateMessage, + setEssenceMessage, +} from '../src/modules/message-actions'; import type { MessageMeta } from '../src/types'; -function instanceContext(sendGroup: ReturnType): OneBotInstanceContext { +function instanceContext( + sendGroup: ReturnType, + sendPrivate: ReturnType = vi.fn(), +): OneBotInstanceContext { const bridge = { - apis: { message: { sendGroup } }, + apis: { message: { sendGroup, sendPrivate } }, resolveUserUid: vi.fn(async () => 'u_peer'), } as unknown as BridgeInterface; @@ -27,6 +35,14 @@ function instanceContext(sendGroup: ReturnType): OneBotInstanceCon } describe('outbound message validation at the Action boundary', () => { + const sendReceipt = { + messageId: 1, + sequence: 100, + clientSequence: 0, + random: 1, + timestamp: 1700000000, + }; + it('returns BAD_REQUEST and performs no send when a later segment is unknown', async () => { const bridgeSend = vi.fn(); const ref = instanceContext(bridgeSend); @@ -95,6 +111,140 @@ describe('outbound message validation at the Action boundary', () => { }); expect(bridgeSend).not.toHaveBeenCalled(); }); + + it('rejects video mixed with other visible content before sending', async () => { + const bridgeSend = vi.fn(async () => sendReceipt); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [ + { type: 'video', data: { file: 'https://example.com/video.mp4' } }, + { type: 'text', data: { text: 'must not become hidden content' } }, + ], + }); + + expect(response).toMatchObject({ + status: 'failed', + retcode: 1400, + wording: expect.stringContaining('video'), + }); + expect(bridgeSend).not.toHaveBeenCalled(); + }); + + it('rejects mixed video content before resolving a later segment', async () => { + const bridgeSend = vi.fn(async () => sendReceipt); + const getGroupRecommendArk = vi.fn(async () => '{"app":"contact"}'); + const ref = instanceContext(bridgeSend); + (ref.bridge.apis as any).contacts = { getGroupRecommendArk }; + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [ + { type: 'video', data: { file: 'https://example.com/video.mp4' } }, + { type: 'contact', data: { type: 'group', id: 67890 } }, + ], + }); + + expect(response).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(getGroupRecommendArk).not.toHaveBeenCalled(); + expect(bridgeSend).not.toHaveBeenCalled(); + }); + + it('rejects multiple video segments before sending', async () => { + const bridgeSend = vi.fn(async () => sendReceipt); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [ + { type: 'video', data: { file: 'https://example.com/first.mp4' } }, + { type: 'video', data: { file: 'https://example.com/second.mp4' } }, + ], + }); + + expect(response).toMatchObject({ + status: 'failed', + retcode: 1400, + wording: expect.stringContaining('video'), + }); + expect(bridgeSend).not.toHaveBeenCalled(); + }); + + it('rejects hidden content after a video in CQ string form', async () => { + const bridgeSend = vi.fn(async () => sendReceipt); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: '[CQ:video,file=https://example.com/video.mp4]hidden text', + }); + + expect(response).toMatchObject({ status: 'failed', retcode: 1400 }); + expect(bridgeSend).not.toHaveBeenCalled(); + }); + + it('rejects video mixed with private-chat content before sending', async () => { + const privateSend = vi.fn(async () => sendReceipt); + const ref = instanceContext(vi.fn(), privateSend); + const api = new ApiHandler({ + sendPrivateMessage: (userId, message, autoEscape, tempGroupId) => + sendPrivateMessage(ref, userId, message, autoEscape, tempGroupId), + } as ApiActionContext); + + const response = await api.handle('send_private_msg', { + user_id: 67890, + message: [ + { type: 'video', data: { file: 'https://example.com/video.mp4' } }, + { type: 'text', data: { text: 'must not become hidden content' } }, + ], + }); + + expect(response).toMatchObject({ + status: 'failed', + retcode: 1400, + wording: expect.stringContaining('only segment'), + }); + expect(privateSend).not.toHaveBeenCalled(); + }); + + it('keeps exact empty text placeholders compatible with a single video', async () => { + const bridgeSend = vi.fn(async () => sendReceipt); + const ref = instanceContext(bridgeSend); + const api = new ApiHandler({ + sendGroupMessage: (groupId, message, autoEscape) => + sendGroupMessage(ref, groupId, message, autoEscape), + } as ApiActionContext); + + const response = await api.handle('send_group_msg', { + group_id: 12345, + message: [ + { type: 'text', data: { text: '' } }, + { type: 'video', data: { file: 'https://example.com/video.mp4' } }, + { type: 'text', data: { text: '' } }, + ], + }); + + expect(response).toMatchObject({ status: 'ok', retcode: 0 }); + expect(bridgeSend).toHaveBeenCalledOnce(); + expect(bridgeSend.mock.calls[0]?.[1]).toMatchObject([{ type: 'video' }]); + }); }); describe('server-sequence action validation', () => { diff --git a/packages/onebot/tests/private-window-shake.test.ts b/packages/onebot/tests/private-window-shake.test.ts index 4b94a450..2f46ffda 100644 --- a/packages/onebot/tests/private-window-shake.test.ts +++ b/packages/onebot/tests/private-window-shake.test.ts @@ -81,6 +81,22 @@ describe('private window shake messages', () => { expect(sendPrivate).not.toHaveBeenCalled(); }); + it('keeps empty text significant for the standalone window-shake policy', async () => { + const sendPrivate = vi.fn(async () => ({ ...receipt, clientSequence: 9 })); + const ctx = makeContext({ sendPrivate }); + + await expect(sendPrivateMessage(ctx, 67890, [ + { type: 'poke', data: { type: 1 } }, + { type: 'text', data: { text: '' } }, + ], false)).rejects.toMatchObject({ + code: 'UNSENDABLE_TYPE', + elementType: 'poke', + message: expect.stringContaining('only segment'), + }); + + expect(sendPrivate).not.toHaveBeenCalled(); + }); + it('rejects group window shakes before resolving an earlier segment', async () => { const sendGroup = vi.fn(async () => receipt); const ctx = makeContext({ sendGroup }); diff --git a/packages/onebot/tests/self-sent-events.test.ts b/packages/onebot/tests/self-sent-events.test.ts index 0ec9318c..3c630988 100644 --- a/packages/onebot/tests/self-sent-events.test.ts +++ b/packages/onebot/tests/self-sent-events.test.ts @@ -8,6 +8,7 @@ import { type LogEntry, } from '@snowluma/common/logger'; import type { BridgeInterface } from '../../core/src/bridge/bridge-interface'; +import { ApiHandler } from '../src/api-handler'; import { OneBotInstance } from '../src/instance'; import { buildApiContext, type OneBotInstanceContext } from '../src/instance-context'; import { hashMessageIdInt32, PRIVATE_NT_MESSAGE_EVENT } from '../src/message-id'; @@ -158,6 +159,89 @@ function privateSentEvent(overrides: JsonObject = {}): JsonObject { } describe('OneBot self-sent events', () => { + it('reports upload_private_file as a private self-sent message', async () => { + const { ctx, dispatchEvent } = makeContext(); + const handler = new ApiHandler(buildApiContext(ctx)); + + const response = await handler.handle('upload_private_file', { + user_id: PEER_ID, + file: 'base64://AQID', + name: 'inline.txt', + }); + + expect(response).toMatchObject({ + status: 'ok', + retcode: 0, + data: { file_id: 'uploaded-file-uuid' }, + }); + expect(ctx.bridge.apis.groupFile.uploadPrivate).toHaveBeenCalledWith( + PEER_ID, + 'base64://AQID', + 'inline.txt', + true, + false, + ); + expect(ctx.bridge.apis.message.sendC2cFile).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledOnce(); + expect(dispatchEvent).toHaveBeenCalledWith(expect.objectContaining({ + post_type: 'message_sent', + message_type: 'private', + self_id: SELF_ID, + user_id: SELF_ID, + target_id: PEER_ID, + message_seq: RECEIPT.clientSequence, + message: [{ + type: 'file', + data: expect.objectContaining({ + file_id: 'uploaded-file-uuid', + file: 'inline.txt', + file_size: 3, + }), + }], + }), 'send'); + }); + + it('fails upload_private_file when publishing the private file fails', async () => { + const { ctx, dispatchEvent } = makeContext(); + vi.mocked(ctx.bridge.apis.message.sendC2cFile).mockRejectedValueOnce( + new Error('private file publication rejected'), + ); + const handler = new ApiHandler(buildApiContext(ctx)); + + const response = await handler.handle('upload_private_file', { + user_id: PEER_ID, + file: 'base64://AQID', + name: 'inline.txt', + }); + + expect(response).toMatchObject({ + status: 'failed', + retcode: 100, + wording: 'private file publication rejected', + }); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + + it('does not report upload_private_file when upload_file is disabled', async () => { + const { ctx, dispatchEvent } = makeContext(); + const handler = new ApiHandler(buildApiContext(ctx)); + + const response = await handler.handle('upload_private_file', { + user_id: PEER_ID, + file: 'base64://AQID', + name: 'inline.txt', + upload_file: false, + }); + + expect(response).toMatchObject({ + status: 'ok', + retcode: 0, + data: { file_id: 'uploaded-file-uuid' }, + }); + expect(ctx.bridge.apis.message.sendC2cFile).not.toHaveBeenCalled(); + expect(dispatchEvent).not.toHaveBeenCalled(); + }); + it('reports a private message sent through an action', async () => { const { ctx, dispatchEvent } = makeContext(); const api = buildApiContext(ctx); diff --git a/packages/onebot/tests/system-face-actions.test.ts b/packages/onebot/tests/system-face-actions.test.ts new file mode 100644 index 00000000..69191540 --- /dev/null +++ b/packages/onebot/tests/system-face-actions.test.ts @@ -0,0 +1,65 @@ +import { describe, expect, it, vi } from 'vitest'; +import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import { ApiHandler, type ApiActionContext } from '../src/api-handler'; + +const FACE = { + qSid: '392', qDes: '/龙年快乐', emCode: '10392', qCid: 392, + aniStickerType: 3, aniStickerPackId: 1, aniStickerId: 38, + url: 'https://example.invalid/392', emojiNameAlias: ['dragon'], + aniStickerWidth: 200, aniStickerHeight: 200, +}; + +function handler(systemFace: Record): ApiHandler { + const bridge = { apis: { systemFace } } as unknown as BridgeInterface; + return new ApiHandler({ bridge } as ApiActionContext); +} + +describe('system face actions', () => { + it('returns the full pack mapping and supports an explicit server refresh', async () => { + const fetchCatalog = vi.fn(async () => [{ packName: '超级表情', emojis: [FACE] }]); + const response = await handler({ fetchCatalog }).handle('fetch_sys_faces', { refresh: true }); + + expect(fetchCatalog).toHaveBeenCalledWith(true); + expect(response).toMatchObject({ + status: 'ok', + data: { + packs: [{ + pack_name: '超级表情', + emojis: [{ q_sid: '392', q_des: '/龙年快乐', is_super: true }], + }], + }, + }); + }); + + it('looks up one id without redownloading a fresh catalog', async () => { + const fetchFace = vi.fn(async () => FACE); + const response = await handler({ fetchFace }).handle('fetch_face_entity', { face_id: '392' }); + + expect(fetchFace).toHaveBeenCalledWith(392, false); + expect(response).toMatchObject({ status: 'ok', data: { q_sid: '392', q_des: '/龙年快乐' } }); + }); + + it('accepts face id 0', async () => { + const fetchFace = vi.fn(async () => ({ ...FACE, qSid: '0', qDes: '/惊讶' })); + const response = await handler({ fetchFace }).handle('fetch_face_entity', { face_id: 0 }); + + expect(fetchFace).toHaveBeenCalledWith(0, false); + expect(response).toMatchObject({ status: 'ok', data: { q_sid: '0', q_des: '/惊讶' } }); + }); + + it('searches descriptions and aliases through the shared local catalog', async () => { + const search = vi.fn(async () => [FACE]); + const response = await handler({ search }).handle('search_sys_faces', { query: 'dragon' }); + + expect(search).toHaveBeenCalledWith('dragon'); + expect(response).toMatchObject({ status: 'ok', data: { faces: [{ q_sid: '392' }] } }); + }); + + it('reports whether an id uses the super-face wire shape', async () => { + const isSuper = vi.fn(async () => true); + const response = await handler({ isSuper }).handle('fetch_super_face_id', { face_id: 392 }); + + expect(isSuper).toHaveBeenCalledWith(392, false); + expect(response).toMatchObject({ status: 'ok', data: { is_super: true } }); + }); +}); diff --git a/packages/onebot/tests/ws-server-lifecycle.test.ts b/packages/onebot/tests/ws-server-lifecycle.test.ts index e4d01a24..0f791476 100644 --- a/packages/onebot/tests/ws-server-lifecycle.test.ts +++ b/packages/onebot/tests/ws-server-lifecycle.test.ts @@ -8,7 +8,10 @@ const { FakeWebSocketServer, servers } = vi.hoisted(() => { class FakeWebSocketServer extends EventEmitter { closeCallback: ((error?: Error) => void) | null = null; readonly options: { - verifyClient?: (info: { req: { headers: Record; url?: string } }) => boolean; + verifyClient?: ( + info: { req: { headers: Record; url?: string } }, + done: (allow: boolean, code?: number, message?: string) => void, + ) => void; }; constructor(options: unknown) { super(); @@ -86,8 +89,13 @@ describe('WsServerAdapter bind/release lifecycle promises', () => { const verify = servers[0].options.verifyClient; expect(verify).toBeTypeOf('function'); - expect(verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } })).toBe(false); - expect(verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } })).toBe(true); + const denied = vi.fn(); + verify?.({ req: { headers: {}, url: '/?access_token=wrong-token' } }, denied); + expect(denied).toHaveBeenCalledWith(false, 401, 'Unauthorized'); + + const accepted = vi.fn(); + verify?.({ req: { headers: {}, url: '/?access_token=expected-token' } }, accepted); + expect(accepted).toHaveBeenCalledWith(true); }); it('rejects bind errors and exposes them as degraded', async () => { diff --git a/packages/onebot/tests/ws-server-routing.test.ts b/packages/onebot/tests/ws-server-routing.test.ts new file mode 100644 index 00000000..f3f2adc6 --- /dev/null +++ b/packages/onebot/tests/ws-server-routing.test.ts @@ -0,0 +1,315 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; +import type { AddressInfo } from 'node:net'; +import { getLogLevel, getRecentLogs, setLogLevel } from '@snowluma/common/logger'; +import { WebSocket, type WebSocketServer } from '@snowluma/websocket'; +import { buildDispatchPayload } from '../src/event-filter'; +import { WsServerAdapter } from '../src/network/ws-server-adapter'; +import type { NetworkAdapterContext } from '../src/network/adapter'; +import type { JsonObject, WsServerNetwork } from '../src/types'; + +function waitForOpen(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + socket.once('open', resolve); + socket.once('error', reject); + }); +} + +function waitForMessage(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + socket.once('message', (raw: Buffer) => { + try { + resolve(JSON.parse(raw.toString('utf8')) as JsonObject); + } catch (error) { + reject(error); + } + }); + socket.once('error', reject); + }); +} + +function waitForHandshakeError(socket: WebSocket): Promise { + return new Promise((resolve, reject) => { + socket.once('open', () => reject(new Error('unexpected WebSocket upgrade'))); + socket.once('error', (error: Error) => resolve(error.message)); + }); +} + +function context(): NetworkAdapterContext { + return { + uin: '10001', + api: { + isAcceptingActions: true, + processStreamRequest: vi.fn(async (text: string, send: (frame: string) => Promise) => { + const request = JSON.parse(text) as { echo?: unknown }; + await send(JSON.stringify({ + status: 'ok', + retcode: 0, + data: { transport: 'websocket' }, + echo: request.echo, + })); + }), + } as never, + buildLifecycleEvent: (subType) => ({ + post_type: 'meta_event', + meta_event_type: 'lifecycle', + sub_type: subType, + }), + buildHeartbeatEvent: () => ({ + post_type: 'meta_event', + meta_event_type: 'heartbeat', + interval: 5000, + }), + }; +} + +function config(): WsServerNetwork { + return { + name: 'ws-routing', + host: '127.0.0.1', + port: 0, + path: '/', + role: 'Universal', + messageFormat: 'array', + reportSelfMessage: false, + }; +} + +describe('WsServerAdapter — OneBot forward WebSocket routes', () => { + let adapter: WsServerAdapter | null = null; + let socket: WebSocket | null = null; + + afterEach(async () => { + await adapter?.close(); + adapter = null; + socket?.terminate(); + socket = null; + }); + + it('serves actions without event frames on /api', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + const frames: JsonObject[] = []; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`); + socket.on('message', (raw: Buffer) => { + frames.push(JSON.parse(raw.toString('utf8')) as JsonObject); + }); + await waitForOpen(socket); + socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'api-route' })); + + await vi.waitFor(() => { + expect(frames.some((frame) => frame.echo === 'api-route')).toBe(true); + }); + expect(frames.filter((frame) => frame.post_type === 'meta_event')).toEqual([]); + }); + + it('accepts the standard trailing slash on /api/', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + const frames: JsonObject[] = []; + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api/`); + socket.on('message', (raw: Buffer) => { + frames.push(JSON.parse(raw.toString('utf8')) as JsonObject); + }); + await waitForOpen(socket); + socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'api-slash' })); + + await vi.waitFor(() => { + expect(frames.some((frame) => frame.echo === 'api-slash')).toBe(true); + }); + expect(frames.filter((frame) => frame.post_type === 'meta_event')).toEqual([]); + }); + + it('pushes events without accepting actions on /event', async () => { + const ctx = context(); + const api = ctx.api as unknown as { processStreamRequest: ReturnType }; + adapter = new WsServerAdapter('ws-routing', config(), ctx); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + const frames: JsonObject[] = []; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/event`); + socket.on('message', (raw: Buffer) => { + frames.push(JSON.parse(raw.toString('utf8')) as JsonObject); + }); + await waitForOpen(socket); + await vi.waitFor(() => { + expect(frames.map((frame) => frame.meta_event_type)).toEqual([ + 'lifecycle', + 'lifecycle', + 'heartbeat', + ]); + }); + + socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'event-route' })); + await new Promise((resolve) => setImmediate(resolve)); + expect(api.processStreamRequest).not.toHaveBeenCalled(); + + const event = { post_type: 'notice', notice_type: 'test' }; + adapter.onEvent(event, buildDispatchPayload(event)); + await vi.waitFor(() => { + expect(frames.at(-1)).toEqual(event); + }); + }); + + it('accepts the standard trailing slash on /event/', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/event/`); + const firstFrame = waitForMessage(socket); + await waitForOpen(socket); + + await expect(firstFrame).resolves.toMatchObject({ + post_type: 'meta_event', + meta_event_type: 'lifecycle', + sub_type: 'connect', + }); + }); + + it('keeps / bidirectional', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + const frames: JsonObject[] = []; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/`); + socket.on('message', (raw: Buffer) => { + frames.push(JSON.parse(raw.toString('utf8')) as JsonObject); + }); + await waitForOpen(socket); + await vi.waitFor(() => { + expect(frames).toHaveLength(3); + }); + + socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'universal-route' })); + await vi.waitFor(() => { + expect(frames.some((frame) => frame.echo === 'universal-route')).toBe(true); + }); + + const event = { post_type: 'notice', notice_type: 'universal-test' }; + adapter.onEvent(event, buildDispatchPayload(event)); + await vi.waitFor(() => { + expect(frames.at(-1)).toEqual(event); + }); + }); + + it('rejects paths outside the configured OneBot endpoints', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/unknown`); + + await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400'); + }); + + it('does not include query-string credentials in rejected-path logs', async () => { + const previousLevel = getLogLevel(); + setLogLevel('debug'); + try { + adapter = new WsServerAdapter( + 'ws-routing', + { ...config(), accessToken: 'expected-secret' }, + context(), + ); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket( + `ws://127.0.0.1:${String(address.port)}/unknown?access_token=log-secret`, + ); + await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400'); + + const rejection = getRecentLogs(20).find((entry) => + entry.scope === 'OneBot.WS-Server' + && entry.message.includes('rejected unknown WebSocket path /unknown')); + expect(rejection).toBeDefined(); + expect(rejection?.message).not.toContain('log-secret'); + } finally { + setLogLevel(previousLevel); + } + }); + + it('does not normalize a protocol-relative path into the root endpoint', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}//unknown`); + + await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400'); + }); + + it('does not normalize a double-slash path into the root endpoint', async () => { + adapter = new WsServerAdapter('ws-routing', config(), context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}//`); + + await expect(waitForHandshakeError(socket)).resolves.toContain('Unexpected response status 400'); + }); + + it('accepts standard routes with query-string authentication', async () => { + adapter = new WsServerAdapter( + 'ws-routing', + { ...config(), accessToken: 'query-secret' }, + context(), + ); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket( + `ws://127.0.0.1:${String(address.port)}/api?access_token=query-secret`, + ); + + await expect(waitForOpen(socket)).resolves.toBeUndefined(); + }); + + it('treats an omitted standalone role as Universal', async () => { + adapter = new WsServerAdapter( + 'ws-routing', + { ...config(), role: undefined }, + context(), + ); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`); + await waitForOpen(socket); + const response = waitForMessage(socket); + socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'default-role' })); + + await expect(response).resolves.toMatchObject({ echo: 'default-role' }); + }); + + it('keeps a non-root configured Universal endpoint bidirectional', async () => { + adapter = new WsServerAdapter('ws-routing', { ...config(), path: '/api' }, context()); + await adapter.open(); + const address = (adapter as unknown as { wss: WebSocketServer }).wss.address() as AddressInfo; + const frames: JsonObject[] = []; + + socket = new WebSocket(`ws://127.0.0.1:${String(address.port)}/api`); + socket.on('message', (raw: Buffer) => { + frames.push(JSON.parse(raw.toString('utf8')) as JsonObject); + }); + await waitForOpen(socket); + await vi.waitFor(() => { + expect(frames.map((frame) => frame.meta_event_type)).toEqual([ + 'lifecycle', + 'lifecycle', + 'heartbeat', + ]); + }); + + socket.send(JSON.stringify({ action: 'get_status', params: {}, echo: 'custom-universal' })); + await vi.waitFor(() => { + expect(frames.some((frame) => frame.echo === 'custom-universal')).toBe(true); + }); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 1b29ff56..98d18d8d 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proto-defs", - "version": "1.14.0", + "version": "1.14.1", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` 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).", diff --git a/packages/proto-defs/src/message.ts b/packages/proto-defs/src/message.ts index 1b775f91..b6c8cc94 100644 --- a/packages/proto-defs/src/message.ts +++ b/packages/proto-defs/src/message.ts @@ -18,11 +18,8 @@ export interface ResponseGrp { groupName?: pb<7, string>; } -// ResponseHead field 7 is multi-purpose: a forward message carries -// `friendName` (field 6); a group temp-session push carries the source group -// (field 4). Subfields don't collide, so one interface covers both. export interface ResponseForward { - tempGroupUin?: pb<4, uint_32>; + tempGroupUin?: pb<5, uint_32>; friendName?: pb<6, string>; } diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index a0a09dd0..b9a587f2 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -315,6 +315,7 @@ export interface OidbGroupDetailFlags { question?: pb<24, bool>; answer?: pb<25, string>; maxAdminCount?: pb<29, string>; + shutUpAllTimestamp?: pb<59, bool>; } export interface OidbGroupDetailConfig { uin?: pb<1, uint_64>; diff --git a/packages/proto-defs/src/oidb.ts b/packages/proto-defs/src/oidb.ts index fae55318..dc1b74f7 100644 --- a/packages/proto-defs/src/oidb.ts +++ b/packages/proto-defs/src/oidb.ts @@ -82,6 +82,7 @@ export interface OidbSvcTrpcTcp0xFE5_2GroupInfo { description?: pb<18, string>; question?: pb<19, string>; announcement?: pb<30, string>; + shutUpAllTimestamp?: pb<31, uint_32>; } export interface OidbSvcTrpcTcp0xFE5_2CustomInfo { @@ -115,6 +116,7 @@ export interface OidbSvcTrpcTcp0x88D_0Results { question?: pb<24, string>; answer?: pb<25, string>; maxAdminCount?: pb<29, uint_64>; + shutUpAllTimestamp?: pb<59, uint_32>; } export interface OidbSvcTrpcTcp0x88D_0ResponseGroupInfo { uin?: pb<1, uint_64>; diff --git a/packages/protocol/package.json b/packages/protocol/package.json index caac9bea..39e02ce2 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/protocol", - "version": "1.14.0", + "version": "1.14.1", "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/'` collapses to `import { … } from '@snowluma/protocol/'`.", @@ -44,6 +44,14 @@ "types": "./src/self-uid.ts", "default": "./src/self-uid.ts" }, + "./sys-face-store": { + "types": "./src/sys-face-store.ts", + "default": "./src/sys-face-store.ts" + }, + "./sys-face-storage": { + "types": "./src/sys-face-storage.ts", + "default": "./src/sys-face-storage.ts" + }, "./bridge-oidb": { "types": "./src/bridge-oidb.ts", "default": "./src/bridge-oidb.ts" diff --git a/packages/protocol/src/element-builder.ts b/packages/protocol/src/element-builder.ts index 78fa3d95..b9fe0c0e 100644 --- a/packages/protocol/src/element-builder.ts +++ b/packages/protocol/src/element-builder.ts @@ -10,6 +10,7 @@ import type { BridgeContext } from './bridge-context'; import { sysFaceStore } from './sys-face-store'; import type { MessageElement } from './events'; import { + assertVideoSendPolicy, assertWindowShakeSendPolicy, assertValidMessageElements, MessageElementValidationError, @@ -55,12 +56,12 @@ function makeTextElem(text: string): ProtoElem { // super (animated, aniSticker not pack (1,1)) → CommonElem 37 + QFaceExtra // other id ≥ 260 → CommonElem 33 + QSmallFaceExtra // classic id < 260 → legacy FaceElem -function makeFaceElem(faceId: number, ctx?: SendContext): ProtoElem { - // Keep the catalog warm so subsequent super-face sends are classified even if - // this one raced ahead of the first fetch. - if (ctx) sysFaceStore.ensureWarm(ctx.bridge); - - const wire = sysFaceStore.classify(faceId); +async function makeFaceElem(faceId: number, ctx?: SendContext): Promise { + // With a live bridge, wait for the authoritative catalog. Login normally + // preloads it, while this await closes the reconnect / first-send race. + const wire = ctx + ? await sysFaceStore.resolveWire(ctx.bridge, faceId) + : sysFaceStore.classify(faceId); if (wire.kind === 'super') { return { commonElem: { @@ -458,6 +459,13 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte // preserves all-or-nothing semantics: a malformed later segment cannot make // an earlier media segment perform side effects before the send is rejected. assertValidMessageElements(elements, 'W'); + // Canonical MessageElements cannot contain empty text. OneBot's explicit + // empty-text compatibility placeholders are removed before this boundary, + // so the array length here is the effective on-wire segment count. + assertVideoSendPolicy( + elements.filter((element) => element.type === 'video').length, + elements.length, + ); assertWindowShakeSendPolicy( elements.filter((element) => element.type === 'poke').length, elements.length, @@ -495,7 +503,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'face': - result.push(makeFaceElem(elem.faceId, ctx)); + result.push(await makeFaceElem(elem.faceId, ctx)); break; case 'poke': diff --git a/packages/protocol/src/element-manifest.ts b/packages/protocol/src/element-manifest.ts index 9ed6614b..6db9314f 100644 --- a/packages/protocol/src/element-manifest.ts +++ b/packages/protocol/src/element-manifest.ts @@ -67,6 +67,33 @@ export function assertWindowShakeSendPolicy( } } +/** + * QQ clients treat a video as a standalone message: sibling elements remain + * on the wire but are not rendered, and additional videos cannot be opened. + * Reject that ambiguous wire shape instead of reporting a successful send + * whose visible content differs from the caller's request. + */ +export function assertVideoSendPolicy( + videoCount: number, + effectiveSegmentCount: number, +): void { + if (videoCount === 0) return; + if (videoCount !== 1) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'message element "video" may appear only once in a message', + 'video', + ); + } + if (effectiveSegmentCount !== 1) { + throw new MessageElementValidationError( + 'UNSENDABLE_TYPE', + 'message element "video" must be the only segment in a message', + 'video', + ); + } +} + type ElementField = Exclude, 'type'> & string; export interface ElementSpec { diff --git a/packages/protocol/src/highway/ffmpeg-addon.ts b/packages/protocol/src/highway/ffmpeg-addon.ts index 249df52e..dfa1b2ff 100644 --- a/packages/protocol/src/highway/ffmpeg-addon.ts +++ b/packages/protocol/src/highway/ffmpeg-addon.ts @@ -161,7 +161,7 @@ export async function encodeSilk(inputFile: string, tempDir: string): Promise { + let text: string; + try { + text = await readFile(this.filePath, 'utf8'); + } catch (error) { + if (isErrno(error, 'ENOENT')) return null; + throw new Error(`failed to read system face catalog ${this.filePath}`, { cause: error }); + } + + try { + return JSON.parse(text) as SysFaceCatalogSnapshot; + } catch (error) { + throw new Error(`failed to parse system face catalog ${this.filePath}`, { cause: error }); + } + } + + async save(snapshot: SysFaceCatalogSnapshot): Promise { + await mkdir(dirname(this.filePath), { recursive: true }); + const temporaryPath = `${this.filePath}.tmp-${process.pid}-${Date.now()}`; + try { + await writeFile(temporaryPath, JSON.stringify(snapshot, null, 2), 'utf8'); + await rename(temporaryPath, this.filePath); + } catch (error) { + try { + await unlink(temporaryPath); + } catch (cleanupError) { + if (!isErrno(cleanupError, 'ENOENT')) { + throw new AggregateError( + [error, cleanupError], + `failed to persist system face catalog ${this.filePath} and remove its temporary file`, + ); + } + } + throw new Error(`failed to persist system face catalog ${this.filePath}`, { cause: error }); + } + } +} diff --git a/packages/protocol/src/sys-face-store.ts b/packages/protocol/src/sys-face-store.ts index 5e92853e..6d32e78b 100644 --- a/packages/protocol/src/sys-face-store.ts +++ b/packages/protocol/src/sys-face-store.ts @@ -1,11 +1,6 @@ -// Process-wide cache of QQ's system-face catalog (fetched once via 0x9154_1), -// used by the send path to pick a face id's wire encoding. The catalog is the -// same for every account, so a single shared store is fetched lazily and reused. -// -// `classify` is synchronous (the element builder is sync); a face sent before -// the catalog is warm falls back to an id-range guess. `ensureWarm` kicks off -// the one-shot fetch — call it proactively at login so the first super-face -// send is already classified. +// Process-wide catalog of QQ system faces. QQ publishes the mapping through +// 0x9154_1; this store makes that catalog durable, queryable, and safe to use +// from the asynchronous send path. import { createLogger } from '@snowluma/common/logger'; import { @@ -16,77 +11,337 @@ import { } from './oidb-services/sys-faces/fetch-sys-faces'; import type { OidbSender } from './oidb-service'; +export type { SysFaceEntry, SysFacePackEntry } from './oidb-services/sys-faces/fetch-sys-faces'; + const log = createLogger('SysFace'); -/** Wire encoding a face id maps to. `classic` → legacy FaceElem; `small` → - * CommonElem serviceType 33 (QSmallFaceExtra); `super` → CommonElem - * serviceType 37 (QFaceExtra) for animated/super faces. */ +/** Wire encoding a face id maps to. `classic` -> legacy FaceElem; `small` -> + * CommonElem serviceType 33; `super` -> CommonElem serviceType 37. */ export type FaceWire = | { kind: 'classic' } | { kind: 'small' } | { kind: 'super'; packId: string; stickerId: string; stickerType: number }; -/** Pure classification: a super face (per the catalog entry) → `super` with its - * pack/sticker ids; otherwise an id-range guess (`< 260` = classic, else - * small). Used both warm (entry from the catalog) and cold (entry undefined). */ +export interface SysFaceCatalogSnapshot { + schemaVersion: 1; + fetchedAt: number; + packs: SysFacePackEntry[]; +} + +export interface SysFaceCatalogStorage { + load(): Promise; + save(snapshot: SysFaceCatalogSnapshot): Promise; +} + +export interface SysFaceStoreOptions { + storage?: SysFaceCatalogStorage; + fetchCatalog?: (sender: OidbSender) => Promise; + now?: () => number; +} + +interface IndexedCatalog { + packs: SysFacePackEntry[]; + byId: Map; + packNameById: Map; +} + +/** Pure classification once an authoritative entry is known. */ export function faceWireFor(entry: SysFaceEntry | null | undefined, faceId: number): FaceWire { - if (entry && isSuperFaceEntry(entry)) { + if (!entry) { + throw new Error(`QQ system face id ${faceId} is absent from the current catalog`); + } + if (isSuperFaceEntry(entry)) { + if (entry.aniStickerPackId == null + || entry.aniStickerId == null + || entry.aniStickerType == null) { + throw new Error(`QQ system face id ${faceId} has incomplete super-face metadata`); + } return { kind: 'super', - packId: String(entry.aniStickerPackId ?? 1), - stickerId: String(entry.aniStickerId ?? 0), - stickerType: entry.aniStickerType ?? 0, + packId: String(entry.aniStickerPackId), + stickerId: String(entry.aniStickerId), + stickerType: entry.aniStickerType, }; } return faceId < 260 ? { kind: 'classic' } : { kind: 'small' }; } -const RETRY_COOLDOWN_MS = 30_000; +export class SysFaceStore { + private catalog: IndexedCatalog | null = null; + private storage: SysFaceCatalogStorage | null; + private readonly fetchCatalog: (sender: OidbSender) => Promise; + private readonly now: () => number; + private cacheLoadCompleted = false; + private cacheLoadInflight: Promise | null = null; + private refreshInflight: Promise | null = null; + private refreshedInProcess = false; + private prewarmInflight: Promise | null = null; + private prewarmed = false; -class SysFaceStore { - private byId: Map | null = null; - private inflight: Promise | null = null; - private lastFailedAt = 0; + constructor(options: SysFaceStoreOptions = {}) { + this.storage = options.storage ?? null; + this.fetchCatalog = options.fetchCatalog ?? ((sender) => FetchSysFaces.invoke(sender)); + this.now = options.now ?? Date.now; + } - /** Index a fetched catalog (also used by tests to seed without a network). */ + /** Configure persistence before the shared store has been used. */ + configureStorage(storage: SysFaceCatalogStorage): void { + if (this.cacheLoadCompleted || this.cacheLoadInflight || this.catalog || this.refreshInflight) { + throw new Error('system face catalog storage must be configured before first use'); + } + this.storage = storage; + } + + /** Index a trusted catalog. Kept public for protocol consumers that already + * obtained a full catalog and want to reuse the same query/send semantics. */ load(packs: SysFacePackEntry[]): void { - this.byId = buildIndex(packs); + this.catalog = indexCatalog(validateCatalog(packs)); } - /** Synchronous classification. Falls back to an id-range guess when the - * catalog isn't warm yet or the id is unknown. */ + lookup(faceId: number): SysFaceEntry | null { + return this.catalog?.byId.get(String(faceId)) ?? null; + } + + /** Case-insensitive query over id, description, aliases, and pack name. */ + search(query: string): SysFaceEntry[] { + const needle = query.trim().toLocaleLowerCase(); + if (!needle || !this.catalog) return []; + + const matches: SysFaceEntry[] = []; + for (const [id, face] of this.catalog.byId) { + const haystacks = [ + id, + face.qDes, + face.emCode, + this.catalog.packNameById.get(id) ?? '', + ...face.emojiNameAlias, + ]; + if (haystacks.some((value) => value.toLocaleLowerCase().includes(needle))) { + matches.push(face); + } + } + return matches; + } + + /** Synchronous classification for callers that already established catalog + * readiness. Unknown ids fail instead of guessing a QQ wire shape. */ classify(faceId: number): FaceWire { - return faceWireFor(this.byId?.get(String(faceId)), faceId); + return faceWireFor(this.lookup(faceId), faceId); } - /** Fire-and-forget one-shot warm. Coalesces concurrent callers; backs off - * briefly after a failure so a flaky fetch isn't hammered per message. */ - ensureWarm(sender: OidbSender): void { - if (this.byId || this.inflight) return; - if (Date.now() - this.lastFailedAt < RETRY_COOLDOWN_MS) return; - this.inflight = FetchSysFaces.invoke(sender) - .then((packs) => { - this.load(packs); - log.info('system face catalog loaded: %d faces', this.byId?.size ?? 0); + /** Load durable state, fetching only when no usable catalog exists. */ + async ensureReady(sender: OidbSender): Promise { + if (this.refreshInflight) { + await this.refreshInflight; + return; + } + if (this.catalog) return; + const loaded = await this.loadCache(); + if (!loaded) await this.refresh(sender); + } + + /** Login hook: restore the durable snapshot for immediate reads, then refresh + * from QQ exactly once per process. Multiple accounts share the same job. */ + prewarm(sender: OidbSender): Promise { + if (this.prewarmed) return Promise.resolve(); + if (this.prewarmInflight) return this.prewarmInflight; + + this.prewarmInflight = (async () => { + try { + await this.loadCache(); + } catch { + // loadCache already emitted the path and failure. A fresh server fetch + // is the authoritative repair for a corrupt rebuildable snapshot. + } + await this.refresh(sender); + this.prewarmed = true; + })().finally(() => { + this.prewarmInflight = null; + }); + return this.prewarmInflight; + } + + /** Fetch the current authoritative catalog. Concurrent callers share one + * request and one atomic persistence operation. */ + refresh(sender: OidbSender): Promise { + if (this.refreshInflight) return this.refreshInflight; + + const startedAt = this.now(); + this.refreshInflight = this.fetchCatalog(sender) + .then(async (packs) => { + const validated = validateCatalog(packs); + const snapshot: SysFaceCatalogSnapshot = { + schemaVersion: 1, + fetchedAt: this.now(), + packs: validated, + }; + this.catalog = indexCatalog(validated); + this.refreshedInProcess = true; + if (this.storage) await this.storage.save(snapshot); + log.info( + 'system face catalog refreshed: faces=%d packs=%d elapsedMs=%d', + this.catalog.byId.size, + validated.length, + this.now() - startedAt, + ); + return validated; }) - .catch((err) => { - this.lastFailedAt = Date.now(); - log.warn('failed to load system face catalog: %s', err instanceof Error ? err.message : String(err)); + .catch((error) => { + log.error( + 'system face catalog refresh failed: elapsedMs=%d error=%s', + this.now() - startedAt, + error instanceof Error ? error.message : String(error), + ); + throw error; }) .finally(() => { - this.inflight = null; + this.refreshInflight = null; }); + return this.refreshInflight; + } + + /** Resolve one id. A miss from a persisted snapshot causes exactly one + * authoritative refresh; a miss from that fresh catalog remains null. */ + async resolve(sender: OidbSender, faceId: number): Promise { + await this.ensureReady(sender); + const cached = this.lookup(faceId); + if (cached || this.refreshedInProcess) return cached; + + await this.refresh(sender); + return this.lookup(faceId); + } + + async resolveWire(sender: OidbSender, faceId: number): Promise { + const entry = await this.resolve(sender, faceId); + if (!entry) { + throw new Error(`QQ system face id ${faceId} is absent from the current catalog`); + } + return faceWireFor(entry, faceId); + } + + async getCatalog(sender: OidbSender, refresh = false): Promise { + if (refresh) await this.refresh(sender); + else await this.ensureReady(sender); + if (!this.catalog) { + throw new Error('system face catalog is unavailable after readiness completed'); + } + return this.catalog.packs; + } + + private loadCache(): Promise { + if (this.catalog) return Promise.resolve(true); + if (this.cacheLoadCompleted) return Promise.resolve(false); + if (this.cacheLoadInflight) return this.cacheLoadInflight; + + if (!this.storage) { + this.cacheLoadCompleted = true; + return Promise.resolve(false); + } + + const startedAt = this.now(); + this.cacheLoadInflight = this.storage.load() + .then((snapshot) => { + this.cacheLoadCompleted = true; + if (!snapshot) return false; + validateSnapshot(snapshot); + this.catalog = indexCatalog(snapshot.packs); + log.info( + 'system face catalog restored: faces=%d packs=%d fetchedAt=%d elapsedMs=%d', + this.catalog.byId.size, + snapshot.packs.length, + snapshot.fetchedAt, + this.now() - startedAt, + ); + return true; + }) + .catch((error) => { + this.cacheLoadCompleted = true; + log.error( + 'system face catalog restore failed: elapsedMs=%d error=%s', + this.now() - startedAt, + error instanceof Error ? error.message : String(error), + ); + throw error; + }) + .finally(() => { + this.cacheLoadInflight = null; + }); + return this.cacheLoadInflight; } } -function buildIndex(packs: SysFacePackEntry[]): Map { - const map = new Map(); - for (const pack of packs) { - for (const emoji of pack.emojis) { - if (emoji.qSid) map.set(emoji.qSid, emoji); +function validateSnapshot(snapshot: SysFaceCatalogSnapshot): void { + if (typeof snapshot !== 'object' || snapshot === null) { + throw new Error('invalid system face catalog snapshot root'); + } + if (snapshot.schemaVersion !== 1) { + throw new Error(`unsupported system face catalog schema version: ${String(snapshot.schemaVersion)}`); + } + if (!Number.isSafeInteger(snapshot.fetchedAt) || snapshot.fetchedAt < 0) { + throw new Error(`invalid system face catalog fetchedAt: ${String(snapshot.fetchedAt)}`); + } + validateCatalog(snapshot.packs); +} + +function validateCatalog(packs: SysFacePackEntry[]): SysFacePackEntry[] { + if (!Array.isArray(packs) || packs.length === 0) { + throw new Error('system face catalog is empty'); + } + + const seen = new Set(); + let faceCount = 0; + for (const [packIndex, pack] of packs.entries()) { + if (!pack || typeof pack.packName !== 'string' || !Array.isArray(pack.emojis)) { + throw new Error(`invalid system face pack at index ${packIndex}`); + } + for (const [faceIndex, face] of pack.emojis.entries()) { + if (!face || typeof face.qSid !== 'string' || !/^(?:0|[1-9]\d*)$/.test(face.qSid) + || !Number.isSafeInteger(Number(face.qSid)) || Number(face.qSid) < 0) { + throw new Error(`invalid system face id at pack ${packIndex}, face ${faceIndex}`); + } + if (seen.has(face.qSid)) { + throw new Error(`duplicate system face id ${face.qSid}`); + } + if (!Array.isArray(face.emojiNameAlias) + || face.emojiNameAlias.some((alias) => typeof alias !== 'string')) { + throw new Error(`invalid aliases for system face id ${face.qSid}`); + } + if (typeof face.qDes !== 'string' || typeof face.emCode !== 'string') { + throw new Error(`invalid text metadata for system face id ${face.qSid}`); + } + for (const [name, value] of [ + ['qCid', face.qCid], + ['aniStickerType', face.aniStickerType], + ['aniStickerPackId', face.aniStickerPackId], + ['aniStickerId', face.aniStickerId], + ['aniStickerWidth', face.aniStickerWidth], + ['aniStickerHeight', face.aniStickerHeight], + ] as const) { + if (value !== null && !Number.isSafeInteger(value)) { + throw new Error(`invalid ${name} for system face id ${face.qSid}`); + } + } + if (face.url !== null && typeof face.url !== 'string') { + throw new Error(`invalid url for system face id ${face.qSid}`); + } + seen.add(face.qSid); + faceCount += 1; } } - return map; + if (faceCount === 0) throw new Error('system face catalog contains no faces'); + return packs; +} + +function indexCatalog(packs: SysFacePackEntry[]): IndexedCatalog { + const byId = new Map(); + const packNameById = new Map(); + for (const pack of packs) { + for (const emoji of pack.emojis) { + byId.set(emoji.qSid, emoji); + packNameById.set(emoji.qSid, pack.packName); + } + } + return { packs, byId, packNameById }; } /** Shared, process-wide catalog (the face set is account-independent). */ diff --git a/packages/protocol/src/web/group-album.ts b/packages/protocol/src/web/group-album.ts index dbc22785..5d1e479d 100644 --- a/packages/protocol/src/web/group-album.ts +++ b/packages/protocol/src/web/group-album.ts @@ -221,8 +221,15 @@ export async function uploadImageToGroupAlbum( filePath: string, uin: string ): Promise { - const { loadBinarySource } = await import('../highway/utils'); + const { detectImageFormat, loadBinarySource } = await import('../highway/utils'); const loaded = await loadBinarySource(filePath, 'album image'); + const format = detectImageFormat(loaded.bytes); + const isJpeg = loaded.bytes.length >= 2 + && loaded.bytes[0] === 0xFF + && loaded.bytes[1] === 0xD8; + if (format.format === 1000 && !isJpeg) { + throw new Error('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片'); + } let tempFile: string | null = null; let actualPath = filePath; diff --git a/packages/protocol/src/web/group-essence.ts b/packages/protocol/src/web/group-essence.ts index 0a34f24d..58bc225e 100644 --- a/packages/protocol/src/web/group-essence.ts +++ b/packages/protocol/src/web/group-essence.ts @@ -41,6 +41,16 @@ export interface GroupEssenceMsgRet { }; } +interface RawGroupEssenceMsgRet { + retcode: number; + retmsg?: string; + data?: { + is_end?: unknown; + msg_list?: Array | null; + group_role?: number; + config_page_url?: string; + } | null; +} /** * 分页获取群精华消息 @@ -61,7 +71,7 @@ export async function getGroupEssenceMsg( }).toString()}`; try { - const ret = await RequestUtil.HttpGetJson( + const ret = await RequestUtil.HttpGetJson( url, 'GET', '', @@ -72,12 +82,35 @@ export async function getGroupEssenceMsg( `group essence request failed with retcode ${ret.retcode}: ${ret.retmsg ?? 'unknown error'}`, ); } + if (ret.data?.is_end === true && ret.data.msg_list == null) { + log.debug( + 'normalized empty group essence response (group=%s page=%d/%d)', + groupCode, + pageStart, + pageLimit, + ); + return { + ...ret, + data: { + ...ret.data, + is_end: true, + msg_list: [], + }, + }; + } if (!ret.data || typeof ret.data.is_end !== 'boolean' || !Array.isArray(ret.data.msg_list)) { throw new Error('invalid group essence response: data.is_end or data.msg_list is missing'); } - return ret; + return { + ...ret, + data: { + ...ret.data, + is_end: ret.data.is_end, + msg_list: ret.data.msg_list, + }, + }; } catch (e) { log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s', groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e)); diff --git a/packages/protocol/tests/msg-push/temp-message-source.test.ts b/packages/protocol/tests/msg-push/temp-message-source.test.ts new file mode 100644 index 00000000..14cd1354 --- /dev/null +++ b/packages/protocol/tests/msg-push/temp-message-source.test.ts @@ -0,0 +1,98 @@ +import type { PacketInfo } from '@snowluma/common/protocol-types'; +import { + protobuf_encode, + type pb, + type pb_repeated, + type string, + type uint_32, +} from '@snowluma/proton'; +import { describe, expect, it } from 'vitest'; + +import type { IdentityService } from '../../src/identity-service'; +import { parseMsgPush } from '../../src/msg-push'; + +interface TextFixture { + str?: pb<1, string>; +} + +interface ElemFixture { + text?: pb<1, TextFixture>; +} + +interface RichTextFixture { + elems?: pb_repeated<2, ElemFixture>; +} + +interface MessageBodyFixture { + richText?: pb<1, RichTextFixture>; +} + +interface TempSessionFixture { + previousGroup?: pb<4, uint_32>; + sourceGroup?: pb<5, uint_32>; +} + +interface ResponseHeadFixture { + fromUin?: pb<1, uint_32>; + fromUid?: pb<2, string>; + tempSession?: pb<7, TempSessionFixture>; +} + +interface ContentHeadFixture { + msgType?: pb<1, uint_32>; + sequence?: pb<5, uint_32>; + timestamp?: pb<6, uint_32>; + ntMsgSeq?: pb<11, uint_32>; +} + +interface PushBodyFixture { + responseHead?: pb<1, ResponseHeadFixture>; + contentHead?: pb<2, ContentHeadFixture>; + body?: pb<3, MessageBodyFixture>; +} + +interface PushFixture { + message?: pb<1, PushBodyFixture>; +} + +const identity = { findFriend: () => undefined } as unknown as IdentityService; + +function tempMessagePacket(previousGroup: number, sourceGroup: number): PacketInfo { + return { + pid: 1, + uin: '2000000001', + serviceCmd: 'trpc.msg.olpush.OlPushService.MsgPush', + seqId: 1, + retCode: 0, + fromClient: false, + body: protobuf_encode({ + message: { + responseHead: { + fromUin: 10001, + fromUid: 'u_peer', + tempSession: { previousGroup, sourceGroup }, + }, + contentHead: { + msgType: 141, + sequence: 7, + timestamp: 1_710_000_000, + ntMsgSeq: 8, + }, + body: { richText: { elems: [{ text: { str: 'hello' } }] } }, + }, + }), + }; +} + +describe('parseMsgPush — temporary-session source (#308)', () => { + it('keeps a passive reply bound to the group that opened the current session', () => { + const events = parseMsgPush(tempMessagePacket(11111, 22222), identity); + + expect(events).toMatchObject([{ + kind: 'temp_message', + senderUin: 10001, + groupId: 22222, + elements: [{ type: 'text', text: 'hello' }], + }]); + }); +}); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts index 603fa99a..562cecd6 100644 --- a/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-detail.test.ts @@ -3,13 +3,33 @@ // matching Lagrange's GetGroupInfoService) and the response decode. import { describe, expect, it, vi } from 'vitest'; -import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import { + protobuf_decode, + protobuf_encode, + type pb, + type uint_32, + type uint_64, +} from '@snowluma/proton'; import type { OidbBase, OidbSvcTrpcTcp0x88D_0Response } from '@snowluma/proto-defs/oidb'; import type { OidbGroupDetailRequest } from '@snowluma/proto-defs/oidb-actions/base'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import { FetchGroupDetail } from '../../../src/oidb-services/contacts/fetch-group-detail'; +interface GroupDetailResultsFixture { + name?: pb<15, string>; + shutUpAllTimestamp?: pb<59, uint_32>; +} + +interface GroupDetailInfoFixture { + uin?: pb<1, uint_64>; + results?: pb<3, GroupDetailResultsFixture>; +} + +interface GroupDetailResponseFixture { + groupInfo?: pb<1, GroupDetailInfoFixture>; +} + function makeSender(body?: OidbSvcTrpcTcp0x88D_0Response) { const responseData = body !== undefined ? Buffer.from(protobuf_encode>({ body })) @@ -33,6 +53,8 @@ describe('FetchGroupDetail namespace', () => { expect(out.config?.flags?.name).toBe(''); // string mask → request the name expect(out.config?.flags?.memberCount).toBe(true); expect(out.config?.flags?.maxMemberCount).toBe(true); + expect((out.config?.flags as { shutUpAllTimestamp?: boolean })?.shutUpAllTimestamp) + .toBe(true); }); }); @@ -66,5 +88,28 @@ describe('FetchGroupDetail namespace', () => { expect(out.groupInfo?.results?.memberCount).toBe(42n); expect(out.groupInfo?.results?.maxMemberCount).toBe(500n); }); + + it('decodes the group-wide mute timestamp from a detail response', async () => { + const responseData = Buffer.from(protobuf_encode>({ + body: { + groupInfo: { + uin: 601692726n, + results: { name: 'Muted Group', shutUpAllTimestamp: 4_294_967_295 }, + }, + }, + })); + 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?.shutUpAllTimestamp).toBe(4_294_967_295); + }); }); }); diff --git a/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts b/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts index 33110cd9..492cff83 100644 --- a/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts +++ b/packages/protocol/tests/oidb-services/contacts/fetch-group-list.test.ts @@ -1,11 +1,31 @@ import { describe, expect, it, vi } from 'vitest'; -import { protobuf_decode } from '@snowluma/proton'; +import { + protobuf_decode, + protobuf_encode, + type pb, + type pb_repeated, + type uint_32, +} from '@snowluma/proton'; import type { OidbBase } from '@snowluma/proto-defs/oidb'; import type { OidbGroupListRequest } from '@snowluma/proto-defs/oidb-actions/base'; import type { SendPacketResult } from '@snowluma/common/packet-sender'; import { FetchGroupList } from '../../../src/oidb-services/contacts/fetch-group-list'; +interface GroupInfoFixture { + groupName?: pb<5, string>; + shutUpAllTimestamp?: pb<31, uint_32>; +} + +interface GroupFixture { + groupUin?: pb<3, uint_32>; + info?: pb<4, GroupInfoFixture>; +} + +interface GroupListFixture { + groups?: pb_repeated<2, GroupFixture>; +} + function makeSender() { const r: SendPacketResult = { success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0) }; return { sendRawPacket: vi.fn(async () => r) }; @@ -35,6 +55,7 @@ describe('FetchGroupList namespace', () => { const env = protobuf_decode>(bytes); expect(env.body?.config?.config1?.groupName).toBe(true); expect(env.body?.config?.config1?.memberCount).toBe(true); + expect(env.body?.config?.config1?.field31).toBe(true); expect(env.body?.config?.config2?.remark).toBe(true); for (const field of ['field1', 'field2', 'field4', 'field5', 'field6', 'field7', 'field8'] as const) { expect(env.body?.config?.config2?.[field] ?? false, field).toBe(false); @@ -43,5 +64,28 @@ describe('FetchGroupList namespace', () => { expect(env.body?.config?.config1?.field5002 ?? false).toBe(false); expect(env.body?.config?.config1?.field5003 ?? false).toBe(false); }); + + it('decodes the group-wide mute timestamp returned with the joined roster', async () => { + const responseData = Buffer.from(protobuf_encode>({ + body: { + groups: [{ + groupUin: 123456789, + info: { groupName: 'Muted Group', shutUpAllTimestamp: 4_294_967_295 }, + }], + }, + })); + const sender = makeSender(); + sender.sendRawPacket.mockResolvedValue({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData, + }); + + const out = await FetchGroupList.invoke(sender); + + expect(out.groups?.[0]?.info?.shutUpAllTimestamp).toBe(4_294_967_295); + }); }); }); diff --git a/packages/protocol/tests/sys-face-storage.test.ts b/packages/protocol/tests/sys-face-storage.test.ts new file mode 100644 index 00000000..f533432c --- /dev/null +++ b/packages/protocol/tests/sys-face-storage.test.ts @@ -0,0 +1,53 @@ +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { afterEach, describe, expect, it } from 'vitest'; +import { JsonSysFaceCatalogStorage } from '../src/sys-face-storage'; +import type { SysFaceCatalogSnapshot } from '../src/sys-face-store'; + +const roots: string[] = []; + +afterEach(async () => { + await Promise.all(roots.splice(0).map((root) => rm(root, { recursive: true, force: true }))); +}); + +async function fixturePath(): Promise { + const root = await mkdtemp(join(tmpdir(), 'snowluma-sys-face-')); + roots.push(root); + return join(root, 'nested', 'sys-faces.json'); +} + +const SNAPSHOT: SysFaceCatalogSnapshot = { + schemaVersion: 1, + fetchedAt: 123, + packs: [{ + packName: '经典', + emojis: [{ + qSid: '14', qDes: '/微笑', emCode: '14', qCid: null, + aniStickerType: null, aniStickerPackId: null, aniStickerId: null, + url: null, emojiNameAlias: ['smile'], + aniStickerWidth: null, aniStickerHeight: null, + }], + }], +}; + +describe('JsonSysFaceCatalogStorage', () => { + it('returns null for a missing cache and round-trips an atomic save', async () => { + const file = await fixturePath(); + const storage = new JsonSysFaceCatalogStorage(file); + + await expect(storage.load()).resolves.toBeNull(); + await storage.save(SNAPSHOT); + await expect(storage.load()).resolves.toEqual(SNAPSHOT); + expect(JSON.parse(await readFile(file, 'utf8'))).toEqual(SNAPSHOT); + }); + + it('surfaces malformed JSON with the cache path instead of ignoring it', async () => { + const file = await fixturePath(); + const storage = new JsonSysFaceCatalogStorage(file); + await storage.save(SNAPSHOT); + await writeFile(file, '{broken', 'utf8'); + + await expect(storage.load()).rejects.toThrow(file); + }); +}); diff --git a/packages/protocol/tests/sys-faces.test.ts b/packages/protocol/tests/sys-faces.test.ts index 6a92661a..52251420 100644 --- a/packages/protocol/tests/sys-faces.test.ts +++ b/packages/protocol/tests/sys-faces.test.ts @@ -1,6 +1,8 @@ import { describe, it, expect } from 'vitest'; -import { protobuf_decode } from '@snowluma/proton'; +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; import type { QFaceExtra, QSmallFaceExtra } from '@snowluma/proto-defs/element'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { OidbFetchSysFacesResp } from '@snowluma/proto-defs/oidb-actions/sys-faces'; import { FetchSysFaces, findFaceEntity, @@ -9,27 +11,54 @@ import { type SysFaceEntry, type SysFacePackEntry, } from '../src/oidb-services/sys-faces/fetch-sys-faces'; -import { faceWireFor, sysFaceStore } from '../src/sys-face-store'; +import { + faceWireFor, + SysFaceStore, + sysFaceStore, + type SysFaceCatalogSnapshot, + type SysFaceCatalogStorage, +} from '../src/sys-face-store'; import { buildSendElems } from '../src/element-builder'; -function entry(qSid: string, aniStickerType: number | null, aniStickerPackId: number | null, aniStickerId: number | null): SysFaceEntry { +function entry( + qSid: string, + aniStickerType: number | null, + aniStickerPackId: number | null, + aniStickerId: number | null, + qDes = '', + emojiNameAlias: string[] = [], +): SysFaceEntry { return { - qSid, qDes: '', emCode: '', qCid: null, + qSid, qDes, emCode: '', qCid: null, aniStickerType, aniStickerPackId, aniStickerId, - url: null, emojiNameAlias: [], aniStickerWidth: null, aniStickerHeight: null, + url: null, emojiNameAlias, aniStickerWidth: null, aniStickerHeight: null, }; } // 392 is a real non-(1,1) super face; 424 is a real (1,1) "new small" face. const CATALOG: SysFacePackEntry[] = [ - { packName: '经典', emojis: [entry('14', null, null, null)] }, + { packName: '经典', emojis: [entry('14', null, null, null, '/微笑', ['smile'])] }, { packName: '超级表情', emojis: [ - entry('392', 3, 2, 38), // super → CommonElem 37 + entry('392', 3, 2, 38, '/龙年快乐'), // super → CommonElem 37 entry('424', 1, 1, 52), // (1,1) → small → CommonElem 33 entry('358', 2, 1, 33), // super (packId 1 but type 2) → CommonElem 37 ] }, ]; +class MemoryCatalogStorage implements SysFaceCatalogStorage { + saved: SysFaceCatalogSnapshot[] = []; + + constructor(private readonly initial: SysFaceCatalogSnapshot | null = null) {} + + async load(): Promise { + return this.initial; + } + + async save(snapshot: SysFaceCatalogSnapshot): Promise { + this.saved.push(snapshot); + } +} + describe('isSuperFaceEntry / isSuperFaceId — the (1,1) rule', () => { it('treats only non-(1,1) aniSticker faces as super', () => { expect(isSuperFaceEntry(entry('x', 3, 2, 1))).toBe(true); @@ -58,13 +87,16 @@ describe('faceWireFor — classification', () => { kind: 'super', packId: '2', stickerId: '38', stickerType: 3, }); }); + it('rejects incomplete super-face metadata instead of filling guessed ids', () => { + expect(() => faceWireFor(entry('392', 3, 2, null), 392)) + .toThrow(/incomplete super-face metadata/); + }); it('(1,1) face → small/classic by id range, not super', () => { expect(faceWireFor(entry('424', 1, 1, 52), 424)).toEqual({ kind: 'small' }); }); - it('cold (no catalog entry) → id-range guess', () => { - expect(faceWireFor(undefined, 14)).toEqual({ kind: 'classic' }); // < 260 - expect(faceWireFor(undefined, 424)).toEqual({ kind: 'small' }); // ≥ 260 - expect(faceWireFor(null, 100)).toEqual({ kind: 'classic' }); + it('rejects an unknown id instead of guessing a wire shape', () => { + expect(() => faceWireFor(null, 14)).toThrow(/absent from the current catalog/); + expect(() => faceWireFor(undefined, 424)).toThrow(/absent from the current catalog/); }); }); @@ -80,9 +112,193 @@ describe('FetchSysFaces.deserialize', () => { }); }); +describe('SysFaceStore — persistent catalog and query seam', () => { + const sender = {} as never; + + it('accepts face id 0 from the authoritative catalog', async () => { + const zero = entry('0', null, null, null, '/惊讶'); + const store = new SysFaceStore({ + storage: new MemoryCatalogStorage({ + schemaVersion: 1, + fetchedAt: 123, + packs: [{ packName: '经典', emojis: [zero] }], + }), + fetchCatalog: async () => { throw new Error('network must not be used'); }, + }); + + await store.ensureReady(sender); + + expect(store.lookup(0)?.qDes).toBe('/惊讶'); + expect(store.classify(0)).toEqual({ kind: 'classic' }); + }); + + it('loads a persisted catalog and resolves ids, descriptions, aliases, and pack names', async () => { + const storage = new MemoryCatalogStorage({ + schemaVersion: 1, + fetchedAt: 123, + packs: CATALOG, + }); + const store = new SysFaceStore({ + storage, + fetchCatalog: async () => { throw new Error('network must not be used'); }, + }); + + await store.ensureReady(sender); + + expect(store.lookup(392)?.qDes).toBe('/龙年快乐'); + expect(store.search('龙年').map((face) => face.qSid)).toEqual(['392']); + expect(store.search('SMILE').map((face) => face.qSid)).toEqual(['14']); + expect(store.search('经典').map((face) => face.qSid)).toEqual(['14']); + }); + + it('coalesces concurrent refreshes and persists the authoritative result once', async () => { + const storage = new MemoryCatalogStorage(); + let fetches = 0; + let release!: (packs: SysFacePackEntry[]) => void; + const pending = new Promise((resolve) => { release = resolve; }); + const store = new SysFaceStore({ + storage, + now: () => 456, + fetchCatalog: async () => { + fetches += 1; + return pending; + }, + }); + + const first = store.refresh(sender); + const second = store.refresh(sender); + release(CATALOG); + await Promise.all([first, second]); + + expect(fetches).toBe(1); + expect(storage.saved).toEqual([{ + schemaVersion: 1, + fetchedAt: 456, + packs: CATALOG, + }]); + }); + + it('refreshes a cache miss once, then keeps an authoritative not-found result', async () => { + const storage = new MemoryCatalogStorage({ + schemaVersion: 1, + fetchedAt: 123, + packs: CATALOG.slice(0, 1), + }); + let fetches = 0; + const store = new SysFaceStore({ + storage, + fetchCatalog: async () => { + fetches += 1; + return CATALOG; + }, + }); + + expect((await store.resolve(sender, 392))?.qSid).toBe('392'); + expect(await store.resolve(sender, 99999)).toBeNull(); + expect(await store.resolve(sender, 99999)).toBeNull(); + expect(fetches).toBe(1); + }); + + it('prewarms from login only once per process while sharing the result across accounts', async () => { + let fetches = 0; + const store = new SysFaceStore({ + storage: new MemoryCatalogStorage(), + fetchCatalog: async () => { + fetches += 1; + return CATALOG; + }, + }); + + await Promise.all([ + store.prewarm({} as never), + store.prewarm({} as never), + store.prewarm({} as never), + ]); + await store.prewarm({} as never); + + expect(fetches).toBe(1); + }); + + it('waits for an in-flight login refresh before resolving a cached face', async () => { + const staleCatalog: SysFacePackEntry[] = [{ + packName: '旧目录', + emojis: [entry('392', 1, 1, 52)], + }]; + let release!: (packs: SysFacePackEntry[]) => void; + let markFetchStarted!: () => void; + const fetchStarted = new Promise((resolve) => { markFetchStarted = resolve; }); + const pending = new Promise((resolve) => { release = resolve; }); + const store = new SysFaceStore({ + storage: new MemoryCatalogStorage({ + schemaVersion: 1, + fetchedAt: 123, + packs: staleCatalog, + }), + fetchCatalog: async () => { + markFetchStarted(); + return pending; + }, + }); + + const prewarm = store.prewarm(sender); + await fetchStarted; + const resolved = store.resolveWire(sender, 392); + let settled = false; + void resolved.finally(() => { settled = true; }); + await Promise.resolve(); + expect(settled).toBe(false); + + release(CATALOG); + await expect(resolved).resolves.toMatchObject({ kind: 'super' }); + await prewarm; + }); +}); + describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () => { const ctx = { bridge: {} as never }; + it('awaits an authoritative refresh when the first send misses the persisted catalog', async () => { + sysFaceStore.load(CATALOG.slice(0, 1)); + let requests = 0; + const responseData = protobuf_encode>({ + body: { + commonFace: { + emojiList: [{ + emojiPackName: '经典', + emojiDetail: [{ qSid: '14', qDes: '/微笑' }], + }], + }, + specialBigFace: { + emojiList: [{ + emojiPackName: '超级表情', + emojiDetail: [{ + qSid: '392', qDes: '/龙年快乐', + aniStickerType: 3, aniStickerPackId: 2, aniStickerId: 38, + }], + }], + }, + }, + }); + const liveCtx = { + bridge: { + sendRawPacket: async () => { + requests += 1; + return { + success: true, + gotResponse: true, + errorCode: 0, + responseData, + }; + }, + } as never, + }; + + const [elem] = await buildSendElems([{ type: 'face', faceId: 392 }], liveCtx); + + expect(requests).toBe(1); + expect(elem.commonElem?.serviceType).toBe(37); + }); + it('encodes each face id by its catalog classification', async () => { sysFaceStore.load(CATALOG); // warm → ensureWarm no-ops, classify uses the catalog @@ -101,4 +317,11 @@ describe('makeFaceElem (via buildSendElems) — three-way wire encoding', () => const [classicElem] = await buildSendElems([{ type: 'face', faceId: 14 }], ctx); expect(classicElem.face?.index).toBe(14); }); + + it('rejects an unknown id even when building without a live send context', async () => { + sysFaceStore.load(CATALOG); + + await expect(buildSendElems([{ type: 'face', faceId: 99999 }])) + .rejects.toThrow(/absent from the current catalog/); + }); }); diff --git a/packages/protocol/tests/web/group-album-upload.test.ts b/packages/protocol/tests/web/group-album-upload.test.ts new file mode 100644 index 00000000..9de0fed0 --- /dev/null +++ b/packages/protocol/tests/web/group-album-upload.test.ts @@ -0,0 +1,30 @@ +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { uploadImageToGroupAlbum } from '../../src/web/group-album'; +import { RequestUtil } from '../../src/web/request-util'; + +describe('group album image upload', () => { + afterEach(() => { + vi.restoreAllMocks(); + vi.unstubAllGlobals(); + }); + + it('rejects an MP4 before starting a remote upload', async () => { + const request = vi.spyOn(RequestUtil, 'HttpGetJson') + .mockRejectedValue(new Error('unexpected remote upload')); + const fetch = vi.fn(); + vi.stubGlobal('fetch', fetch); + + await expect(uploadImageToGroupAlbum( + { skey: 'SK', p_skey: 'PSK' }, + '12345', + 'album-id', + 'album-name', + 'base64://AAAAGGZ0eXBtcDQyAAAAAG1wNDJpc29t', + '10000', + )).rejects.toThrow('群相册上传仅支持 JPEG、PNG、GIF、WebP 或 BMP 图片'); + + expect(request).not.toHaveBeenCalled(); + expect(fetch).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/protocol/tests/web/group-essence.test.ts b/packages/protocol/tests/web/group-essence.test.ts index 56ba075e..80a60d4a 100644 --- a/packages/protocol/tests/web/group-essence.test.ts +++ b/packages/protocol/tests/web/group-essence.test.ts @@ -45,10 +45,26 @@ describe('group essence pagination', () => { .rejects.toThrow(/retcode 100.*permission denied/); }); - it('rejects a success response without a message list', async () => { + it.each([ + ['an omitted list', { is_end: true }], + ['a null list', { is_end: true, msg_list: null }], + ])('normalizes an ended success response with %s to an empty page', async (_case, data) => { + const request = vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ + retcode: 0, + data, + } as never); + + await expect(getGroupEssenceMsgAll(cookie, '123456789')).resolves.toEqual([{ + retcode: 0, + data: { is_end: true, msg_list: [] }, + }]); + expect(request).toHaveBeenCalledOnce(); + }); + + it('rejects a missing message list before the response explicitly ends', async () => { vi.spyOn(RequestUtil, 'HttpGetJson').mockResolvedValue({ retcode: 0, - data: { is_end: true }, + data: { is_end: false }, } as never); await expect(getGroupEssenceMsgAll(cookie, '123456789')) diff --git a/packages/proton/package.json b/packages/proton/package.json index 8747d95b..f590f48b 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/proton", - "version": "1.14.0", + "version": "1.14.1", "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.", diff --git a/packages/runtime/native/snowluma-linux-arm64.node b/packages/runtime/native/snowluma-linux-arm64.node index 7cb5becd..77d26392 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.node and b/packages/runtime/native/snowluma-linux-arm64.node differ diff --git a/packages/runtime/native/snowluma-linux-arm64.so b/packages/runtime/native/snowluma-linux-arm64.so index ee2b10c4..e20f470f 100644 Binary files a/packages/runtime/native/snowluma-linux-arm64.so and b/packages/runtime/native/snowluma-linux-arm64.so differ diff --git a/packages/runtime/native/snowluma-linux-x64.node b/packages/runtime/native/snowluma-linux-x64.node index 170bac3e..893eecc7 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.node and b/packages/runtime/native/snowluma-linux-x64.node differ diff --git a/packages/runtime/native/snowluma-linux-x64.so b/packages/runtime/native/snowluma-linux-x64.so index 90e5886a..cf752168 100644 Binary files a/packages/runtime/native/snowluma-linux-x64.so and b/packages/runtime/native/snowluma-linux-x64.so differ diff --git a/packages/runtime/native/snowluma-win32-x64.dll b/packages/runtime/native/snowluma-win32-x64.dll index e25ca7fe..9cd0646b 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.dll and b/packages/runtime/native/snowluma-win32-x64.dll differ diff --git a/packages/runtime/native/snowluma-win32-x64.node b/packages/runtime/native/snowluma-win32-x64.node index 768823f2..60fe6ca9 100644 Binary files a/packages/runtime/native/snowluma-win32-x64.node and b/packages/runtime/native/snowluma-win32-x64.node differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 5f5ebf3e..499940b3 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/runtime", - "version": "1.14.0", + "version": "1.14.1", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index cf2e82d9..ada55532 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.0", + "version": "1.14.1", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sdk/src/client/api-client.ts b/packages/sdk/src/client/api-client.ts index 4a8d3a1f..05ded173 100644 --- a/packages/sdk/src/client/api-client.ts +++ b/packages/sdk/src/client/api-client.ts @@ -409,6 +409,28 @@ export abstract class SnowLumaApiClient { return this.call('set_msg_emoji_like', { message_id: messageId, emoji_id: emojiId, set }, options); } + fetchSysFaces(refresh = false, options?: RequestOptions) { + return this.call('fetch_sys_faces', { refresh }, options); + } + + fetchFaceEntity(faceId: number, options: RequestOptions & { refresh?: boolean } = {}) { + return this.call('fetch_face_entity', { + face_id: faceId, + refresh: options.refresh ?? false, + }, options); + } + + searchSysFaces(query: string, options?: RequestOptions) { + return this.call('search_sys_faces', { query }, options); + } + + fetchSuperFaceId(faceId: number, options: RequestOptions & { refresh?: boolean } = {}) { + return this.call('fetch_super_face_id', { + face_id: faceId, + refresh: options.refresh ?? false, + }, options); + } + markAllAsRead(options?: RequestOptions) { return this.call('_mark_all_as_read', {}, options); } @@ -444,12 +466,18 @@ export abstract class SnowLumaApiClient { return this.call('get_clientkey', {}, options); } - getGroupInfoEx(groupId: number, options?: RequestOptions) { - return this.call('get_group_info_ex', { group_id: groupId }, options); + getGroupInfoEx(groupId: number, options?: RequestOptions & { noCache?: boolean }) { + return this.call('get_group_info_ex', { + group_id: groupId, + no_cache: options?.noCache, + }, options); } - getGroupDetailInfo(groupId: number, options?: RequestOptions) { - return this.call('get_group_detail_info', { group_id: groupId }, options); + getGroupDetailInfo(groupId: number, options?: RequestOptions & { noCache?: boolean }) { + return this.call('get_group_detail_info', { + group_id: groupId, + no_cache: options?.noCache, + }, options); } /** Calls any registered SnowLuma action and returns the response data. */ diff --git a/packages/sdk/src/types/actions.ts b/packages/sdk/src/types/actions.ts index 9c27db03..6add8ae1 100644 --- a/packages/sdk/src/types/actions.ts +++ b/packages/sdk/src/types/actions.ts @@ -7,6 +7,8 @@ import type { DomainParams, DownloadFileParams, FetchCustomFaceParams, + FetchFaceEntityParams, + FetchSysFacesParams, FetchEmojiLikeParams, ForwardMessageParams, FriendPokeParams, @@ -70,6 +72,7 @@ import type { AiVoiceParams, DeleteGroupFolderParams, SendPacketParams, + SearchSysFacesParams, } from './params'; import type { CapabilityInfo, @@ -100,6 +103,10 @@ import type { UserOnlineStatus, SendGroupAiRecordResult, CollectionListInfo, + SuperFaceInfo, + SystemFaceCatalogInfo, + SystemFaceInfo, + SystemFaceSearchInfo, } from './results'; export type ActionData = JsonValue; @@ -200,6 +207,10 @@ export interface SnowLumaActionMap { get_recent_contact: { params: JsonObject; data: JsonArray }; get_profile_like: { params: JsonObject; data: JsonObject }; fetch_custom_face: { params: FetchCustomFaceParams; data: string[] }; + fetch_sys_faces: { params: FetchSysFacesParams; data: SystemFaceCatalogInfo }; + fetch_face_entity: { params: FetchFaceEntityParams; data: SystemFaceInfo | null }; + search_sys_faces: { params: SearchSysFacesParams; data: SystemFaceSearchInfo }; + fetch_super_face_id: { params: FetchFaceEntityParams; data: SuperFaceInfo }; get_emoji_likes: { params: GetEmojiLikesParams; data: JsonObject }; fetch_emoji_like: { params: FetchEmojiLikeParams; data: JsonObject }; get_friends_with_category: { params: JsonObject; data: FriendCategoryResult[] }; @@ -221,8 +232,8 @@ export interface SnowLumaActionMap { click_inline_keyboard_button: { params: JsonObject; data: JsonValue }; set_group_sign: { params: JsonObject; data: EmptyData }; send_group_sign: { params: JsonObject; data: EmptyData }; - get_group_info_ex: { params: GroupIdParams; data: JsonObject }; - get_group_detail_info: { params: GroupIdParams; data: JsonObject }; + get_group_info_ex: { params: GetGroupInfoParams; data: JsonObject }; + get_group_detail_info: { params: GetGroupInfoParams; data: JsonObject }; trans_group_file: { params: JsonObject; data: JsonValue }; rename_group_file: { params: JsonObject; data: JsonValue }; get_file: { params: GetMediaParams; data: JsonValue }; diff --git a/packages/sdk/src/types/params.ts b/packages/sdk/src/types/params.ts index cfea50f7..693ea1a2 100644 --- a/packages/sdk/src/types/params.ts +++ b/packages/sdk/src/types/params.ts @@ -302,6 +302,18 @@ export interface FetchCustomFaceParams extends JsonObject { count?: number; } +export interface FetchSysFacesParams extends JsonObject { + refresh?: boolean; +} + +export interface FetchFaceEntityParams extends FetchSysFacesParams { + face_id: number; +} + +export interface SearchSysFacesParams extends JsonObject { + query: string; +} + export interface GetCollectionListParams extends JsonObject { /** Collection category ID; 0 returns every category. */ category?: number; diff --git a/packages/sdk/src/types/results.ts b/packages/sdk/src/types/results.ts index 5fdfa31c..f8c7b553 100644 --- a/packages/sdk/src/types/results.ts +++ b/packages/sdk/src/types/results.ts @@ -175,6 +175,38 @@ export interface CollectionListInfo extends JsonObject { collectionSearchList: CollectionSearchListInfo; } +export interface SystemFaceInfo extends JsonObject { + q_sid: string; + q_des: string; + em_code: string; + q_cid: number | null; + ani_sticker_type: number | null; + ani_sticker_pack_id: number | null; + ani_sticker_id: number | null; + url: string | null; + emoji_name_alias: string[]; + ani_sticker_width: number | null; + ani_sticker_height: number | null; + is_super: boolean; +} + +export interface SystemFacePackInfo extends JsonObject { + pack_name: string; + emojis: SystemFaceInfo[]; +} + +export interface SystemFaceCatalogInfo extends JsonObject { + packs: SystemFacePackInfo[]; +} + +export interface SystemFaceSearchInfo extends JsonObject { + faces: SystemFaceInfo[]; +} + +export interface SuperFaceInfo extends JsonObject { + is_super: boolean; +} + export interface UrlSafetyInfo { level: number; } diff --git a/packages/sdk/tests/http-client.test.ts b/packages/sdk/tests/http-client.test.ts index 0a9f24c6..c3eaaa90 100644 --- a/packages/sdk/tests/http-client.test.ts +++ b/packages/sdk/tests/http-client.test.ts @@ -7,6 +7,44 @@ import { } from '../src'; describe('SnowLumaHttpClient', () => { + it('maps extended group-info refresh options to OneBot field names', async () => { + const fetchImpl = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ + status: 'ok', + retcode: 0, + data: null, + }))); + const client = new SnowLumaHttpClient({ fetch: fetchImpl }); + + await client.getGroupInfoEx(123456, { noCache: true }); + await client.getGroupDetailInfo(123456, { noCache: true }); + + expect(fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))).toEqual([ + { action: 'get_group_info_ex', params: { group_id: 123456, no_cache: true } }, + { action: 'get_group_detail_info', params: { group_id: 123456, no_cache: true } }, + ]); + }); + + it('maps system-face catalog helpers to their OneBot actions', async () => { + const fetchImpl = vi.fn().mockImplementation(async () => new Response(JSON.stringify({ + status: 'ok', + retcode: 0, + data: null, + }))); + const client = new SnowLumaHttpClient({ fetch: fetchImpl }); + + await client.fetchSysFaces(true); + await client.fetchFaceEntity(392, { refresh: true }); + await client.searchSysFaces('dragon'); + await client.fetchSuperFaceId(392); + + expect(fetchImpl.mock.calls.map((call) => JSON.parse((call[1] as RequestInit).body as string))).toEqual([ + { action: 'fetch_sys_faces', params: { refresh: true } }, + { action: 'fetch_face_entity', params: { face_id: 392, refresh: true } }, + { action: 'search_sys_faces', params: { query: 'dragon' } }, + { action: 'fetch_super_face_id', params: { face_id: 392, refresh: false } }, + ]); + }); + it('maps group-announcement options to their OneBot field names', async () => { const fetchImpl = vi.fn().mockResolvedValue(new Response(JSON.stringify({ status: 'ok', diff --git a/packages/ui/package.json b/packages/ui/package.json index 5817da35..95a415a4 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.14.0", + "version": "1.14.1", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index ea35e68a..f9277394 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,7 +1,7 @@ { "license": "SEE LICENSE IN LICENSE", "name": "@snowluma/websocket", - "version": "1.14.0", + "version": "1.14.1", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 42ce317b..dbe8ad76 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -2,7 +2,7 @@ "license": "SEE LICENSE IN LICENSE", "name": "webui", "private": true, - "version": "1.14.0", + "version": "1.14.1", "type": "module", "scripts": { "dev": "vite", diff --git a/tools/check-release-layout.mjs b/tools/check-release-layout.mjs new file mode 100644 index 00000000..c905df0a --- /dev/null +++ b/tools/check-release-layout.mjs @@ -0,0 +1,34 @@ +import fs from 'node:fs'; +import path from 'node:path'; + +const root = path.resolve(process.argv[2] ?? 'dist'); +const entryPoint = path.join(root, 'index.mjs'); + +if (!fs.statSync(root, { throwIfNoEntry: false })?.isDirectory()) { + throw new Error(`release directory does not exist: ${root}`); +} +if (!fs.statSync(entryPoint, { throwIfNoEntry: false })?.isFile()) { + throw new Error(`release entry point must be at the archive root: ${entryPoint}`); +} + +const forbidden = []; +const pending = [root]; +while (pending.length > 0) { + const directory = pending.pop(); + if (!directory) continue; + + for (const entry of fs.readdirSync(directory, { withFileTypes: true })) { + if (!entry.isDirectory()) continue; + const absolute = path.join(directory, entry.name); + if (/snowluma/i.test(entry.name)) { + forbidden.push(path.relative(root, absolute)); + } + pending.push(absolute); + } +} + +if (forbidden.length > 0) { + throw new Error(`release contains forbidden directory names:\n${forbidden.join('\n')}`); +} + +console.log(`Release layout verified: ${root}`);