refactor(onebot): extract OneBot protocol translation into @snowluma/onebot

Phase 3 of the 4-package split (RoadMap #3). Moves the entire
`packages/core/src/onebot/` subtree (43 source files + 20 test files
spanning network adapters, action handlers, event converters, message
parser, message store, media store, instance + manager) into the new
`@snowluma/onebot` workspace package. The remaining `@snowluma/core`
now hosts only the api-layer (Bridge class + 13 Api classes), the
hook tooling, the WebUI server, and the runnable `index.ts`.

Why
---
- The OneBot adapter is the public-facing OneBot11 protocol surface;
  it has its own version cadence and its own consumers (third-party
  bots talking OneBot WS / HTTP). Splitting it lets that cadence move
  independently of the Api-on-ctx layer.
- The two were sharing the `packages/core/` build pipeline only
  because they happened to live in the same directory. Nothing in
  the api-layer reaches into OneBot internals.
- Mirrors NapCat / Lagrange.OneBot's repo split (their OneBot adapter
  is a separate assembly from the Core protocol library).

Layout
------
Moved via `git mv` (history preserved):
  packages/core/src/onebot/*  → @snowluma/onebot/src/<x>
  packages/core/tests/onebot/* (6 files)   → @snowluma/onebot/tests/
  packages/core/tests/{message-parser,message-store,event-pipeline,
    media-store,media-url-resolver,event-converter,
    http-server-hot-reload,http-server-content-type,
    api-handler-logging,message-id,group-msg-emoji-like,
    config,media-indexer,network-manager}.test.ts (14 files)
                                              → @snowluma/onebot/tests/

What stays in @snowluma/core
----------------------------
- `bridge/{bridge,bridge-interface,bridge-context,manager}.ts`
- `bridge/apis/*` (the 13 typed Api classes)
- `hook/*` (debugger/injector — tooling for the core protocol layer)
- `webui/*` (admin UI server — application wiring, not the OneBot
  adapter itself)
- `index.ts` (application entry that wires BridgeManager +
  OneBotManager + HookManager + WebUI together)

Changes
-------
- New package `packages/onebot/` (package.json with subpath exports
  mirroring legacy `core/src/onebot/<x>` 1:1, tsconfig.json,
  vitest.config.ts with `SNOWLUMA_LOG_LEVEL=debug` env so the action-
  dispatch logging tests see debug-level subscribers — copied verbatim
  from core's vitest.config.ts).
- @snowluma/core grows new subpath exports for the api-layer files
  OneBot's type-only imports need: `./bridge`, `./bridge-interface`,
  `./bridge-context`, `./manager`, `./apis`.
- `@snowluma/onebot` depends on `@snowluma/bridge`, `@snowluma/common`,
  `@snowluma/core`, `@snowluma/proto-defs`, `@snowluma/proton`,
  `@snowluma/websocket`.
- `@snowluma/core` depends on `@snowluma/onebot` (for index.ts +
  webui/server.ts wiring).
- 100+ import sites rewritten via sed:
  * OneBot → core: `'../bridge/bridge'` → `'@snowluma/core/bridge'`,
    `'../bridge/manager'` → `'@snowluma/core/manager'`,
    `'../bridge/bridge-interface'` → `'@snowluma/core/bridge-interface'`,
    `'@/bridge/bridge'` (vite path alias) → `'@snowluma/core/bridge'`.
  * Core → OneBot: `'./onebot/manager'` → `'@snowluma/onebot/manager'`,
    `'../onebot/config'` → `'@snowluma/onebot/config'`, etc.
  * Test relative paths: `'../../src/onebot/<x>'` → `'../src/<x>'`
    after the test file move (one level shallower).
- New `packages/onebot/src/env.d.ts` declaring `__APP_VERSION__` and
  `__BUILD_WEBUI__` (the vite-injected globals `info.ts` reads).

Workspace cycle
---------------
core ↔ onebot is allowed by pnpm workspaces. The runtime direction
is one-way: core → onebot (index.ts constructs OneBotManager,
webui/server reads OneBot config). OneBot only reaches into core for
TYPES (Bridge, BridgeInterface, BridgeManager, ClientKeyInfo,
DownloadRKeyInfo); those imports use `import type` so they compile
out at runtime and don't introduce a real cycle.

Verification
------------
- Full workspace `pnpm -r typecheck`: all 11 projects clean.
- `@snowluma/core` test suite: 302/302 pass (33 test files).
- `@snowluma/onebot` test suite: 250/250 pass (20 test files;
  pre-existing `network-manager.test.ts` native-addon failure
  unchanged — same baseline as before the split).
- Combined: 552/552 — identical pass count to the pre-Phase-3
  baseline.
- Vite build with stubbed native binary: clean, 2.84 MB bundle /
  224 KB gzip (identical envelope).
This commit is contained in:
DrSmoothl committed 2026-05-21 08:52:00 +08:00
1 parent f7a03ca05a
commit 9a30df9907
71 files changed
+286 -59

No files matched your search

+103
View File
@@ -0,0 +1,103 @@
{
"name": "@snowluma/onebot",
"version": "1.9.0",
"private": true,
"type": "module",
"description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis.<area>.method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/<x>'` collapses to `import { … } from '@snowluma/onebot/<x>'`.",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": {
"types": "./src/index.ts",
"default": "./src/index.ts"
},
"./manager": {
"types": "./src/manager.ts",
"default": "./src/manager.ts"
},
"./instance": {
"types": "./src/instance.ts",
"default": "./src/instance.ts"
},
"./instance-context": {
"types": "./src/instance-context.ts",
"default": "./src/instance-context.ts"
},
"./api-handler": {
"types": "./src/api-handler.ts",
"default": "./src/api-handler.ts"
},
"./config": {
"types": "./src/config.ts",
"default": "./src/config.ts"
},
"./types": {
"types": "./src/types.ts",
"default": "./src/types.ts"
},
"./message-id": {
"types": "./src/message-id.ts",
"default": "./src/message-id.ts"
},
"./message-parser": {
"types": "./src/message-parser.ts",
"default": "./src/message-parser.ts"
},
"./message-store": {
"types": "./src/message-store.ts",
"default": "./src/message-store.ts"
},
"./media-store": {
"types": "./src/media-store.ts",
"default": "./src/media-store.ts"
},
"./media-indexer": {
"types": "./src/media-indexer.ts",
"default": "./src/media-indexer.ts"
},
"./media-url-resolver": {
"types": "./src/media-url-resolver.ts",
"default": "./src/media-url-resolver.ts"
},
"./event-filter": {
"types": "./src/event-filter.ts",
"default": "./src/event-filter.ts"
},
"./event-pipeline": {
"types": "./src/event-pipeline.ts",
"default": "./src/event-pipeline.ts"
},
"./event-converter": {
"types": "./src/event-converter/index.ts",
"default": "./src/event-converter/index.ts"
},
"./event-converter/utils": {
"types": "./src/event-converter/utils.ts",
"default": "./src/event-converter/utils.ts"
},
"./instance-rkey": {
"types": "./src/instance-rkey.ts",
"default": "./src/instance-rkey.ts"
}
},
"scripts": {
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@snowluma/bridge": "workspace:*",
"@snowluma/common": "workspace:*",
"@snowluma/core": "workspace:*",
"@snowluma/proto-defs": "workspace:*",
"@snowluma/proton": "workspace:*",
"@snowluma/websocket": "workspace:*"
},
"devDependencies": {
"@hono/node-server": "^1.19.14",
"@types/node": "^24.12.2",
"hono": "^4.12.14",
"typescript": "catalog:",
"vite": "catalog:",
"vitest": "^4.1.4"
}
}
File diff suppressed because it is too large. Load diff
+30
View File
@@ -0,0 +1,30 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_friend_list', async () => {
if (ctx.getFriendList) {
return okResponse(await ctx.getFriendList());
}
return okResponse([]);
});
h.registerAction('get_stranger_info', async (params) => {
const userId = asNumber(params.user_id);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
if (ctx.getStrangerInfo) {
const info = await ctx.getStrangerInfo(userId);
return okResponse(info ?? { user_id: userId, nickname: '', sex: 'unknown', age: 0 });
}
return okResponse({ user_id: userId, nickname: '', sex: 'unknown', age: 0 });
});
h.registerAction('delete_friend', async (params) => {
const userId = asNumber(params.user_id);
const block = asBoolean(params.block, false);
if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
await ctx.handleDeleteFriend(userId, block);
return okResponse();
});
}
+122
View File
@@ -0,0 +1,122 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_group_kick', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupKick(groupId, userId, reject);
return okResponse();
});
h.registerAction('set_group_kick_members', async (params) => {
const groupId = asNumber(params.group_id);
const userIds = Array.isArray(params.user_id) ? params.user_id.map(asNumber).filter(Boolean) : [];
const reject = asBoolean(params.reject_add_request, false);
if (!groupId || userIds.length === 0) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id array are required');
await ctx.setGroupKickMembers(groupId, userIds, reject);
return okResponse();
});
h.registerAction('set_group_ban', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const duration = asNumber(params.duration) || 1800;
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.setGroupBan(groupId, userId, duration);
return okResponse();
});
h.registerAction('set_group_whole_ban', async (params) => {
const groupId = asNumber(params.group_id);
const enable = asBoolean(params.enable, true);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupWholeBan(groupId, enable);
return okResponse();
});
h.registerAction('set_group_add_option', async (params) => {
const groupId = asNumber(params.group_id);
const addType = asNumber(params.add_type);
if (!groupId || addType === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and add_type are required');
await ctx.bridge.apis.groupAdmin.setAddOption(groupId, addType);
return okResponse();
});
h.registerAction('set_group_search', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.setSearch(groupId);
return okResponse();
});
h.registerAction('set_group_admin', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const enable = asBoolean(params.enable, true);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setAdmin(groupId, userId, enable);
return okResponse();
});
h.registerAction('set_group_card', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const card = asString(params.card);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setCard(groupId, userId, card);
return okResponse();
});
h.registerAction('set_group_name', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.group_name);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.bridge.apis.groupAdmin.setName(groupId, name);
return okResponse();
});
h.registerAction('set_group_leave', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
await ctx.setGroupLeave(groupId);
return okResponse();
});
h.registerAction('set_group_special_title', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
const title = asString(params.special_title);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
await ctx.bridge.apis.groupAdmin.setSpecialTitle(groupId, userId, title);
return okResponse();
});
h.registerAction('set_group_anonymous', async () => {
return okResponse();
});
h.registerAction('set_group_anonymous_ban', async () => {
return okResponse();
});
// Highway upload with cmdId 3000 + GroupAvatarExtra (Lagrange protocol).
// `file` accepts everything bridge.setGroupAvatar's underlying
// loadBinarySource handles: local paths, file:// URLs, http(s) URLs,
// and base64:// data URIs — same surface as set_qq_avatar.
h.registerAction('set_group_portrait', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.bridge.apis.profile.setGroupAvatar(groupId, file);
return okResponse();
} catch (err) {
return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err));
}
});
}
+132
View File
@@ -0,0 +1,132 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_album_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
try {
const albumList = await ctx.getGroupAlbumList(groupId);
return okResponse(albumList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('upload_image_to_qun_album', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const albumName = asString(params.album_name);
const file = asString(params.file);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!albumName) return failedResponse(RETCODE.BAD_REQUEST, 'album_name is required');
if (!file) return failedResponse(RETCODE.BAD_REQUEST, 'file is required');
try {
await ctx.uploadImageToGroupAlbum(groupId, albumId, albumName, file);
return okResponse(null);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to upload image to group album';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('get_group_album_media_list', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const attachInfo = asString(params.attach_info) || '';
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
try {
const mediaList = await ctx.getGroupAlbumMediaList(groupId, albumId, attachInfo);
return okResponse(mediaList);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to get group album media list';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('do_group_album_comment', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
const content = asString(params.content);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
if (!albumId) return failedResponse(RETCODE.BAD_REQUEST, 'album_id is required');
if (!lloc) return failedResponse(RETCODE.BAD_REQUEST, 'lloc is required');
if (!content) return failedResponse(RETCODE.BAD_REQUEST, 'content is required');
try {
const comment = await ctx.commentGroupAlbumMedia(groupId, albumId, lloc, content);
return okResponse(comment);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to comment on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('set_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, true);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to set like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
// 取消点赞群相册媒体
h.registerAction('cancel_group_album_media_like', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const batchId = asString(params.batch_id);
const lloc = params.lloc ? asString(params.lloc) : undefined; // 可选参数
if (!groupId || !albumId || !batchId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and batch_id are required');
}
try {
const res = await ctx.likeGroupAlbumMedia(groupId, albumId, batchId, lloc, false);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to cancel like on album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
h.registerAction('del_group_album_media', async (params) => {
const groupId = asNumber(params.group_id);
const albumId = asString(params.album_id);
const lloc = asString(params.lloc);
if (!groupId || !albumId || !lloc) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, album_id and lloc are required');
}
try {
const res = await ctx.deleteGroupAlbumMedia(groupId, albumId, lloc);
return okResponse(res);
} catch (error) {
const message = error instanceof Error ? error.message : 'failed to delete album media';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
});
}
+118
View File
@@ -0,0 +1,118 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asBoolean, asNumber, asString } from '../api-handler';
import { RETCODE, failedResponse } from '../types';
import { okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('upload_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const file = asString(params.file);
const name = asString(params.name);
const folderId = asString(params.folder) || asString(params.folder_id) || '/';
const uploadFile = asBoolean(params.upload_file, true);
if (!groupId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file are required');
const fileId = await ctx.uploadGroupFile(groupId, file, name, folderId, uploadFile);
return okResponse({ file_id: fileId });
});
h.registerAction('upload_private_file', async (params) => {
const userId = asNumber(params.user_id);
const file = asString(params.file);
const name = asString(params.name);
const uploadFile = asBoolean(params.upload_file, true);
if (!userId || !file) return failedResponse(RETCODE.BAD_REQUEST, 'user_id and file are required');
const fileId = await ctx.uploadPrivateFile(userId, file, name, uploadFile);
return okResponse({ file_id: fileId });
});
h.registerAction('get_group_file_url', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const busId = asNumber(params.busid) || 102;
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
return okResponse({ url: await ctx.getGroupFileUrl(groupId, fileId, busId) });
});
h.registerAction('get_group_root_files', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
return okResponse(await ctx.getGroupFiles(groupId, '/'));
});
h.registerAction('get_group_files_by_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id) || asString(params.folder) || '/';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
return okResponse(await ctx.getGroupFiles(groupId, folderId));
});
h.registerAction('delete_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
if (!groupId || !fileId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and file_id are required');
}
await ctx.bridge.apis.groupFile.delete(groupId, fileId);
return okResponse();
});
h.registerAction('move_group_file', async (params) => {
const groupId = asNumber(params.group_id);
const fileId = asString(params.file_id);
const parentDirectory = asString(params.parent_directory);
const targetDirectory = asString(params.target_directory);
if (!groupId || !fileId || !parentDirectory || !targetDirectory) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, file_id, parent_directory and target_directory are required');
}
await ctx.bridge.apis.groupFile.move(groupId, fileId, parentDirectory, targetDirectory);
return okResponse();
});
h.registerAction('create_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const name = asString(params.name);
const parentId = asString(params.parent_id) || '/';
if (!groupId || !name) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and name are required');
}
await ctx.createGroupFileFolder(groupId, name, parentId);
return okResponse();
});
h.registerAction('delete_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
if (!groupId || !folderId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id and folder_id are required');
}
await ctx.bridge.apis.groupFile.deleteFolder(groupId, folderId);
return okResponse();
});
h.registerAction('rename_group_file_folder', async (params) => {
const groupId = asNumber(params.group_id);
const folderId = asString(params.folder_id);
const newName = asString(params.new_folder_name) || asString(params.name);
if (!groupId || !folderId || !newName) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id, folder_id and new_folder_name are required');
}
await ctx.bridge.apis.groupFile.renameFolder(groupId, folderId, newName);
return okResponse();
});
h.registerAction('get_private_file_url', async (params) => {
const userId = asNumber(params.user_id);
const fileId = asString(params.file_id);
const fileHash = asString(params.file_hash);
if (!userId || !fileId || !fileHash) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id, file_id and file_hash are required');
}
return okResponse({ url: await ctx.getPrivateFileUrl(userId, fileId, fileHash) });
});
}
+84
View File
@@ -0,0 +1,84 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asBoolean, asString } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
import { WebHonorType } from '@snowluma/bridge/web/group-honor';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_group_list', async (params) => {
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupList) {
return okResponse(await ctx.getGroupList(noCache));
}
return okResponse([]);
});
h.registerAction('get_group_info', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupInfo) {
const info = await ctx.getGroupInfo(groupId, noCache);
return okResponse(info ?? { group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
}
return okResponse({ group_id: groupId, group_name: '', member_count: 0, max_member_count: 0 });
});
h.registerAction('get_group_member_list', async (params) => {
const groupId = asNumber(params.group_id);
if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberList) {
return okResponse(await ctx.getGroupMemberList(groupId, noCache));
}
return okResponse([]);
});
h.registerAction('get_group_member_info', async (params) => {
const groupId = asNumber(params.group_id);
const userId = asNumber(params.user_id);
if (!groupId || !userId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id and user_id are required');
const noCache = asBoolean(params.no_cache, false);
if (ctx.getGroupMemberInfo) {
const info = await ctx.getGroupMemberInfo(groupId, userId, noCache);
return okResponse(info ?? {
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
}
return okResponse({
group_id: groupId, user_id: userId, nickname: '', card: '',
sex: 'unknown', age: 0, join_time: 0, last_sent_time: 0,
level: '0', role: 'member', title: '',
});
});
h.registerAction('get_group_honor_info', async (params) => {
const groupId = asNumber(params.group_id);
const typeStr = asString(params.type) || 'all';
if (!groupId) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
const typeValues = Object.values(WebHonorType) as string[];
if (!typeValues.includes(typeStr)) {
return failedResponse(RETCODE.BAD_REQUEST, `invalid type, must be one of ${typeValues.join(', ')}`);
}
try {
const honorInfo = await ctx.bridge.apis.web.getHonorInfo(groupId, typeStr as WebHonorType);
return okResponse(honorInfo);
} catch (e) {
return failedResponse(RETCODE.ACTION_FAILED, `failed to get group honor info: ${(e as Error).message}`);
}
});
h.registerAction('get_group_system_msg', async () => {
if (ctx.handleGetGroupSystemMsg) {
return okResponse(await ctx.handleGetGroupSystemMsg());
}
return okResponse([]);
});
}
+33
View File
@@ -0,0 +1,33 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('get_login_info', async () => {
const login = ctx.getLoginInfo();
return okResponse({ user_id: login.userId, nickname: login.nickname });
});
h.registerAction('get_status', async () => {
const online = ctx.isOnline();
return okResponse({ online, good: online });
});
// __APP_VERSION__ is injected by Vite from the monorepo root package.json;
// it's undefined under vitest (no define plugin), so fall back to 'dev'.
const appVersion = typeof __APP_VERSION__ !== 'undefined' ? __APP_VERSION__ : 'dev';
h.registerAction('get_version_info', async () => {
return okResponse({
app_name: 'SnowLuma',
app_version: `${appVersion}-node`,
protocol_version: 'v11',
});
});
h.registerAction('can_send_image', async () => {
return okResponse({ yes: ctx.canSendImage?.() ?? false });
});
h.registerAction('can_send_record', async () => {
return okResponse({ yes: ctx.canSendRecord?.() ?? false });
});
}
+97
View File
@@ -0,0 +1,97 @@
import type { JsonObject, JsonValue } from '../types';
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asNumber, asString, asBoolean, asMessage } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('send_msg', async (params) => {
const messageType = asString(params.message_type);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
if (messageType === 'group' || params.group_id !== undefined) {
const groupId = asNumber(params.group_id);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
}
const userId = asNumber(params.user_id);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('send_private_msg', async (params) => {
const userId = asNumber(params.user_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(userId) || userId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
const result = await ctx.sendPrivateMessage(userId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('send_group_msg', async (params) => {
const groupId = asNumber(params.group_id);
const message = asMessage(params.message);
const autoEscape = asBoolean(params.auto_escape, false);
if (!Number.isInteger(groupId) || groupId <= 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required');
}
if (message === undefined) {
return failedResponse(RETCODE.BAD_REQUEST, 'message is required');
}
const result = await ctx.sendGroupMessage(groupId, message, autoEscape);
return okResponse({ message_id: result.messageId });
});
h.registerAction('get_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const data = ctx.getMessage(messageId);
if (!data) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found');
}
const result: JsonObject = { ...data };
delete result.post_type;
delete result.self_id;
result.real_id = (result.message_id ?? messageId) as JsonValue;
return okResponse(result);
});
h.registerAction('delete_msg', async (params) => {
const messageId = asNumber(params.message_id);
if (!Number.isInteger(messageId) || messageId === 0) {
return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required');
}
const meta = ctx.getMessageMeta(messageId);
if (!meta) {
return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not retractable');
}
await ctx.deleteMessage(messageId, meta);
return okResponse();
});
}
+23
View File
@@ -0,0 +1,23 @@
import type { ApiHandler, ApiActionContext } from '../api-handler';
import { asString, asBoolean } from '../api-handler';
import { RETCODE, failedResponse, okResponse } from '../types';
export function register(h: ApiHandler, ctx: ApiActionContext): void {
h.registerAction('set_friend_add_request', async (params) => {
const flag = asString(params.flag);
const approve = asBoolean(params.approve, true);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
await ctx.handleFriendRequest(flag, approve);
return okResponse();
});
h.registerAction('set_group_add_request', async (params) => {
const flag = asString(params.flag);
const subType = asString(params.sub_type, asString(params.type, 'add'));
const approve = asBoolean(params.approve, true);
const reason = asString(params.reason);
if (!flag) return failedResponse(RETCODE.BAD_REQUEST, 'flag is required');
await ctx.handleGroupRequest(flag, subType, approve, reason);
return okResponse();
});
}
+274
View File
@@ -0,0 +1,274 @@
import type { JsonObject, JsonValue, MessageMeta } from './types';
import type { ForwardPreviewMeta } from './modules/message-actions';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { RETCODE, failedResponse } from './types';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { summarizeParams } from '@snowluma/common/log-summary';
const moduleLog = createLogger('Bridge.Action');
import { register as registerInfo } from './actions/info';
import { register as registerMessage } from './actions/message';
import { register as registerFriend } from './actions/friend';
import { register as registerGroupInfo } from './actions/group-info';
import { register as registerGroupAdmin } from './actions/group-admin';
import { register as registerGroupFile } from './actions/group-file';
import { register as registerRequest } from './actions/request';
import { register as registerExtended } from './actions/extended';
import { register as registerGroupAlbum } from './actions/group-album';
import { WebHonorType } from '@snowluma/bridge/web/group-honor';
import type { ClientKeyInfo } from '@snowluma/core/bridge';
export interface MessageSendResult {
messageId: number;
meta?: MessageMeta;
echoEvent?: JsonObject;
}
export interface GroupEssenceMsgRet {
retcode: number;
data: {
is_end: boolean;
msg_list: any[];
[key: string]: any;
};
[key: string]: any;
}
export interface ApiActionContext {
/**
* Direct access to the BridgeInterface. Use for actions that are pure
* 1:1 calls to a Bridge method — no rename, no default args, no
* composition with messageStore / mediaStore. When translation IS
* needed, route through the named adapters declared below instead.
*/
bridge: BridgeInterface;
getLoginInfo: () => { userId: number; nickname: string };
isOnline: () => boolean;
getMessage: (messageId: number) => JsonObject | null;
getMessageMeta: (messageId: number) => MessageMeta | null;
sendPrivateMessage: (userId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
sendGroupMessage: (groupId: number, message: JsonValue, autoEscape: boolean) => Promise<MessageSendResult>;
deleteMessage: (messageId: number, meta: MessageMeta) => Promise<void>;
canSendImage: () => boolean;
canSendRecord: () => boolean;
// Info retrieval (async — triggers OIDB fetch)
getFriendList: () => Promise<JsonObject[]>;
getGroupList: (noCache?: boolean) => Promise<JsonObject[]>;
getGroupInfo: (groupId: number, noCache?: boolean) => Promise<JsonObject | null>;
getGroupMemberList: (groupId: number, noCache?: boolean) => Promise<JsonObject[]>;
getGroupMemberInfo: (groupId: number, userId: number, noCache?: boolean) => Promise<JsonObject | null>;
getStrangerInfo: (userId: number) => Promise<JsonObject | null>;
// Group admin (adapters: rename Bridge methods to OneBot vocabulary)
setGroupKick: (groupId: number, userId: number, rejectAdd: boolean) => Promise<void>;
setGroupKickMembers: (groupId: number, userIds: number[], rejectAdd: boolean) => Promise<void>;
setGroupBan: (groupId: number, userId: number, duration: number) => Promise<void>;
setGroupWholeBan: (groupId: number, enable: boolean) => Promise<void>;
setGroupLeave: (groupId: number) => Promise<void>;
// Group file (adapters: field extraction + Bridge name translation)
uploadGroupFile: (groupId: number, file: string, name?: string, folderId?: string, uploadFile?: boolean) => Promise<string | null>;
uploadPrivateFile: (userId: number, file: string, name?: string, uploadFile?: boolean) => Promise<string | null>;
getGroupFileUrl: (groupId: number, fileId: string, busId?: number) => Promise<string>;
getGroupFiles: (groupId: number, folderId?: string) => Promise<JsonObject>;
createGroupFileFolder: (groupId: number, name: string, parentId?: string) => Promise<void>;
getPrivateFileUrl: (userId: number, fileId: string, fileHash: string) => Promise<string>;
getGroupFileCount: (groupId: number) => Promise<{ fileCount: number; maxCount: number }>;
// Requests (adapters: rename to OneBot vocabulary)
handleFriendRequest: (flag: string, approve: boolean) => Promise<void>;
handleGroupRequest: (flag: string, subType: string, approve: boolean, reason: string) => Promise<void>;
// Pokes (adapters: flatten isGroup into bridge.sendPoke signature)
sendFriendPoke: (userId: number, targetId?: number) => Promise<void>;
sendGroupPoke: (groupId: number, userId: number) => Promise<void>;
// Essence (adapter: bakes the set/unset boolean)
setEssenceMsg: (messageId: number) => Promise<void>;
deleteEssenceMsg: (messageId: number) => Promise<void>;
// Profile reads with OneBot-specific default args
getProfileLike: (userId?: number, start?: number, limit?: number) => Promise<any>;
getGroupEssence: (groupId: number, pageStart?: number, pageLimit?: number) => Promise<GroupEssenceMsgRet>;
// Friend deletion (adapter: rename + force-boolean)
handleDeleteFriend: (userId: number, block?: boolean) => Promise<void>;
// Module wrappers / multi-dep compositions
getGroupMsgHistory: (groupId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
getFriendMsgHistory: (userId: number, messageId?: number, count?: number) => Promise<JsonObject[]>;
handleGetGroupSystemMsg: () => Promise<JsonObject[]>;
getDownloadRKeys: () => Promise<JsonObject[]>;
sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>;
sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>;
getForwardMsg: (resId: string) => Promise<JsonObject[]>;
forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>;
// Extended NapCat-compatible
setFriendRemark: (userId: number, remark: string) => Promise<void>;
setGroupRemark: (groupId: number, remark: string) => Promise<void>;
setGroupAvatar: (groupId: number, source: string) => Promise<void>;
setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise<void>;
markGroupMsgAsRead: (groupId: number, sequence: number) => Promise<void>;
markPrivateMsgAsRead: (userId: number, sequence: number) => Promise<void>;
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => Promise<void>;
setProfile: (nickname?: string, personalNote?: string) => Promise<void>;
fetchCustomFace: (count?: number) => Promise<string[]>;
getEmojiLikes: (groupId: number, sequence: number, emojiId: string, emojiType?: number, count?: number, cookie?: string) => Promise<{ users: Array<{ uin: number }>, cookie: string, isLast: boolean }>;
// Web
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => Promise<any>;
getGroupEssenceAll: (groupId: number) => Promise<GroupEssenceMsgRet[]>;
getGroupAlbumList: (groupId: number) => Promise<any>;
uploadImageToGroupAlbum: (groupId: number, albumId: string, albumName: string, filePath: string) => Promise<void>;
getGroupAlbumMediaList: (groupId: number, albumId: string, attachInfo?: string) => Promise<any>;
commentGroupAlbumMedia: (groupId: number, albumId: string, lloc: string, content: string) => Promise<any>;
deleteGroupAlbumMedia: (groupId: number, albumId: string, lloc: string) => Promise<any>;
likeGroupAlbumMedia: (groupId: number, albumId: string, batchId: string, lloc: string | undefined, isLike: boolean) => Promise<any>;
sendGroupNotice: (groupId: number, content: string, options?: any) => Promise<any>;
getGroupNotice: (groupId: number) => Promise<any[]>;
deleteGroupNotice: (groupId: number, fid: string) => Promise<boolean>;
getCookiesStr: (domain: string) => Promise<string>;
getCsrfToken: () => Promise<number>;
getCredentials: (domain: string) => Promise<{ cookies: string; token: number; csrf_token: number }>;
forceFetchClientKey: () => Promise<ClientKeyInfo>;
// Media lookup (populated from previously dispatched message segments)
getImageInfo: (file: string) => Promise<JsonObject | null>;
getRecordInfo: (file: string) => Promise<JsonObject | null>;
}
type ActionHandler = (params: JsonObject) => Promise<import('./types').ApiResponse>;
export class ApiHandler {
private readonly handlers = new Map<string, ActionHandler>();
private readonly log: Logger;
constructor(context: ApiActionContext, uin?: number) {
this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog;
registerInfo(this, context);
registerMessage(this, context);
registerFriend(this, context);
registerGroupInfo(this, context);
registerGroupAdmin(this, context);
registerGroupFile(this, context);
registerRequest(this, context);
registerExtended(this, context);
registerGroupAlbum(this, context);
}
registerAction(action: string, handler: ActionHandler): void {
this.handlers.set(action, handler);
}
async handle(action: string, params: JsonObject): Promise<import('./types').ApiResponse> {
const handler = this.handlers.get(action);
if (!handler) {
this.log.debug('unknown action %s', action);
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
}
// Entry log goes to file always (debug); console only when level is
// dialed down to debug. Caller-perspective summary lets the operator
// grep "what did the bot get asked to do" without scraping wire logs.
this.log.debug('%s params=%s', action, summarizeParams(params));
try {
return await handler(params);
} catch (error) {
// Action failures are almost always param-shape problems coming
// from the OneBot client; warn (not error) is the right level so
// the log file stays a useful signal of real internal faults.
this.log.warn('%s failed: %s\n%s',
action,
error instanceof Error ? error.message : String(error),
error instanceof Error ? (error.stack ?? '') : '');
const message = error instanceof Error ? error.message : 'internal error';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}
}
async processRequest(rawRequest: string): Promise<string> {
if (!rawRequest.trim()) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
try {
const parsed = JSON.parse(rawRequest) as unknown;
if (!isJsonObject(parsed)) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
const action = asString(parsed.action);
if (!action) {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
const params = isJsonObject(parsed.params) ? parsed.params : {};
const echo = parsed.echo;
const response = await this.handle(action, params);
if (echo !== undefined) {
response.echo = toJsonValue(echo);
}
return JSON.stringify(response);
} catch {
return JSON.stringify(failedResponse(RETCODE.BAD_REQUEST, 'bad request'));
}
}
}
function isJsonObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
export function asString(value: unknown, fallback = ''): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return fallback;
}
export function asNumber(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) return Math.trunc(n);
}
return 0;
}
export function asBoolean(value: unknown, fallback: boolean): boolean {
if (typeof value === 'boolean') return value;
if (typeof value === 'number') return value !== 0;
if (typeof value === 'string') {
const text = value.trim().toLowerCase();
if (text === 'true' || text === '1' || text === 'yes' || text === 'on') return true;
if (text === 'false' || text === '0' || text === 'no' || text === 'off') return false;
}
return fallback;
}
export function toJsonValue(value: unknown): JsonValue {
if (value === null) return null;
if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return value;
if (Array.isArray(value)) return value.map(toJsonValue);
if (isJsonObject(value)) {
const obj: JsonObject = {};
for (const [key, item] of Object.entries(value)) {
obj[key] = toJsonValue(item);
}
return obj;
}
return String(value);
}
export function asMessage(value: unknown): import('./types').JsonValue | undefined {
if (value === undefined) return undefined;
if (typeof value === 'string') {
const trimmed = value.trim();
if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
try {
const parsed = JSON.parse(trimmed);
if (Array.isArray(parsed)) {
return toJsonValue(parsed);
}
} catch {
// Fallback to literal text if it just looks like an array but is invalid JSON
}
}
}
return toJsonValue(value);
}
+386
View File
@@ -0,0 +1,386 @@
import fs from 'fs';
import path from 'path';
import { randomBytes } from 'crypto';
import { createLogger } from '@snowluma/common/logger';
import type {
HttpClientNetwork,
HttpServerNetwork,
JsonObject,
MessageFormat,
OneBotConfig,
OneBotNetworks,
WsClientNetwork,
WsRole,
WsServerNetwork,
} from './types';
const log = createLogger('OneBot.Config');
const CONFIG_DIR = 'config';
const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json');
const DEFAULT_ACCESS_TOKEN_BYTES = 32;
export function makeDefaultOneBotConfig(): OneBotConfig {
return {
networks: {
httpServers: [{
name: 'http-default',
host: '0.0.0.0',
port: 3000,
path: '/',
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}],
httpClients: [],
wsServers: [{
name: 'ws-default',
host: '0.0.0.0',
port: 3001,
path: '/',
role: 'Universal',
accessToken: generateAccessToken(),
messageFormat: 'array',
reportSelfMessage: false,
}],
wsClients: [],
},
musicSignUrl: '',
};
}
function generateAccessToken(): string {
return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url');
}
export interface LoadOneBotConfigOptions {
/**
* Persist the normalized config to disk when the file is missing or was
* in legacy format. Default `false` so accidental call sites (read-only
* GETs in particular) don't generate fresh access tokens, race on
* concurrent writes, or surprise the operator with materialized files.
* Pass `true` from boot / explicit POST handlers.
*/
persistDefaults?: boolean;
}
export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig {
ensureConfigDir();
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
const globalRaw = tryLoadJson(DEFAULT_CONFIG_PATH);
const perUinRaw = tryLoadJson(perUinPath);
// Detect legacy on-disk format (top-level per-type arrays). We auto-migrate
// these entries into `networks.*` and rewrite the file on the next save.
const legacy = !!perUinRaw && hasLegacyTopLevel(perUinRaw);
const sources: JsonObject[] = [];
if (globalRaw) sources.push(globalRaw);
if (perUinRaw) sources.push(perUinRaw);
const config = fromJson(sources, !perUinRaw && !globalRaw);
if (options.persistDefaults && (!perUinRaw || legacy)) {
saveOneBotConfig(uin, config);
}
return config;
}
export function saveOneBotConfig(uin: string, config: OneBotConfig): void {
ensureConfigDir();
const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`);
saveJson(perUinPath, toJsonObject(config));
}
function ensureConfigDir(): void {
fs.mkdirSync(CONFIG_DIR, { recursive: true });
}
function toJsonObject(config: OneBotConfig): JsonObject {
const nets = config.networks;
return {
networks: {
httpServers: nets.httpServers.map(httpServerToJson),
httpClients: nets.httpClients.map(httpClientToJson),
wsServers: nets.wsServers.map(wsServerToJson),
wsClients: nets.wsClients.map(wsClientToJson),
},
musicSignUrl: config.musicSignUrl ?? '',
};
}
function applyBase(
out: JsonObject,
n: { name: string; enabled?: boolean; accessToken?: string; messageFormat: MessageFormat; reportSelfMessage: boolean },
): void {
out.name = n.name;
if (n.enabled === false) out.enabled = false;
if (n.accessToken) out.accessToken = n.accessToken;
out.messageFormat = n.messageFormat;
out.reportSelfMessage = n.reportSelfMessage;
}
function httpServerToJson(n: HttpServerNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.host = n.host ?? '0.0.0.0';
out.port = n.port;
out.path = n.path ?? '/';
return out;
}
function httpClientToJson(n: HttpClientNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.url = n.url;
if (typeof n.timeoutMs === 'number' && n.timeoutMs > 0) out.timeoutMs = n.timeoutMs;
return out;
}
function wsServerToJson(n: WsServerNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.host = n.host ?? '0.0.0.0';
out.port = n.port;
out.path = n.path ?? '/';
out.role = n.role ?? 'Universal';
return out;
}
function wsClientToJson(n: WsClientNetwork): JsonObject {
const out: JsonObject = {};
applyBase(out, n);
out.url = n.url;
out.role = n.role ?? 'Universal';
out.reconnectIntervalMs =
typeof n.reconnectIntervalMs === 'number' && Number.isFinite(n.reconnectIntervalMs)
? Math.max(1000, Math.trunc(n.reconnectIntervalMs))
: 5000;
return out;
}
function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig {
// Legacy top-level scalars are pulled DOWN into each adapter on the first
// load: the on-disk schema has no globals anymore, every adapter is
// self-describing. We compute the legacy fallbacks here so that adapters
// missing `messageFormat`/`reportSelfMessage` inherit them once and the
// file is rewritten in normalized form.
let legacyFormat: MessageFormat | undefined;
let legacyReport: boolean | undefined;
let musicSignUrl = '';
for (const src of sources) {
const mf = parseMessageFormat(src.messageFormat);
if (mf) legacyFormat = mf;
if (typeof src.reportSelfMessage === 'boolean') legacyReport = src.reportSelfMessage;
if (typeof src.musicSignUrl === 'string') musicSignUrl = src.musicSignUrl;
}
const inheritedFormat: MessageFormat = legacyFormat ?? 'array';
const inheritedReport: boolean = legacyReport ?? false;
// Pluck per-type arrays from each source: prefer `networks.<kind>` over
// legacy top-level arrays, but accept both. Later sources override earlier
// ones at the network level (last write wins per `(kind, name)` pair).
const adapterDefaults = { messageFormat: inheritedFormat, reportSelfMessage: inheritedReport };
const httpServers = collectByName<HttpServerNetwork>(sources, 'httpServers', (raw) => parseHttpServer(raw, adapterDefaults));
const httpClients = collectByName<HttpClientNetwork>(sources, 'httpClients', (raw) => parseHttpClient(raw, adapterDefaults), 'httpPostEndpoints');
const wsServers = collectByName<WsServerNetwork>(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults));
const wsClients = collectByName<WsClientNetwork>(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults));
// Seed defaults ONLY for a brand-new install (no source files at all).
// If the operator deliberately emptied every adapter, respect that and
// do NOT silently revive default 0.0.0.0 listeners.
if (
freshInstall &&
httpServers.length === 0 &&
httpClients.length === 0 &&
wsServers.length === 0 &&
wsClients.length === 0
) {
const defaults = makeDefaultOneBotConfig().networks;
httpServers.push(...defaults.httpServers);
wsServers.push(...defaults.wsServers);
}
const networks: OneBotNetworks = { httpServers, httpClients, wsServers, wsClients };
return { networks, musicSignUrl };
}
function collectByName<T extends { name: string }>(
sources: JsonObject[],
kind: keyof OneBotNetworks,
parse: (raw: JsonObject) => T | null,
legacyKey?: string,
): T[] {
const byName = new Map<string, T>();
const order: string[] = [];
let counter = 0;
const ingest = (rawArr: unknown): void => {
if (!Array.isArray(rawArr)) return;
for (const raw of rawArr) {
if (!isObject(raw)) continue;
const parsed = parse(raw);
if (!parsed) continue;
const name = parsed.name && parsed.name.trim() ? parsed.name.trim() : pickAutoName(kind, byName, ++counter);
parsed.name = name;
if (!byName.has(name)) order.push(name);
byName.set(name, parsed);
}
};
for (const src of sources) {
const nested = isObject(src.networks) ? (src.networks as JsonObject)[kind] : undefined;
ingest(nested);
if (legacyKey) ingest(src[legacyKey]);
ingest(src[kind]);
}
return order.map((n) => byName.get(n)!);
}
function pickAutoName(kind: keyof OneBotNetworks, used: Map<string, unknown>, counter: number): string {
const prefix =
kind === 'httpServers' ? 'http' :
kind === 'httpClients' ? 'httppost' :
kind === 'wsServers' ? 'ws' :
'wsclient';
let candidate = `${prefix}-${counter}`;
while (used.has(candidate)) {
counter += 1;
candidate = `${prefix}-${counter}`;
}
return candidate;
}
interface AdapterDefaults {
messageFormat: MessageFormat;
reportSelfMessage: boolean;
}
function parseBase(value: JsonObject, defaults: AdapterDefaults) {
return {
name: asString(value.name),
enabled: typeof value.enabled === 'boolean' ? value.enabled : undefined,
accessToken: asString(value.accessToken) || undefined,
messageFormat: parseMessageFormat(value.messageFormat) ?? defaults.messageFormat,
reportSelfMessage:
typeof value.reportSelfMessage === 'boolean' ? value.reportSelfMessage : defaults.reportSelfMessage,
};
}
function parseHttpServer(value: JsonObject, defaults: AdapterDefaults): HttpServerNetwork | null {
const port = asNumber(value.port, 0);
if (port <= 0) return null;
return clean({
...parseBase(value, defaults),
host: asString(value.host, '0.0.0.0'),
port,
path: asString(value.path, '/'),
});
}
function parseHttpClient(value: JsonObject, defaults: AdapterDefaults): HttpClientNetwork | null {
const url = asString(value.url);
if (!url) return null;
const timeout = asNumber(value.timeoutMs, 0);
return clean({
...parseBase(value, defaults),
url,
timeoutMs: timeout > 0 ? timeout : undefined,
});
}
function parseWsServer(value: JsonObject, defaults: AdapterDefaults): WsServerNetwork | null {
const port = asNumber(value.port, 0);
if (port <= 0) return null;
return clean({
...parseBase(value, defaults),
host: asString(value.host, '0.0.0.0'),
port,
path: asString(value.path, '/'),
role: asRole(value.role, 'Universal'),
});
}
function parseWsClient(value: JsonObject, defaults: AdapterDefaults): WsClientNetwork | null {
const url = asString(value.url);
if (!url) return null;
const reconnectIntervalMs = asNumber(value.reconnectIntervalMs, 5000);
return clean({
...parseBase(value, defaults),
url,
role: asRole(value.role, 'Universal'),
reconnectIntervalMs: Math.max(1000, reconnectIntervalMs),
});
}
function hasLegacyTopLevel(raw: JsonObject): boolean {
return (
Array.isArray(raw.httpServers) ||
Array.isArray(raw.httpPostEndpoints) ||
Array.isArray(raw.wsServers) ||
Array.isArray(raw.wsClients) ||
typeof raw.messageFormat === 'string' ||
typeof raw.reportSelfMessage === 'boolean'
);
}
function parseMessageFormat(value: unknown): MessageFormat | undefined {
if (value === 'array' || value === 'string') return value;
return undefined;
}
function clean<T extends Record<string, unknown>>(obj: T): T {
for (const key of Object.keys(obj) as (keyof T)[]) {
if (obj[key] === undefined) delete obj[key];
}
return obj;
}
function asRole(value: unknown, fallback: WsRole): WsRole {
// Accept both uppercase (canonical) and lowercase (legacy on-disk) forms.
// Lowercase values are auto-migrated to uppercase on the next save.
const text = asString(value, fallback).toLowerCase();
if (text === 'api') return 'Api';
if (text === 'event') return 'Event';
if (text === 'universal') return 'Universal';
return fallback;
}
function asString(value: unknown, fallback = ''): string {
if (typeof value === 'string') return value;
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
return fallback;
}
function asNumber(value: unknown, fallback = 0): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.max(0, Math.trunc(value));
if (typeof value === 'string' && value.trim()) {
const n = Number(value);
if (Number.isFinite(n)) return Math.max(0, Math.trunc(n));
}
return fallback;
}
function tryLoadJson(filePath: string): JsonObject | null {
if (!fs.existsSync(filePath)) return null;
try {
const raw = fs.readFileSync(filePath, 'utf8');
const parsed = JSON.parse(raw) as unknown;
return isObject(parsed) ? parsed : null;
} catch (err) {
log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err));
return null;
}
}
function saveJson(filePath: string, json: JsonObject): void {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8');
}
function isObject(value: unknown): value is JsonObject {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
+8
View File
@@ -0,0 +1,8 @@
// Globals injected by Vite at build time (see `packages/core/vite.config.ts`).
// `__APP_VERSION__` reads from the monorepo root `package.json::version`;
// `__BUILD_WEBUI__` flips on when `BUILD_WEBUI=true` is set so the runner
// stitches the SPA assets in. Both are typed as `unknown` outside vite
// (e.g. when running tests via vitest where the plugin isn't applied) —
// callers guard with `typeof __APP_VERSION__ !== 'undefined'`.
declare const __BUILD_WEBUI__: boolean;
declare const __APP_VERSION__: string;
@@ -0,0 +1,126 @@
import type { MessageElement, QQEventVariant } from '@snowluma/bridge/events';
import type { JsonObject } from '../types';
import {
convertFriendMessage,
convertGroupMessage,
convertTempMessage,
} from './to-message';
import {
convertFriendAdd,
convertFriendPoke,
convertFriendRecall,
convertGroupAdmin,
convertGroupEssence,
convertGroupFileUpload,
convertGroupMemberJoin,
convertGroupMemberLeave,
convertGroupMsgEmojiLike,
convertGroupMute,
convertGroupPoke,
convertGroupRecall,
} from './to-notice';
import {
convertFriendRequest,
convertGroupInvite,
} from './to-request';
import { elementsToJson } from './to-segment';
// ─────────────── resolver callback types ───────────────
export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string;
export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise<string>;
export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number;
/**
* Side-channel callback invoked every time an image / record / video
* segment is produced, so callers can keep a lookup index (e.g. for
* `get_image` / `get_record`) without re-scanning the message store.
*/
export type MediaSegmentSink = (
mediaType: 'image' | 'record' | 'video',
element: MessageElement,
data: JsonObject,
isGroup: boolean,
sessionId: number,
) => void;
// ─────────────── context ───────────────
/**
* Everything `convertEvent` needs that isn't on the bridge event itself.
* Built once per OneBotInstance and passed through unchanged. Resolvers
* are nullable because tests routinely omit them; when missing, the
* converter falls back to the bridge event's own fields (e.g. raw
* `element.url`, raw `event.msgSeq`).
*/
export interface ConverterContext {
/** Self uin parsed once into a Number for inclusion in `self_id`. */
selfId: number;
imageUrlResolver: ImageUrlResolver | null;
mediaUrlResolver: MediaUrlResolver | null;
messageIdResolver: MessageIdResolver | null;
mediaSegmentSink: MediaSegmentSink | null;
}
// ─────────────── dispatcher ───────────────
/**
* Convert a bridge `QQEventVariant` to the OneBot wire-shape JSON.
* Returns null for kinds we don't surface (so callers can skip them
* without an explicit allow-list).
*/
export async function convertEvent(
ctx: ConverterContext,
event: QQEventVariant,
): Promise<JsonObject | null> {
switch (event.kind) {
// Messages.
case 'friend_message': return convertFriendMessage(ctx, event);
case 'group_message': return convertGroupMessage(ctx, event);
case 'temp_message': return convertTempMessage(ctx, event);
// Notices.
case 'group_member_join': return convertGroupMemberJoin(ctx, event);
case 'group_member_leave': return convertGroupMemberLeave(ctx, event);
case 'group_mute': return convertGroupMute(ctx, event);
case 'group_admin': return convertGroupAdmin(ctx, event);
case 'friend_recall': return convertFriendRecall(ctx, event);
case 'group_recall': return convertGroupRecall(ctx, event);
case 'friend_poke': return convertFriendPoke(ctx, event);
case 'group_poke': return convertGroupPoke(ctx, event);
case 'group_essence': return convertGroupEssence(ctx, event);
case 'group_file_upload': return convertGroupFileUpload(ctx, event);
case 'friend_add': return convertFriendAdd(ctx, event);
case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event);
// Requests.
case 'friend_request': return convertFriendRequest(ctx, event);
case 'group_invite': return convertGroupInvite(ctx, event);
default:
return null;
}
}
// ─────────────── side-channel re-export ───────────────
/**
* Element-array -> OneBot segment-array helper. Used by
* `modules/message-actions.ts` for forward-message rebuilding (where
* we already know the elements but want the OneBot segment shape).
* The signature stays backwards-compatible: each resolver is an
* optional positional argument.
*/
export async function elementsToOneBotSegments(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
imageUrlResolver?: ImageUrlResolver | null,
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
) {
return elementsToJson(
elements, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
);
}
@@ -0,0 +1,107 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { elementsToJson } from './to-segment';
import { applyMessageIdResolver, segmentsToRawMessage } from './utils';
type FriendMessage = Extract<QQEventVariant, { kind: 'friend_message' }>;
type GroupMessage = Extract<QQEventVariant, { kind: 'group_message' }>;
type TempMessage = Extract<QQEventVariant, { kind: 'temp_message' }>;
export async function convertFriendMessage(ctx: ConverterContext, event: FriendMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, false, event.senderUin,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'private',
sub_type: 'friend',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
export async function convertGroupMessage(ctx: ConverterContext, event: GroupMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, true, event.groupId,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'group',
sub_type: 'normal',
message_id: messageId,
message_seq: event.msgSeq,
group_id: event.groupId,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
card: event.senderCard,
role: event.senderRole || 'member',
sex: 'unknown',
age: 0,
},
anonymous: null,
};
}
export async function convertTempMessage(ctx: ConverterContext, event: TempMessage): Promise<JsonObject> {
const isSelf = event.senderUin === ctx.selfId;
const postType = isSelf ? 'message_sent' : 'message';
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.senderUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
const segments = await elementsToJson(
event.elements, false, event.senderUin,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: postType,
message_type: 'private',
sub_type: 'group',
message_id: messageId,
message_seq: event.msgSeq,
user_id: event.senderUin,
message: segments,
raw_message: segmentsToRawMessage(segments),
font: 0,
sender: {
user_id: event.senderUin,
nickname: event.senderNick,
sex: 'unknown',
age: 0,
},
};
}
@@ -0,0 +1,213 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
import { applyMessageIdResolver, isSameActor } from './utils';
type GroupMemberJoin = Extract<QQEventVariant, { kind: 'group_member_join' }>;
type GroupMemberLeave = Extract<QQEventVariant, { kind: 'group_member_leave' }>;
type GroupMute = Extract<QQEventVariant, { kind: 'group_mute' }>;
type GroupAdmin = Extract<QQEventVariant, { kind: 'group_admin' }>;
type FriendRecall = Extract<QQEventVariant, { kind: 'friend_recall' }>;
type GroupRecall = Extract<QQEventVariant, { kind: 'group_recall' }>;
type FriendPoke = Extract<QQEventVariant, { kind: 'friend_poke' }>;
type GroupPoke = Extract<QQEventVariant, { kind: 'group_poke' }>;
type GroupEssence = Extract<QQEventVariant, { kind: 'group_essence' }>;
type GroupFileUpload = Extract<QQEventVariant, { kind: 'group_file_upload' }>;
type FriendAdd = Extract<QQEventVariant, { kind: 'friend_add' }>;
type GroupMsgEmojiLike = Extract<QQEventVariant, { kind: 'group_msg_emoji_like' }>;
export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_increase',
sub_type: isSameActor(event.operatorUin, event.operatorUid, event.userUin, event.userUid) ? 'approve' : 'invite',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
}
export function convertGroupMemberLeave(ctx: ConverterContext, event: GroupMemberLeave): JsonObject {
let subType: string;
if (event.isKick) {
subType = event.userUin === ctx.selfId ? 'kick_me' : 'kick';
} else {
subType = 'leave';
}
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_decrease',
sub_type: subType,
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
};
}
export function convertGroupMute(ctx: ConverterContext, event: GroupMute): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_ban',
sub_type: event.duration > 0 ? 'ban' : 'lift_ban',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.userUin,
duration: event.duration,
};
}
export function convertGroupAdmin(ctx: ConverterContext, event: GroupAdmin): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_admin',
sub_type: event.set ? 'set' : 'unset',
group_id: event.groupId,
user_id: event.userUin,
};
}
export function convertFriendRecall(ctx: ConverterContext, event: FriendRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, false, event.userUin, event.msgSeq, PRIVATE_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'friend_recall',
user_id: event.userUin,
message_id: messageId,
};
}
export function convertGroupRecall(ctx: ConverterContext, event: GroupRecall): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_recall',
group_id: event.groupId,
operator_id: event.operatorUin,
user_id: event.authorUin,
message_id: messageId,
};
}
export function convertFriendPoke(ctx: ConverterContext, event: FriendPoke): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
}
export function convertGroupPoke(ctx: ConverterContext, event: GroupPoke): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'notify',
sub_type: 'poke',
group_id: event.groupId,
user_id: event.userUin,
target_id: event.targetUin,
action: event.action,
suffix: event.suffix,
action_img_url: event.actionImgUrl,
};
}
export function convertGroupEssence(ctx: ConverterContext, event: GroupEssence): JsonObject {
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'essence',
sub_type: event.set ? 'add' : 'delete',
group_id: event.groupId,
user_id: event.senderUin,
sender_id: event.senderUin,
operator_id: event.operatorUin,
message_id: messageId,
message_seq: event.msgSeq,
random: event.random,
};
}
export function convertGroupFileUpload(ctx: ConverterContext, event: GroupFileUpload): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_upload',
group_id: event.groupId,
user_id: event.userUin,
file: {
id: event.fileId,
name: event.fileName,
size: event.fileSize,
busid: event.busId,
},
};
}
export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'friend_add',
user_id: event.userUin,
};
}
/**
* Group message emoji reaction notice. Matches the gocqhttp / NapCat
* extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot
* v11 standard has no slot for reactions and that's what every
* downstream framework keys off.
*/
export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject {
// Reconstruct the OneBot message_id we originally minted for the
// reacted-to message. hashMessageIdInt32 is deterministic so the ID
// matches whatever the client received at receive-time, even when
// the message has fallen out of our store.
const messageId = applyMessageIdResolver(
ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT,
);
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'notice',
notice_type: 'group_msg_emoji_like',
sub_type: event.isAdd ? 'add' : 'remove',
group_id: event.groupId,
user_id: event.operatorUin,
operator_id: event.operatorUin,
message_id: messageId,
message_seq: event.msgSeq,
likes: [{ emoji_id: event.emojiId, count: event.count }],
};
}
@@ -0,0 +1,32 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import type { JsonObject } from '../types';
import type { ConverterContext } from './index';
type FriendRequest = Extract<QQEventVariant, { kind: 'friend_request' }>;
type GroupInvite = Extract<QQEventVariant, { kind: 'group_invite' }>;
export function convertFriendRequest(ctx: ConverterContext, event: FriendRequest): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'request',
request_type: 'friend',
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
}
export function convertGroupInvite(ctx: ConverterContext, event: GroupInvite): JsonObject {
return {
time: event.time,
self_id: ctx.selfId,
post_type: 'request',
request_type: 'group',
sub_type: event.subType || 'invite',
group_id: event.groupId,
user_id: event.fromUin,
comment: event.message,
flag: event.flag,
};
}
@@ -0,0 +1,149 @@
import type { MessageElement } from '@snowluma/bridge/events';
import type { JsonArray, JsonObject } from '../types';
import type {
ImageUrlResolver,
MediaSegmentSink,
MediaUrlResolver,
MessageIdResolver,
} from './index';
import { resolveReplyId } from './utils';
export async function elementsToJson(
elements: MessageElement[],
isGroup: boolean,
sessionId: number,
imageUrlResolver?: ImageUrlResolver | null,
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
): Promise<JsonArray> {
const result: JsonArray = [];
for (const element of elements) {
result.push(await elementToSegment(
element, isGroup, sessionId,
imageUrlResolver, mediaUrlResolver, messageIdResolver, mediaSegmentSink,
));
}
return result;
}
async function elementToSegment(
element: MessageElement,
isGroup: boolean,
sessionId: number,
imageUrlResolver?: ImageUrlResolver | null,
mediaUrlResolver?: MediaUrlResolver | null,
messageIdResolver?: MessageIdResolver | null,
mediaSegmentSink?: MediaSegmentSink | null,
): Promise<JsonObject> {
if (element.type === 'text') {
return { type: 'text', data: { text: element.text ?? '' } };
}
if (element.type === 'face') {
return { type: 'face', data: { id: String(element.faceId ?? 0) } };
}
if (element.type === 'image') {
const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? '');
const data: JsonObject = {
url,
file: element.fileId ?? '',
sub_type: element.subType ?? 0,
summary: element.summary ?? '',
};
if (mediaSegmentSink) mediaSegmentSink('image', element, data, isGroup, sessionId);
return { type: 'image', data };
}
if (element.type === 'at') {
const qq = (element.uid === 'all' || element.targetUin === 0)
? 'all'
: String(element.targetUin ?? 0);
return { type: 'at', data: { qq } };
}
if (element.type === 'reply') {
const id = resolveReplyId(isGroup, sessionId, element.replySeq ?? 0, messageIdResolver);
return { type: 'reply', data: { id: String(id) } };
}
if (element.type === 'record') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSegmentSink) mediaSegmentSink('record', element, data, isGroup, sessionId);
return { type: 'record', data };
}
if (element.type === 'video') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
const data: JsonObject = {
file: element.fileName ?? element.fileId ?? '',
url,
};
if (mediaSegmentSink) mediaSegmentSink('video', element, data, isGroup, sessionId);
return { type: 'video', data };
}
if (element.type === 'json') {
return { type: 'json', data: { data: element.text ?? '' } };
}
if (element.type === 'xml') {
return {
type: 'xml',
data: {
data: element.text ?? '',
resid: element.subType ?? 35,
},
};
}
if (element.type === 'file') {
const url = mediaUrlResolver ? await mediaUrlResolver(element, isGroup, sessionId) : (element.url ?? '');
return {
type: 'file',
data: {
name: element.fileName ?? '',
size: element.fileSize ?? 0,
id: element.fileId ?? '',
url,
file_hash: element.fileHash ?? '',
},
};
}
if (element.type === 'mface') {
return {
type: 'mface',
data: {
name: element.text ?? '',
tab_id: element.faceId ?? 0,
sub_type: element.subType ?? 0,
},
};
}
if (element.type === 'poke') {
return {
type: 'poke',
data: {
type: element.subType ?? 0,
},
};
}
if (element.type === 'forward') {
return {
type: 'forward',
data: { id: element.resId ?? '' },
};
}
// Unknown / unmapped element type — emit an empty segment to keep the
// outgoing message length consistent with the bridge event.
return { type: element.type, data: {} };
}
@@ -0,0 +1,105 @@
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../message-id';
import type { JsonArray, JsonObject } from '../types';
import type { MessageIdResolver } from './index';
export function parseSelfId(instanceUin: string): number {
const parsed = Number.parseInt(instanceUin, 10);
return Number.isNaN(parsed) ? 0 : parsed;
}
/**
* Two QQEvent actors are "the same" when their uins match, or their
* uids match when uins aren't available. Used by the group_member_join
* sub-type calculation (self-approve vs. invite).
*/
export function isSameActor(
leftUin: number,
leftUid: string | undefined,
rightUin: number,
rightUid: string | undefined,
): boolean {
if (leftUin > 0 && rightUin > 0) return leftUin === rightUin;
return Boolean(leftUid) && leftUid === rightUid;
}
/**
* Run the optional MessageId resolver, falling back to the raw
* sequence when no resolver is wired or it returns 0.
*/
export function applyMessageIdResolver(
resolver: MessageIdResolver | null,
isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
): number {
if (resolver) {
const resolved = resolver(isGroup, sessionId, sequence, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
const seq = Math.trunc(sequence);
return seq === 0 ? 0 : seq;
}
export function resolveReplyId(
isGroup: boolean,
sessionId: number,
sequence: number,
resolver?: MessageIdResolver | null,
): number {
const seq = Math.trunc(sequence);
if (seq === 0) return 0;
if (resolver) {
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
const resolved = resolver(isGroup, sessionId, seq, eventName);
if (Number.isInteger(resolved) && resolved !== 0) return resolved;
}
return seq;
}
// ─────────────── raw_message (CQ string) generation ───────────────
function cqEscape(text: string): string {
return text.replace(/&/g, '&amp;').replace(/\[/g, '&#91;').replace(/\]/g, '&#93;').replace(/,/g, '&#44;');
}
export function segmentsToRawMessage(segments: JsonArray): string {
return segments.map(seg => segmentToCQ(seg as JsonObject)).join('');
}
function segmentToCQ(seg: JsonObject): string {
const type = String(seg.type ?? '');
const data = (seg.data ?? {}) as Record<string, unknown>;
switch (type) {
case 'text':
return cqEscape(String(data.text ?? ''));
case 'face':
return `[CQ:face,id=${data.id ?? 0}]`;
case 'image':
return `[CQ:image,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'at':
return `[CQ:at,qq=${data.qq ?? ''}]`;
case 'reply':
return `[CQ:reply,id=${data.id ?? 0}]`;
case 'record':
return `[CQ:record,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'video':
return `[CQ:video,file=${cqEscape(String(data.file ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
case 'json':
return `[CQ:json,data=${cqEscape(String(data.data ?? ''))}]`;
case 'xml':
return `[CQ:xml,data=${cqEscape(String(data.data ?? ''))}]`;
case 'forward':
return `[CQ:forward,id=${cqEscape(String(data.id ?? ''))}]`;
case 'mface':
return `[CQ:mface,name=${cqEscape(String(data.name ?? ''))}]`;
case 'poke':
return `[CQ:poke,type=${data.type ?? 0}]`;
case 'file':
return `[CQ:file,name=${cqEscape(String(data.name ?? ''))},size=${data.size ?? 0},id=${cqEscape(String(data.id ?? ''))},url=${cqEscape(String(data.url ?? ''))}]`;
default:
return `[CQ:${type}]`;
}
}
+99
View File
@@ -0,0 +1,99 @@
import type { JsonObject, JsonValue, MessageFormat } from './types';
export interface EventReportOptions {
/** Effective `messageFormat` for this adapter. */
messageFormat: MessageFormat;
/** Whether self-sent messages should be forwarded to this adapter. */
reportSelfMessage: boolean;
}
/**
* Extract the dispatch options from an adapter. Each adapter is fully
* self-describing — there is no global fallback. Defaults are applied here
* only as a safety net for partially-deserialized legacy configs.
*/
export function resolveReportOptions(
network: { messageFormat?: MessageFormat; reportSelfMessage?: boolean },
): EventReportOptions {
return {
messageFormat: network.messageFormat ?? 'array',
reportSelfMessage: network.reportSelfMessage ?? false,
};
}
/**
* Pre-built payload covering every adapter variant of a single canonical event.
*
* The bridge produces one OneBot-shaped event per upstream packet. Because
* adapters only differ in (a) whether they receive `message_sent` self-events
* and (b) whether the `message` field is the segment array or its CQ-string
* form, we serialize the event at most twice up-front and let every adapter
* pick the slot it needs in O(1).
*/
export interface DispatchPayload {
/** True when the canonical event is a self-sent message (`post_type='message_sent'`). */
isSelfMessage: boolean;
/** JSON for adapters using `messageFormat: 'array'` (the canonical event). */
arrayJson: string;
/**
* JSON for adapters using `messageFormat: 'string'`. For non-message events
* this points at the same string as `arrayJson` (no transformation needed).
*/
stringJson: string;
}
/**
* Build the dispatch payload for one canonical OneBot event. Performs at most
* two `JSON.stringify` calls (one per format variant) regardless of how many
* adapters the payload will fan out to.
*/
export function buildDispatchPayload(event: JsonObject): DispatchPayload {
const isSelfMessage = event.post_type === 'message_sent';
const arrayJson = JSON.stringify(event);
let stringJson = arrayJson;
const hasMessage = event.post_type === 'message' || event.post_type === 'message_sent';
if (hasMessage && Array.isArray(event.message)) {
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
stringJson = JSON.stringify({ ...event, message: raw as JsonValue });
}
return { isSelfMessage, arrayJson, stringJson };
}
/**
* Pick the pre-serialized payload variant an adapter should send, or `null`
* when the adapter chose not to receive this event. Hot-path helper: one
* branch + one map lookup per connection, no allocation.
*/
export function pickDispatchJson(
payload: DispatchPayload,
options: EventReportOptions,
): string | null {
if (payload.isSelfMessage && !options.reportSelfMessage) return null;
return options.messageFormat === 'string' ? payload.stringJson : payload.arrayJson;
}
/**
* One-shot variant of {@link buildDispatchPayload} + {@link pickDispatchJson}
* for ad-hoc events (e.g. WS connection bootstrap meta events) that aren't
* worth pre-building a full payload for.
*
* Returns `null` when the adapter shouldn't see this event. Otherwise returns
* the original event untouched, or a shallow clone with `message` rewritten.
*/
export function shapeEventForAdapter(
event: JsonObject,
options: EventReportOptions,
): JsonObject | null {
if (event.post_type === 'message_sent' && !options.reportSelfMessage) return null;
if (options.messageFormat === 'string'
&& (event.post_type === 'message' || event.post_type === 'message_sent')
&& Array.isArray(event.message)
) {
const raw = typeof event.raw_message === 'string' ? event.raw_message : '';
return { ...event, message: raw as JsonValue };
}
return event;
}
+107
View File
@@ -0,0 +1,107 @@
import type { QQEventVariant } from '@snowluma/bridge/events';
import { convertEvent } from './event-converter';
import type { OneBotInstanceContext } from './instance-context';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
/**
* Subscribe every `OneBotInstanceContext`-aware handler onto the bridge
* event bus. Returns a disposer that removes every subscription registered
* here in one shot — useful for tests and for tearing down a session.
*/
export function registerEventPipeline(ctx: OneBotInstanceContext): () => void {
const disposers: Array<() => void> = [];
// Every kind that maps onto an OB11 message event also seeds the
// message-meta cache; we do that synchronously before async conversion so
// reply / quote lookups for that message id work even if the converter
// takes a beat to finish (e.g. while resolving image URLs).
disposers.push(
ctx.bridge.events.on('group_message', async (event) => {
cacheGroupMessageMeta(ctx, event);
await convertAndDispatch(ctx, event);
}),
);
disposers.push(
ctx.bridge.events.on('friend_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, event.msgId);
await convertAndDispatch(ctx, event);
}),
);
disposers.push(
ctx.bridge.events.on('temp_message', async (event) => {
cachePrivateMessageMeta(ctx, event.senderUin, event.msgSeq, event.time, 0);
await convertAndDispatch(ctx, event);
}),
);
// Notice / request / non-message events: no meta caching needed, just
// convert and dispatch.
for (const kind of NOTICE_KINDS) {
disposers.push(
ctx.bridge.events.on(kind, async (event) => {
await convertAndDispatch(ctx, event);
}),
);
}
return () => {
for (const dispose of disposers) {
try { dispose(); } catch { /* ignore */ }
}
};
}
const NOTICE_KINDS = [
'group_member_join',
'group_member_leave',
'group_mute',
'group_admin',
'friend_recall',
'group_recall',
'friend_request',
'group_invite',
'friend_poke',
'group_poke',
'group_essence',
'group_file_upload',
'friend_add',
'group_msg_emoji_like',
] as const satisfies readonly QQEventVariant['kind'][];
async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise<void> {
const converted = await convertEvent(ctx.converterCtx, event);
if (!converted) return;
ctx.dispatchEvent(converted);
}
function cacheGroupMessageMeta(ctx: OneBotInstanceContext, event: Extract<QQEventVariant, { kind: 'group_message' }>): void {
const messageId = hashMessageIdInt32(event.msgSeq, event.groupId, GROUP_MESSAGE_EVENT);
ctx.cacheMessageMeta(messageId, {
isGroup: true,
targetId: event.groupId,
sequence: event.msgSeq,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: event.msgId,
timestamp: event.time,
});
}
function cachePrivateMessageMeta(
ctx: OneBotInstanceContext,
senderUin: number,
msgSeq: number,
timestamp: number,
random: number,
): void {
const messageId = hashMessageIdInt32(msgSeq, senderUin, PRIVATE_MESSAGE_EVENT);
ctx.cacheMessageMeta(messageId, {
isGroup: false,
targetId: senderUin,
sequence: msgSeq,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random,
timestamp,
});
}
+218
View File
@@ -0,0 +1,218 @@
import type { WebHonorType } from '@snowluma/bridge/web/group-honor';
import type { Bridge } from '@snowluma/core/bridge';
import type { ApiActionContext } from './api-handler';
import type { ConverterContext } from './event-converter';
import type { MediaStore } from './media-store';
import type { MessageStore } from './message-store';
import type { JsonObject, MessageMeta, OneBotConfig } from './types';
import {
getDownloadRKeys,
getFriendList,
getGroupFiles,
getGroupInfo,
getGroupList,
getGroupMemberInfo,
getGroupMemberList,
getGroupSystemMessages,
getLoginInfo,
getStrangerInfo,
} from './modules/contact-actions';
import {
deleteMessage,
forwardSingleMessage,
getForwardMessage,
getFriendMsgHistory,
getGroupMsgHistory,
sendGroupForwardMessage,
sendGroupMessage,
sendPrivateForwardMessage,
sendPrivateMessage,
setEssenceMessage,
uploadForwardMessage,
} from './modules/message-actions';
import {
getImageInfo as getCachedImageInfo,
getRecordInfo as getCachedRecordInfo,
} from './modules/media-actions';
import { handleGroupAddRequest } from './modules/request-actions';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
/**
* Single shared context bag that flows through every OneBot instance-internal
* subsystem: API builder and the per-kind event pipeline.
*
* Only fields that are actually read through this bag live here. The API
* handler and network manager are owned by `OneBotInstance` directly because
* nothing reads them via ctx, and including them here would force a
* chicken-and-egg late-bound field dance during construction.
*
* `dispatchEvent` is the indirection used by the event pipeline to hand a
* converted OneBot event back to the instance for caching + adapter fan-out;
* it lets the pipeline stay decoupled from the network manager.
*/
export interface OneBotInstanceContext {
/** Self UIN as string (matches what's on disk and on the wire). */
uin: string;
/** Self UIN parsed once, used in event payloads. */
selfId: number;
bridge: BridgeInterface;
messageStore: MessageStore;
mediaStore: MediaStore;
converterCtx: ConverterContext;
config: OneBotConfig;
musicSignUrl?: string;
/** Persist meta about a message id; safe to call any number of times. */
cacheMessageMeta(messageId: number, meta: MessageMeta): void;
/** Hand a fully-converted OneBot event to the network manager + caches. */
dispatchEvent(event: JsonObject): void;
}
/**
* Build the ApiActionContext that ApiHandler hands to each action file.
*
* Two flavours of entries live in here:
* - Adapters — rename a Bridge method (setGroupKick → kickGroupMember),
* compose with messageStore / mediaStore / ref, bake in a constant
* (setEssenceMsg passes true; deleteEssenceMsg passes false), bridge a
* bridge call into OneBot vocabulary (sendFriendPoke flattens the
* isGroup boolean), or extract a field from the bridge return shape.
* - Pass-throughs used to live here too but added zero value; OneBot
* actions now call `ctx.bridge.<name>` directly when no translation is
* happening (set_group_admin, set_online_status, set_avatar, …).
*/
export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext {
const { bridge, messageStore, mediaStore } = ref;
return {
bridge,
getLoginInfo: () => getLoginInfo(ref),
isOnline: () => true,
getMessage: (messageId) => messageStore.findEvent(messageId),
getMessageMeta: (messageId) => messageStore.findMeta(messageId),
canSendImage: () => true,
canSendRecord: () => true,
// OneBot11 message actions.
sendPrivateMessage: (userId, message, autoEscape) => sendPrivateMessage(ref, userId, message, autoEscape),
sendGroupMessage: (groupId, message, autoEscape) => sendGroupMessage(ref, groupId, message, autoEscape),
deleteMessage: (_messageId, meta) => deleteMessage(bridge, meta),
// OneBot11 info actions (wrap modules that also touch identity).
getFriendList: () => getFriendList(bridge),
getGroupList: (noCache) => getGroupList(bridge, noCache),
getGroupInfo: (groupId, noCache) => getGroupInfo(bridge, groupId, noCache),
getGroupMemberList: (groupId, noCache) => getGroupMemberList(bridge, groupId, noCache),
getGroupMemberInfo: (groupId, userId, noCache) => getGroupMemberInfo(bridge, groupId, userId, noCache),
getStrangerInfo: (userId) => getStrangerInfo(bridge, userId),
// Group admin — names translate to OneBot vocabulary.
setGroupKick: (groupId, userId, reject) => bridge.apis.groupAdmin.kickMember(groupId, userId, reject),
setGroupKickMembers: (groupId, userIds, reject) => bridge.apis.groupAdmin.kickMembers(groupId, userIds, reject),
setGroupBan: (groupId, userId, duration) => bridge.apis.groupAdmin.muteMember(groupId, userId, duration),
setGroupWholeBan: (groupId, enable) => bridge.apis.groupAdmin.muteAll(groupId, enable),
setGroupLeave: (groupId) => bridge.apis.groupAdmin.leave(groupId),
// Group file — fileId field extraction + defaults.
uploadGroupFile: async (groupId, file, name, folderId, uploadFile) => {
const result = await bridge.apis.groupFile.upload(groupId, file, name ?? '', folderId ?? '/', uploadFile ?? true);
return result.fileId;
},
uploadPrivateFile: async (userId, file, name, uploadFile) => {
const result = await bridge.apis.groupFile.uploadPrivate(userId, file, name ?? '', uploadFile ?? true);
return result.fileId;
},
getGroupFileUrl: (groupId, fileId, busId) => bridge.apis.groupFile.getUrl(groupId, fileId, busId ?? 102),
getGroupFiles: (groupId, folderId) => getGroupFiles(bridge, groupId, folderId),
createGroupFileFolder: (groupId, name, parentId) => bridge.apis.groupFile.createFolder(groupId, name, parentId ?? '/'),
getPrivateFileUrl: (userId, fileId, fileHash) => bridge.apis.groupFile.getPrivateUrl(userId, fileId, fileHash),
// Requests — name translation.
handleFriendRequest: (flag, approve) => bridge.apis.friend.handleRequest(flag, approve),
handleGroupRequest: (flag, _subType, approve, reason) => handleGroupAddRequest(bridge, flag, approve, reason),
// Pokes — flatten isGroup into the bridge signature.
sendFriendPoke: (userId, targetId) => bridge.apis.interaction.sendPoke(false, userId, targetId),
sendGroupPoke: (groupId, userId) => bridge.apis.interaction.sendPoke(true, groupId, userId),
// Essence — bake the set/unset boolean.
setEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, true),
deleteEssenceMsg: (messageId) => setEssenceMessage(bridge, messageStore, messageId, false),
// Profile-like / get_group_essence — OneBot-specific defaults that the
// action handlers don't supply.
getProfileLike: (userId = undefined, start = 0, limit = 10) => bridge.apis.profile.getLike(userId, start, limit),
getGroupEssence: (groupId, pageStart = 0, pageLimit = 50) => bridge.apis.web.getEssence(groupId, pageStart, pageLimit),
// Message-store-backed history reads.
getGroupMsgHistory: (groupId, messageId, count) => getGroupMsgHistory(messageStore, groupId, messageId, count),
getFriendMsgHistory: (userId, messageId, count) => getFriendMsgHistory(messageStore, userId, messageId, count),
// Module wrappers / multi-dep compositions.
handleGetGroupSystemMsg: () => getGroupSystemMessages(bridge),
getDownloadRKeys: () => getDownloadRKeys(bridge),
sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta),
sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta),
sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId),
getForwardMsg: (resId) => getForwardMessage(ref, resId),
forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target),
handleDeleteFriend: (userId, block) => bridge.apis.friend.delete(userId, !!block),
forceFetchClientKey: () => bridge.apis.web.forceFetchClientKey(),
setFriendRemark: (userId, remark) => bridge.apis.friend.setRemark(userId, remark),
setGroupRemark: (groupId, remark) => bridge.apis.groupAdmin.setRemark(groupId, remark),
setGroupAvatar: (groupId, source) => bridge.apis.profile.setGroupAvatar(groupId, source),
getGroupFileCount: (groupId) => bridge.apis.groupFile.getCount(groupId),
// Cross-store: looks up the meta then routes through Bridge.
setMsgEmojiLike: async (messageId, emojiId, set) => {
const meta = messageStore.findMeta(messageId);
if (!meta) throw new Error('message not found');
// QQ itself doesn't expose emoji reactions on private chats, so
// there is no wire path to forward this to; fail loudly instead
// of silently no-op'ing.
if (!meta.isGroup) throw new Error('emoji reactions are not supported on private messages');
await bridge.apis.interaction.setReaction(meta.targetId, meta.sequence, emojiId, set);
},
markGroupMsgAsRead: (groupId, sequence) => bridge.apis.message.markGroupRead(groupId, sequence),
markPrivateMsgAsRead: (userId, sequence) => bridge.apis.message.markPrivateRead(userId, sequence),
setOnlineStatus: (status: number, extStatus?: number, batteryStatus?: number) => bridge.apis.profile.setOnlineStatus(status, extStatus, batteryStatus),
setProfile: (nickname?: string, personalNote?: string) => bridge.apis.profile.setProfile(nickname, personalNote),
// Web-backed actions.
getGroupHonorInfo: (groupId: number, type: WebHonorType | string) => bridge.apis.web.getHonorInfo(groupId, type),
getGroupEssenceAll: (groupId) => bridge.apis.web.getEssenceAll(groupId),
getGroupAlbumList: (groupId) => bridge.apis.groupAlbum.list(groupId),
uploadImageToGroupAlbum: (groupId, albumId, albumName, filePath) => bridge.apis.groupAlbum.upload(groupId, albumId, albumName, filePath),
getGroupAlbumMediaList: (groupId, albumId, attachInfo) => bridge.apis.groupAlbum.getMediaList(groupId, albumId, attachInfo),
commentGroupAlbumMedia: (groupId, albumId, lloc, content) => bridge.apis.groupAlbum.comment(groupId, albumId, lloc, content),
deleteGroupAlbumMedia: (groupId, albumId, lloc) => bridge.apis.groupAlbum.delete(groupId, albumId, lloc),
likeGroupAlbumMedia: (groupId, albumId, batchId, lloc, isLike) => bridge.apis.groupAlbum.like(groupId, albumId, batchId, lloc, isLike),
sendGroupNotice: (groupId, content, options) => bridge.apis.web.sendNotice(groupId, content, options),
getGroupNotice: (groupId) => bridge.apis.web.getNotice(groupId),
deleteGroupNotice: (groupId, fid) => bridge.apis.web.deleteNotice(groupId, fid),
getCookiesStr: (domain) => bridge.apis.web.getCookiesStr(domain),
getCsrfToken: () => bridge.apis.web.getCsrfToken(),
getCredentials: (domain) => bridge.apis.web.getCredentials(domain),
// Extended
fetchCustomFace: (count) => bridge.apis.profile.fetchCustomFace(count),
getEmojiLikes: (groupId, sequence, emojiId, emojiType, count, cookie) => bridge.apis.interaction.getEmojiLikes(groupId, sequence, emojiId, emojiType, count, cookie),
// Media lookup.
getImageInfo: (file) => getCachedImageInfo(mediaStore, file),
getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file),
};
}
// Re-export Bridge type so consumers of OneBotInstanceContext that need it
// (legacy) keep the import surface stable.
export type { Bridge };
// Re-export WebHonorType so legacy spots that imported it via this module
// keep working.
export type { WebHonorType };
+144
View File
@@ -0,0 +1,144 @@
import type { MessageElement } from '@snowluma/bridge/events';
import type { DownloadRKeyInfo } from '@snowluma/core/bridge';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { createLogger } from '@snowluma/common/logger';
const log = createLogger('OneBot');
interface CachedRKey {
value: string;
type: number;
createTime: number;
ttlSeconds: number;
expiresAt: number;
}
const RKEY_REFRESH_SKEW = 60;
const RKEY_REFRESH_COOLDOWN = 30;
const PRIVATE_IMAGE_RKEY_TYPE = 10;
const GROUP_IMAGE_RKEY_TYPE = 20;
const PRIVATE_VIDEO_RKEY_TYPE = 12;
const GROUP_VIDEO_RKEY_TYPE = 22;
const PRIVATE_PTT_RKEY_TYPE = 14;
const GROUP_PTT_RKEY_TYPE = 24;
const FALLBACK_IMAGE_RKEY_TYPE = 2;
export class RKeyCache {
private cache = new Map<number, CachedRKey>();
private lastRefreshAttempt = 0;
warmUp(bridge: BridgeInterface, uin: string): void {
bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => {
this.updateCache(rkeys);
log.info('rkeys loaded: UIN=%s count=%d', uin, rkeys.length);
},
(err) => {
log.warn('failed to load rkeys for UIN %s: %s', uin, err instanceof Error ? err.message : String(err));
},
);
}
resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.imageUrl ?? '';
if (!urlNeedsRKey(url)) return url;
const rkey = this.findRKey(bridge, isGroup);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
/**
* Resolve a URL for video/record/file media elements.
* Appends the correct RKey type based on media kind and group/private context.
*/
resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string {
const url = element.url ?? '';
if (!url || !urlNeedsRKey(url)) return url;
const mediaType = element.type;
let primaryType: number;
if (mediaType === 'video') {
primaryType = isGroup ? GROUP_VIDEO_RKEY_TYPE : PRIVATE_VIDEO_RKEY_TYPE;
} else if (mediaType === 'record') {
primaryType = isGroup ? GROUP_PTT_RKEY_TYPE : PRIVATE_PTT_RKEY_TYPE;
} else {
// For file types, try image rkeys as a fallback (file URLs typically use image rkeys)
primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
}
const rkey = this.findRKeyForType(bridge, primaryType);
if (!rkey) return url;
const cleanRKey = stripRKeyPrefix(rkey);
const separator = url.includes('?') ? '&rkey=' : '?rkey=';
return url + separator + encodeURIComponent(cleanRKey);
}
private updateCache(rkeys: DownloadRKeyInfo[]): void {
const now = Math.floor(Date.now() / 1000);
for (const rk of rkeys) {
if (!rk.rkey || !rk.type) continue;
const baseTime = rk.createTime || now;
const ttl = rk.ttlSeconds || 3600;
this.cache.set(rk.type, {
value: rk.rkey,
type: rk.type,
createTime: rk.createTime,
ttlSeconds: rk.ttlSeconds,
expiresAt: baseTime + ttl,
});
}
}
private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null {
const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE;
return this.findRKeyForType(bridge, primaryType);
}
private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null {
const now = Math.floor(Date.now() / 1000);
const tryFind = (type: number): string | null => {
const cached = this.cache.get(type);
if (!cached || !cached.value) return null;
if (cached.expiresAt !== 0 && now + RKEY_REFRESH_SKEW >= cached.expiresAt) return null;
return cached.value;
};
let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
if (result) return result;
// Refresh check cooldown
if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null;
this.lastRefreshAttempt = now;
// Schedule async refresh
bridge.apis.contacts.fetchDownloadRKeys().then(
(rkeys) => this.updateCache(rkeys),
() => { /* ignore */ },
);
// Try again (won't be ready yet for this call, but future calls will benefit)
result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE);
return result;
}
}
function urlNeedsRKey(url: string): boolean {
if (!url || url.includes('rkey=')) return false;
if (url.includes('gchat.qpic.cn')) return false;
return url.includes('multimedia.nt.qq.com.cn') ||
url.includes('.nt.qq.com.cn') ||
url.includes('/download');
}
function stripRKeyPrefix(rkey: string): string {
for (const prefix of ['&rkey=', '?rkey=']) {
if (rkey.startsWith(prefix)) return rkey.slice(prefix.length);
}
return rkey;
}
+369
View File
@@ -0,0 +1,369 @@
import path from 'path';
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { ApiHandler } from './api-handler';
import type { ConverterContext } from './event-converter';
import { MediaIndexer } from './media-indexer';
import { MediaStore } from './media-store';
import { MediaUrlResolver } from './media-url-resolver';
import { MessageStore } from './message-store';
import { RKeyCache } from './instance-rkey';
import { buildApiContext, type OneBotInstanceContext } from './instance-context';
import { registerEventPipeline } from './event-pipeline';
import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id';
import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types';
import {
OneBotNetworkManager,
WsServerAdapter,
WsClientAdapter,
HttpServerAdapter,
HttpPostAdapter,
type NetworkAdapterContext,
} from './network';
import { createLogger, type Logger } from '@snowluma/common/logger';
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '@snowluma/bridge/format';
const moduleLog = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
private readonly bridge: BridgeInterface;
private readonly apiHandler: ApiHandler;
private readonly converterCtx: ConverterContext;
private readonly messageStore: MessageStore;
private readonly mediaStore: MediaStore;
private readonly networkManager: OneBotNetworkManager;
private readonly rkeyCache: RKeyCache;
private readonly ctx: OneBotInstanceContext;
private disposeEventPipeline: (() => void) | null = null;
private readonly pids = new Set<number>();
private online = true;
private heartbeatTimer: NodeJS.Timeout | null = null;
private static readonly HEARTBEAT_INTERVAL = 30000;
private readonly log: Logger;
get nickname(): string { return this.bridge.identity.nickname; }
constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) {
this.uin = uin;
this.bridge = bridge;
const uinNum = Number.parseInt(uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0
? moduleLog.child({ uin: uinNum })
: moduleLog;
this.rkeyCache = new RKeyCache();
this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db'));
this.messageStore = new MessageStore(path.join('data', this.uin, 'messages.json'));
// The converter context's four callbacks delegate to small, focused
// modules so this constructor doesn't carry the bridge-URL fetch
// branching or the mediaStore field-mapping fanout inline.
const mediaUrlResolver = new MediaUrlResolver(this.bridge, this.rkeyCache);
const mediaIndexer = new MediaIndexer(this.mediaStore);
this.converterCtx = {
selfId: parseInt(this.uin, 10) || 0,
imageUrlResolver: (element, isGroup) =>
this.rkeyCache.resolveImageUrl(this.bridge, element, isGroup),
mediaUrlResolver: (element, isGroup, sessionId) =>
mediaUrlResolver.resolve(element, isGroup, sessionId),
messageIdResolver: (isGroup, sessionId, sequence, eventName) =>
hashMessageIdInt32(sequence, sessionId, eventName || (isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT)),
mediaSegmentSink: (mediaType, element, data, isGroup, sessionId) =>
mediaIndexer.remember(mediaType, element, data, isGroup, sessionId),
};
// Shared instance context. Only carries fields that are actually read
// through it — api handler and network manager stay as direct fields on
// the instance because nothing reads them via ctx.
const ctx: OneBotInstanceContext = {
uin: this.uin,
selfId: parseInt(this.uin, 10) || 0,
bridge: this.bridge,
messageStore: this.messageStore,
mediaStore: this.mediaStore,
converterCtx: this.converterCtx,
config,
musicSignUrl: config.musicSignUrl,
cacheMessageMeta: (messageId, meta) => this.cacheMessageMeta(messageId, meta),
dispatchEvent: (event) => this.dispatchEvent(event),
};
this.ctx = ctx;
this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined);
this.networkManager = new OneBotNetworkManager();
this.installAdaptersFromConfig(config);
void this.networkManager.openAll().catch((err) => {
this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
this.startHeartbeat();
this.rkeyCache.warmUp(this.bridge, this.uin);
// Per-kind subscription on the typed event bus. Each bridge event kind
// gets its own focused handler in `event-pipeline`; the firehose is gone.
this.disposeEventPipeline = registerEventPipeline(ctx);
}
reloadConfig(config: OneBotConfig): void {
void this.applyConfigDiff(config).catch((err) => {
this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
dispose(): void {
this.online = false;
this.stopHeartbeat();
this.disposeEventPipeline?.();
this.disposeEventPipeline = null;
void this.networkManager.closeAll().catch((err) => {
this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
this.messageStore.close();
this.mediaStore.close();
}
addPid(pid: number): void {
this.pids.add(pid);
}
removePid(pid: number): void {
this.pids.delete(pid);
}
hasPid(pid: number): boolean {
return this.pids.has(pid);
}
getPids(): number[] {
return [...this.pids];
}
get empty(): boolean {
return this.pids.size === 0;
}
private dispatchEvent(event: JsonObject): void {
this.cacheMessageEvent(event);
this.logReceivedMessage(event);
// NetworkManager builds the dispatch payload once and fans out to every
// active adapter in parallel via Promise.allSettled — per-adapter errors
// are already isolated, so the outer promise should never reject. The
// .catch is a belt-and-suspenders guard against future refactors.
void this.networkManager.emitEvent(event).catch((err) => {
this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
private buildNetworkContext(): NetworkAdapterContext {
return {
uin: this.uin,
api: this.apiHandler,
buildLifecycleEvent: (subType) => this.makeLifecycleEvent(subType),
buildHeartbeatEvent: () => this.makeHeartbeatEvent(),
};
}
private installAdaptersFromConfig(config: OneBotConfig): void {
const ctx = this.buildNetworkContext();
for (const net of config.networks.httpServers) {
if (net.enabled === false) continue;
this.networkManager.register(new HttpServerAdapter(net.name, net, ctx));
}
for (const net of config.networks.httpClients) {
if (net.enabled === false || !net.url) continue;
this.networkManager.register(new HttpPostAdapter(net.name, net, ctx));
}
for (const net of config.networks.wsServers) {
if (net.enabled === false) continue;
this.networkManager.register(new WsServerAdapter(net.name, net, ctx));
}
for (const net of config.networks.wsClients) {
if (net.enabled === false || !net.url) continue;
this.networkManager.register(new WsClientAdapter(net.name, net, ctx));
}
}
private async applyConfigDiff(next: OneBotConfig): Promise<void> {
const ctx = this.buildNetworkContext();
const desired = new Map<string, NetworkBase>();
const factories = new Map<string, () => void>();
for (const net of next.networks.httpServers) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new HttpServerAdapter(net.name, net, ctx)));
}
for (const net of next.networks.httpClients) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new HttpPostAdapter(net.name, net, ctx)));
}
for (const net of next.networks.wsServers) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new WsServerAdapter(net.name, net, ctx)));
}
for (const net of next.networks.wsClients) {
desired.set(net.name, net);
factories.set(net.name, () => this.networkManager.register(new WsClientAdapter(net.name, net, ctx)));
}
// Close adapters whose entry has been removed entirely.
for (const adapter of this.networkManager.list()) {
if (!desired.has(adapter.name)) {
await this.networkManager.closeOne(adapter.name);
}
}
// Reload existing adapters in place; spin up new ones the manager hasn't
// seen before.
for (const [name, net] of desired) {
const existing = this.networkManager.get(name);
if (existing) {
try {
await existing.reload(net as never);
} catch (err) {
this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err));
}
} else if (net.enabled !== false) {
const factory = factories.get(name);
if (factory) {
factory();
await this.networkManager.get(name)?.open();
}
}
}
}
private logReceivedMessage(event: JsonObject): void {
const isSelf = event.post_type === 'message_sent';
if (event.post_type !== 'message' && !isSelf) return;
const messageId = toInt(event.message_id);
const isGroup = event.message_type === 'group';
const idStr = `ID:${messageId}`;
const selfTag = isSelf ? '[自身] ' : '';
const identity = this.bridge.identity;
// Walk the segment array once: render via the shared formatter for
// non-reply segments, and resolve `reply` segments through the
// message store so the chain reference becomes legible
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
const renderedParts: string[] = [];
const message = event.message;
if (Array.isArray(message)) {
for (const seg of message) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const type = String((seg as JsonObject).type ?? '');
const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data))
? (seg as JsonObject).data as Record<string, unknown>
: {};
if (type === 'reply') {
const replyId = toInt(data.id);
renderedParts.push(formatReply(this.messageStore, identity, replyId));
} else {
renderedParts.push(formatMessageSegments([seg as JsonValue]));
}
}
} else if (typeof message === 'string') {
renderedParts.push(formatMessageSegments(message));
}
const content = renderedParts.join(' ').trim() || '[空消息]';
if (isGroup) {
const groupId = toInt(event.group_id);
const userId = toInt(event.user_id);
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
? event.sender as JsonObject
: {};
const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || '';
const userPart = nicknameFromEvent
? `[${nicknameFromEvent}(${userId})]`
: formatUser(identity, groupId, userId);
this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`);
} else {
const userId = toInt(event.user_id);
const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender))
? event.sender as JsonObject
: {};
const nicknameFromEvent = (sender.nickname as string) || '';
const userPart = nicknameFromEvent
? `[${nicknameFromEvent}(${userId})]`
: formatUser(identity, undefined, userId);
this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`);
}
}
private cacheMessageEvent(event: JsonObject): void {
if (event.post_type !== 'message' && event.post_type !== 'message_sent') return;
const messageId = toInt(event.message_id);
if (messageId === 0) return;
const isGroup = event.message_type === 'group';
const sessionId = isGroup ? toInt(event.group_id) : toInt(event.user_id);
const sequence = toInt(event.message_seq);
const eventName = isGroup ? GROUP_MESSAGE_EVENT : PRIVATE_MESSAGE_EVENT;
if (sessionId === 0) return;
this.messageStore.storeEvent(messageId, isGroup, sessionId, sequence, eventName, event);
}
private cacheMessageMeta(messageId: number, meta: MessageMeta): void {
if (!Number.isInteger(messageId) || messageId === 0) return;
this.messageStore.storeMeta(messageId, meta);
}
private makeLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject {
const selfId = parseInt(this.uin, 10) || 0;
const time = Math.floor(Date.now() / 1000);
return {
time,
self_id: selfId,
post_type: 'meta_event',
meta_event_type: 'lifecycle',
sub_type: subType,
status: {
online: this.online,
good: this.online,
},
};
}
// --- Heartbeat ---
private startHeartbeat(): void {
this.heartbeatTimer = setInterval(() => {
this.dispatchEvent(this.makeHeartbeatEvent());
}, OneBotInstance.HEARTBEAT_INTERVAL);
this.heartbeatTimer.unref?.();
}
private makeHeartbeatEvent(): JsonObject {
const selfId = parseInt(this.uin, 10) || 0;
const time = Math.floor(Date.now() / 1000);
return {
time,
self_id: selfId,
post_type: 'meta_event',
meta_event_type: 'heartbeat',
status: { online: this.online, good: this.online },
interval: OneBotInstance.HEARTBEAT_INTERVAL,
};
}
private stopHeartbeat(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.trunc(parsed);
}
return 0;
}
+164
View File
@@ -0,0 +1,164 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { BridgeManager } from '@snowluma/core/manager';
import { createLogger } from '@snowluma/common/logger';
import { loadOneBotConfig } from './config';
import { OneBotInstance } from './instance';
const log = createLogger('OneBot');
const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1';
export class OneBotManager {
private readonly instances = new Map<string, OneBotInstance>();
bind(bridgeManager: BridgeManager): void {
bridgeManager.setSessionStartedCallback((uin, bridge) => {
this.onSessionStarted(uin, bridge);
});
bridgeManager.setSessionClosedCallback((uin) => {
this.onSessionClosed(uin);
});
}
getInstance(uin: string): OneBotInstance | null {
return this.instances.get(uin) ?? null;
}
getInstances(): OneBotInstance[] {
return [...this.instances.values()];
}
reloadConfig(uin: string): boolean {
const instance = this.instances.get(uin);
if (!instance) return false;
const config = loadOneBotConfig(uin, { persistDefaults: true });
instance.reloadConfig(config);
log.info('configuration reloaded: UIN=%s', uin);
return true;
}
dispose(): void {
for (const instance of this.instances.values()) {
instance.dispose();
}
this.instances.clear();
}
private onSessionStarted(uin: string, bridge: BridgeInterface): void {
if (this.instances.has(uin)) return;
const config = loadOneBotConfig(uin, { persistDefaults: true });
const instance = new OneBotInstance(uin, bridge, config);
const activePid = bridge.activePid;
if (activePid !== null) {
instance.addPid(activePid);
}
// Seed nickname with the UIN so the WebUI never renders blank while
// warmup is in flight or if warmup never resolves a real nickname.
if (!bridge.identity.nickname) bridge.identity.nickname = uin;
this.instances.set(uin, instance);
log.info('session started: UIN=%s', uin);
// Warm up bridge state asynchronously (mirrors C++ warm_up_bridge_state)
warmUpBridgeState(uin, bridge).catch((err) => {
log.warn('warmup error for UIN %s: %s', uin, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
private onSessionClosed(uin: string): void {
const instance = this.instances.get(uin);
if (!instance) return;
instance.dispose();
this.instances.delete(uin);
log.info('session closed: UIN=%s', uin);
}
}
async function warmUpBridgeState(uin: string, bridge: BridgeInterface): Promise<void> {
const selfUin = parseInt(uin, 10) || 0;
let selfResolved = false;
// Step 1: Fetch friend list + derive self profile when QQ happens to
// include self in the response. Some accounts / versions omit self,
// which used to leave identity.nickname empty — see step 1b for the
// explicit fallback.
try {
const friends = await bridge.apis.contacts.fetchFriendList();
log.info('friends loaded: UIN=%s count=%d', uin, friends.length);
for (const f of friends) {
if (f.uin === selfUin) {
bridge.identity.setSelfProfile({
uin: f.uin, uid: f.uid,
nickname: f.nickname || uin,
remark: '', qid: '', sex: 'unknown', age: 0, sign: '', avatar: '',
});
bridge.identity.nickname = f.nickname || uin;
log.debug('self info: UIN=%s uid=%s nickname=%s', uin, f.uid, f.nickname ?? '');
selfResolved = true;
break;
}
}
} catch (e) {
log.warn('failed to load friends for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
// Step 1b: friend-list path didn't resolve self → fetch user profile
// directly via OIDB 0xFE1_2 so multi-account WebUI shows a nickname
// for every injected session, not just the ones where QQ echoed self
// back in the friend list.
if (!selfResolved && selfUin > 0) {
try {
const profile = await bridge.apis.contacts.fetchUserProfile(selfUin);
bridge.identity.setSelfProfile(profile);
bridge.identity.nickname = profile.nickname || uin;
log.debug('self info via profile: UIN=%s uid=%s nickname=%s',
uin, profile.uid, profile.nickname);
} catch (e) {
log.warn('failed to load self profile for UIN %s: %s',
uin, e instanceof Error ? e.message : String(e));
}
}
// Step 2: Fetch group list
let groups: { groupId: number }[] = [];
try {
groups = await bridge.apis.contacts.fetchGroupList();
log.info('groups loaded: UIN=%s count=%d', uin, groups.length);
} catch (e) {
log.warn('failed to load groups for UIN %s: %s', uin, e instanceof Error ? e.message : String(e));
}
// Step 3: Fetch members for each group
let loadedGroupCount = 0;
let loadedMemberCount = 0;
let failedGroupCount = 0;
for (const g of groups) {
try {
const members = await bridge.apis.contacts.fetchGroupMemberList(g.groupId);
loadedGroupCount += 1;
loadedMemberCount += members.length;
if (VERBOSE_WARMUP) {
log.debug('members loaded: group=%d count=%d', g.groupId, members.length);
}
} catch (e) {
failedGroupCount += 1;
log.warn('failed to load members for group %d: %s', g.groupId, e instanceof Error ? e.message : String(e));
}
}
log.info(
'member warmup completed: UIN=%s groups=%d/%d members=%d failed=%d',
uin,
loadedGroupCount,
groups.length,
loadedMemberCount,
failedGroupCount,
);
}
+82
View File
@@ -0,0 +1,82 @@
// Side-channel observer that watches every image / record / video
// segment emitted by the event converter and writes a row into the
// MediaStore so later `get_image` / `get_record` OneBot actions can
import type { MessageElement } from '@snowluma/bridge/events';
import type { MediaStore } from './media-store';
import type { JsonObject } from './types';
export type MediaType = 'image' | 'record' | 'video';
export class MediaIndexer {
constructor(private readonly mediaStore: MediaStore) { }
remember(
mediaType: MediaType,
element: MessageElement,
data: JsonObject,
isGroup: boolean,
sessionId: number,
): void {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (mediaType === 'image') {
this.mediaStore.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
width: element.width,
height: element.height,
picFormat: element.picFormat,
});
return;
}
if (mediaType === 'record') {
this.mediaStore.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
voiceFormat: element.voiceFormat,
});
return;
}
// video
this.mediaStore.rememberVideo({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
md5Hex: element.md5Hex,
sha1Hex: element.sha1Hex,
width: element.width,
height: element.height,
videoFormat: element.videoFormat,
});
}
}
+302
View File
@@ -0,0 +1,302 @@
// Persistent media metadata store.
//
// The `get_image` / `get_record` actions need to map a `data.file` (or related
// identifier) we previously emitted in a message segment back to the URL,
// size, name, and any OIDB media-node info needed to re-resolve a stale URL.
import fs from 'fs';
import { DatabaseSync, type StatementSync } from 'node:sqlite';
import path from 'path';
import type { MessageElement } from '@snowluma/bridge/events';
export interface CachedImage {
/** Primary `data.file` value as exposed in the OneBot segment. */
file: string;
/** Last known resolved URL (may be empty if resolution failed). */
url: string;
fileSize: number;
fileName: string;
subType: number;
summary: string;
/** Conversation the media originated from. */
isGroup: boolean;
sessionId: number;
/** Original imageUrl from the MessageElement, used for RKey re-appending. */
imageUrl: string;
/** Fingerprints used for md5/sha1 fast-upload on forward. Optional because
* legacy CustomFace / NotOnlineImage only carry md5. */
md5Hex?: string;
sha1Hex?: string;
width?: number;
height?: number;
picFormat?: number;
}
export interface CachedRecord {
/** Primary `data.file` value as exposed in the OneBot segment. */
file: string;
/** Raw fileId from the MessageElement (typically the fileUuid). */
fileId: string;
/** Last known resolved URL (may be empty if resolution failed). */
url: string;
fileSize: number;
fileName: string;
duration: number;
fileHash: string;
/** OIDB media node used to re-fetch the URL via getPtt*UrlByNode. */
mediaNode?: MessageElement['mediaNode'];
/** Conversation the media originated from (group vs private path). */
isGroup: boolean;
sessionId: number;
/** Fingerprints used for md5/sha1 fast-upload on forward. */
md5Hex?: string;
sha1Hex?: string;
voiceFormat?: number;
}
export interface CachedVideo {
file: string;
fileId: string;
url: string;
fileSize: number;
fileName: string;
duration: number;
fileHash: string;
mediaNode?: MessageElement['mediaNode'];
isGroup: boolean;
sessionId: number;
/** Fingerprints used for md5/sha1 fast-upload on forward. */
md5Hex?: string;
sha1Hex?: string;
width?: number;
height?: number;
videoFormat?: number;
}
const TYPE_IMAGE = 'image';
const TYPE_RECORD = 'record';
const TYPE_VIDEO = 'video';
const DEFAULT_KEEP_ENTRIES = 4096;
export class MediaStore {
private readonly db: DatabaseSync;
private readonly maxEntriesPerType: number;
// Prepared statements (pay the parsing cost once at startup).
private readonly upsertEntry: StatementSync;
private readonly upsertKey: StatementSync;
private readonly findEntryByKey: StatementSync;
private readonly findEntryByPrimary: StatementSync;
private readonly evictByType: StatementSync;
private readonly purgeOrphanKeys: StatementSync;
private readonly countByType: StatementSync;
constructor(dbPath: string, maxEntriesPerType = DEFAULT_KEEP_ENTRIES) {
this.maxEntriesPerType = Math.max(64, maxEntriesPerType);
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
this.db = new DatabaseSync(dbPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
this.upsertEntry = this.db.prepare(
`INSERT INTO media_entries (type, primary_key, data, last_seen)
VALUES (?, ?, ?, ?)
ON CONFLICT(type, primary_key) DO UPDATE SET
data = excluded.data,
last_seen = excluded.last_seen`,
);
this.upsertKey = this.db.prepare(
`INSERT INTO media_keys (type, key, primary_key)
VALUES (?, ?, ?)
ON CONFLICT(type, key) DO UPDATE SET primary_key = excluded.primary_key`,
);
this.findEntryByKey = this.db.prepare(
`SELECT e.data FROM media_entries e
JOIN media_keys k ON k.type = e.type AND k.primary_key = e.primary_key
WHERE k.type = ? AND k.key = ?
LIMIT 1`,
);
this.findEntryByPrimary = this.db.prepare(
`SELECT data FROM media_entries WHERE type = ? AND primary_key = ?`,
);
this.evictByType = this.db.prepare(
// `rowid DESC` makes the tiebreaker match insertion order (newest first)
// so reproducible inserts within the same `last_seen` second still get
// the most recent rows retained, regardless of how the lexicographic
// sort would have ordered the synthetic primary_key.
`DELETE FROM media_entries WHERE type = ? AND rowid IN (
SELECT rowid FROM media_entries
WHERE type = ?
ORDER BY last_seen DESC, rowid DESC
LIMIT -1 OFFSET ?
)`,
);
this.purgeOrphanKeys = this.db.prepare(
`DELETE FROM media_keys WHERE type = ? AND primary_key NOT IN (
SELECT primary_key FROM media_entries WHERE type = ?
)`,
);
this.countByType = this.db.prepare(
`SELECT COUNT(*) AS n FROM media_entries WHERE type = ?`,
);
}
close(): void {
this.db.close();
}
rememberImage(info: CachedImage): void {
const primaryKey = pickPrimary([info.file, info.fileName]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_IMAGE, primaryKey, info, [info.file, info.fileName, info.url]);
}
rememberRecord(info: CachedRecord): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_RECORD, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
rememberVideo(info: CachedVideo): void {
const primaryKey = pickPrimary([info.file, info.fileName, info.fileId]);
if (!primaryKey) return;
this.upsertWithAliases(TYPE_VIDEO, primaryKey, info, [info.file, info.fileName, info.fileId, info.url]);
}
findImage(key: string): CachedImage | null {
return this.findByAnyKey<CachedImage>(TYPE_IMAGE, key);
}
findRecord(key: string): CachedRecord | null {
return this.findByAnyKey<CachedRecord>(TYPE_RECORD, key);
}
findVideo(key: string): CachedVideo | null {
return this.findByAnyKey<CachedVideo>(TYPE_VIDEO, key);
}
updateImageUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findImage(key);
if (!cached || cached.url === url) return;
this.rememberImage({ ...cached, url });
}
updateRecordUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findRecord(key);
if (!cached || cached.url === url) return;
this.rememberRecord({ ...cached, url });
}
updateVideoUrl(key: string, url: string): void {
if (!url) return;
const cached = this.findVideo(key);
if (!cached || cached.url === url) return;
this.rememberVideo({ ...cached, url });
}
/** Snapshot count of distinct entries per type; mostly used by tests. */
size(): { images: number; records: number; videos: number } {
const img = this.countByType.get(TYPE_IMAGE) as { n: number } | undefined;
const rec = this.countByType.get(TYPE_RECORD) as { n: number } | undefined;
const vid = this.countByType.get(TYPE_VIDEO) as { n: number } | undefined;
return { images: img?.n ?? 0, records: rec?.n ?? 0, videos: vid?.n ?? 0 };
}
// --- internals ---
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS media_entries (
type TEXT NOT NULL,
primary_key TEXT NOT NULL,
data TEXT NOT NULL,
last_seen INTEGER NOT NULL,
PRIMARY KEY (type, primary_key)
);
CREATE INDEX IF NOT EXISTS idx_media_entries_lastseen
ON media_entries(type, last_seen DESC);
CREATE TABLE IF NOT EXISTS media_keys (
type TEXT NOT NULL,
key TEXT NOT NULL,
primary_key TEXT NOT NULL,
PRIMARY KEY (type, key)
);
CREATE INDEX IF NOT EXISTS idx_media_keys_primary
ON media_keys(type, primary_key);
`);
}
private upsertWithAliases<T>(
type: string,
primaryKey: string,
info: T,
aliases: (string | undefined)[],
): void {
const data = JSON.stringify(info);
const lastSeen = Math.floor(Date.now() / 1000);
// Run the writes in a transaction so concurrent readers always see a
// consistent (entry, keys) pair.
this.db.exec('BEGIN');
try {
this.upsertEntry.run(type, primaryKey, data, lastSeen);
const seen = new Set<string>();
for (const raw of aliases) {
if (!raw) continue;
if (seen.has(raw)) continue;
seen.add(raw);
this.upsertKey.run(type, raw, primaryKey);
}
this.db.exec('COMMIT');
} catch (err) {
try { this.db.exec('ROLLBACK'); } catch { /* ignore */ }
throw err;
}
// Eager eviction. The DELETE is a no-op when row count <= cap so
// there is no measurable cost while we are below the limit.
this.evictOldEntries(type);
}
private findByAnyKey<T>(type: string, key: string): T | null {
if (!key) return null;
const row = this.findEntryByKey.get(type, key) as { data: string } | undefined;
if (row?.data) return safeParse<T>(row.data);
// Fall back to looking up by primary_key directly so callers that pass
// the canonical identifier still hit (e.g. when the alias index is yet
// to be built for that key in this session).
const fallback = this.findEntryByPrimary.get(type, key) as { data: string } | undefined;
return fallback?.data ? safeParse<T>(fallback.data) : null;
}
private evictOldEntries(type: string): void {
try {
this.evictByType.run(type, type, this.maxEntriesPerType);
this.purgeOrphanKeys.run(type, type);
} catch {
// Best-effort eviction; don't propagate.
}
}
}
function pickPrimary(candidates: (string | undefined)[]): string {
for (const c of candidates) {
if (c && c.length > 0) return c;
}
return '';
}
function safeParse<T>(json: string): T | null {
try {
return JSON.parse(json) as T;
} catch {
return null;
}
}
+50
View File
@@ -0,0 +1,50 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { MessageElement } from '@snowluma/bridge/events';
import type { RKeyCache } from './instance-rkey';
export class MediaUrlResolver {
constructor(
private readonly bridge: BridgeInterface,
private readonly rkeyCache: RKeyCache,
) { }
async resolve(element: MessageElement, isGroup: boolean, sessionId: number): Promise<string> {
if (!element.url) {
try {
await this.populateUrl(element, isGroup, sessionId);
} catch {
// Best-effort: a URL fetch hiccup should never block the
// outgoing segment. The RKey pass below still runs.
}
}
return this.rkeyCache.resolveMediaUrl(this.bridge, element, isGroup);
}
/** Branches by element.type + isGroup to pick the right Bridge API.
* Mutates `element.url` in-place so the caller sees the same URL
* the downstream rkey/media-store path will see. */
private async populateUrl(element: MessageElement, isGroup: boolean, sessionId: number): Promise<void> {
if (element.type === 'file' && element.fileId) {
if (isGroup) {
element.url = await this.bridge.apis.groupFile.getUrl(sessionId, element.fileId);
} else if (element.fileHash) {
element.url = await this.bridge.apis.groupFile.getPrivateUrl(sessionId, element.fileId, element.fileHash);
} else {
element.url = '';
}
return;
}
if ((element.type === 'record' || element.type === 'video') && element.mediaNode) {
if (isGroup) {
element.url = element.type === 'record'
? await this.bridge.apis.groupFile.getPttUrl(sessionId, element.mediaNode)
: await this.bridge.apis.groupFile.getVideoUrl(sessionId, element.mediaNode);
} else {
element.url = element.type === 'record'
? await this.bridge.apis.groupFile.getPrivatePttUrl(element.mediaNode)
: await this.bridge.apis.groupFile.getPrivateVideoUrl(element.mediaNode);
}
}
}
}
+15
View File
@@ -0,0 +1,15 @@
import { createHash } from 'node:crypto';
export const GROUP_MESSAGE_EVENT = 'group_message';
export const PRIVATE_MESSAGE_EVENT = 'private_message';
export function hashMessageIdInt32(sequence: number, sessionId: number, eventName: string): number {
const seq = Number.isFinite(sequence) ? Math.trunc(sequence) : 0;
const session = Number.isFinite(sessionId) ? Math.trunc(sessionId) : 0;
const key = `${seq}:${session}:${eventName}`;
const digest = createHash('sha1').update(key).digest();
let id = digest.readInt32BE(0);
if (id === 0) id = 1;
return id;
}
+421
View File
@@ -0,0 +1,421 @@
import type { MessageElement } from '@snowluma/bridge/events';
import { createLogger } from '@snowluma/common/logger';
import type { JsonValue } from './types';
const log = createLogger('MsgParser');
export interface ParseMessageOptions {
resolveReplySequence?: (replyMessageId: number) => number | null;
resolveReplyMeta?: (replyMessageId: number) => { senderUin: number; time: number; random: number } | null;
resolveMentionUid?: (targetUin: number) => string | null | Promise<string | null>;
musicSignUrl?: string;
}
// --- CQ Code parsing ---
const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g;
/**
* Best-effort base-10 integer coercion. Falls back to `fallback` (default 0)
* when the input can't be parsed as a finite integer — `parseInt('abc')`
* is `NaN`, which silently turns into `0`/`null` further down the wire
* pipeline and produces undebuggable protocol-level failures.
*/
function intOr(value: unknown, fallback = 0): number {
if (value === undefined || value === null) return fallback;
if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback;
const n = parseInt(String(value), 10);
return Number.isFinite(n) ? n : fallback;
}
function parseCQParams(raw: string): Record<string, string> {
const params: Record<string, string> = {};
if (!raw) return params;
for (const pair of raw.split(',')) {
const eq = pair.indexOf('=');
if (eq > 0) {
params[pair.substring(0, eq)] = pair.substring(eq + 1)
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
}
return params;
}
function cqUnescape(text: string): string {
// Order matters: `&amp;` MUST be last so that, e.g., `&amp;#91;` keeps
// the literal `&#91;` instead of decoding twice into `[`.
return text
.replace(/&#91;/g, '[')
.replace(/&#93;/g, ']')
.replace(/&#44;/g, ',')
.replace(/&amp;/g, '&');
}
async function parseFromCQString(message: string, options?: ParseMessageOptions): Promise<MessageElement[]> {
const elements: MessageElement[] = [];
let lastIndex = 0;
for (const match of message.matchAll(CQ_REGEX)) {
// Text before this CQ code
if (match.index! > lastIndex) {
const text = cqUnescape(message.substring(lastIndex, match.index!));
if (text) elements.push({ type: 'text', text });
}
lastIndex = match.index! + match[0].length;
const cqType = match[1];
const params = parseCQParams(match[2] || '');
const elem = await segmentToElement(cqType, params, options);
if (elem) elements.push(elem);
}
// Trailing text
if (lastIndex < message.length) {
const text = cqUnescape(message.substring(lastIndex));
if (text) elements.push({ type: 'text', text });
}
return elements;
}
// --- JSON segment parsing ---
interface MessageSegment {
type: string;
data?: Record<string, unknown>;
[key: string]: unknown;
}
function isSegmentArray(val: unknown): val is MessageSegment[] {
return Array.isArray(val) && val.every(
(item) => typeof item === 'object' && item !== null && 'type' in item
);
}
async function segmentToElement(type: string, data: Record<string, unknown>, options?: ParseMessageOptions): Promise<MessageElement | null> {
const normalizedType = type.toLowerCase();
switch (normalizedType) {
case 'text': {
const text = String(data.text ?? '');
return text ? { type: 'text', text } : null;
}
case 'face': {
const id = intOr(data.id, -1);
if (id < 0) return null;
return { type: 'face', faceId: id };
}
case 'at': {
const qq = String(data.qq ?? '').trim();
if (qq === 'all') {
return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' };
}
const uin = intOr(qq, 0);
if (uin <= 0) return null;
const name = String(data.name ?? data.nickname ?? data.card ?? '').trim();
let uid = String(data.uid ?? '').trim();
if (!uid && options?.resolveMentionUid) {
uid = (await options.resolveMentionUid(uin))?.trim() ?? '';
}
// Leave `text` undefined when the caller didn't supply a display
// name. The element-builder then resolves it from the group roster
// (so QQ renders `@昵称` instead of `@QQ号`).
const element: MessageElement = { type: 'at', targetUin: uin };
if (uid) element.uid = uid;
if (name) element.text = `@${name} `;
return element;
}
case 'reply': {
const id = intOr(data.id, 0);
if (id === 0) return null;
if (options?.resolveReplySequence) {
const resolved = options.resolveReplySequence(id);
if (typeof resolved === 'number' && resolved > 0) {
const element: MessageElement = {
type: 'reply',
replySeq: resolved,
replyMessageId: id // Keep the original messageId for logging
};
// Try to get additional meta info for better reply display
if (options?.resolveReplyMeta) {
const meta = options.resolveReplyMeta(id);
if (meta) {
element.replySenderUin = meta.senderUin;
element.replyTime = meta.time;
element.replyRandom = meta.random;
}
}
return element;
}
}
// Backward-compatible path: allow direct seq reply IDs.
return id > 0 ? { type: 'reply', replySeq: id } : null;
}
case 'image': {
return {
type: 'image',
url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''),
flash: data.type === 'flash',
subType: intOr(data.subType, 0),
summary: data.summary ? String(data.summary) : undefined,
};
}
case 'record': {
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
if (!source) return null;
return {
type: 'record',
url: source,
};
}
case 'video': {
const source = String(data.file ?? data.url ?? data.path ?? data.media ?? '');
if (!source) return null;
return {
type: 'video',
url: source,
thumbUrl: data.thumb ? String(data.thumb) : undefined,
};
}
case 'json': {
return {
type: 'json',
text: String(data.data ?? ''),
};
}
case 'xml': {
return {
type: 'xml',
text: String(data.data ?? ''),
subType: intOr(data.id, 0),
};
}
case 'poke': {
return {
type: 'poke',
faceId: intOr(data.type ?? data.id, 0),
};
}
case 'forward': {
return {
type: 'forward',
resId: String(data.id ?? ''),
};
}
case 'node': {
// Fake forward node segment — store the raw data for later processing
// The content field may be a segment array, a single segment, or a CQ string
const name = String(data.nickname ?? data.name ?? '');
return {
type: 'node',
targetUin: intOr(data.user_id ?? data.uin, 0),
text: name,
// Raw content is stored as JSON string in resId for later processing
resId: JSON.stringify(data.content ?? ''),
};
}
case 'markdown': {
return {
type: 'markdown',
text: String(data.content ?? ''),
};
}
case 'share': {
// Link share — map to json card message
const url = String(data.url ?? '');
const title = String(data.title ?? '');
const content = String(data.content ?? '');
const image = String(data.image ?? '');
const jsonData = JSON.stringify({
app: 'com.tencent.structmsg',
view: 'news',
prompt: title,
meta: { news: { title, desc: content, jumpUrl: url, preview: image } },
});
return { type: 'json', text: jsonData };
}
case 'music': {
// Music share — uses external signing service (NapCat-compatible)
const musicType = String(data.type ?? '');
const signUrl = options?.musicSignUrl || 'https://ss.xingzhige.com/music_card/card';
try {
let postData: Record<string, unknown>;
if (musicType === 'custom') {
postData = {
type: 'custom',
id: undefined,
url: String(data.url ?? ''),
audio: String(data.audio ?? ''),
title: String(data.title ?? ''),
image: String(data.image ?? ''),
singer: String(data.content ?? ''),
};
} else {
postData = { type: musicType, id: String(data.id ?? '') };
}
const resp = await fetch(signUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(postData),
});
if (!resp.ok) throw new Error(`music sign HTTP ${resp.status}`);
const musicJson = await resp.text();
return { type: 'json', text: musicJson };
} catch (e) {
log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e));
// Fallback: build a basic card locally
const title = String(data.title ?? 'Music');
const jsonData = JSON.stringify({
app: 'com.tencent.structmsg',
view: 'music',
prompt: `[音乐]${title}`,
meta: {
music: {
title,
desc: String(data.content ?? ''),
jumpUrl: String(data.url ?? ''),
musicUrl: String(data.audio ?? ''),
preview: String(data.image ?? ''),
},
},
});
return { type: 'json', text: jsonData };
}
}
case 'location': {
// Location — map to json card
const lat = String(data.lat ?? '');
const lon = String(data.lon ?? '');
const title = String(data.title ?? '位置');
const content = String(data.content ?? `${lat},${lon}`);
const jsonData = JSON.stringify({
app: 'com.tencent.map',
view: 'LocationShare',
prompt: `[位置]${title}`,
meta: { Location: { lat, lng: lon, title, address: content } },
});
return { type: 'json', text: jsonData };
}
case 'contact': {
// Contact card — map to json card
const contactType = String(data.type ?? 'qq');
const contactId = String(data.id ?? '');
const jsonData = JSON.stringify({
app: 'com.tencent.contact.lua',
view: 'contact',
prompt: `[推荐${contactType === 'group' ? '群' : '好友'}]`,
meta: { contact: { type: contactType, id: contactId } },
});
return { type: 'json', text: jsonData };
}
case 'rps': {
// Rock-paper-scissors — map to dice-like face
return { type: 'face', faceId: 359 };
}
case 'dice': {
// Dice — map to dice face
return { type: 'face', faceId: 358 };
}
case 'shake': {
// Window shake — map to poke
return { type: 'poke', faceId: 1 };
}
case 'anonymous': {
// Anonymous flag — ignored during send, the protocol handles anonymity
return null;
}
case 'file': {
// OneBot11 file segment referencing a previously-uploaded file
// (returned by `upload_group_file` / `upload_private_file`).
// We deliberately do NOT support `{file: '/path'}` here because
// the upload pipeline is async and lives behind the bridge —
// the element-builder runs synchronously over the parsed
// message. Callers that want upload-and-send should use the
// dedicated `upload_*` actions which now publish the file in
// chat atomically (`actions/group-file.ts`).
const fileId = String(data.file_id ?? data.fileId ?? '').trim();
if (!fileId) {
log.warn('[MsgParser] file segment without file_id is unsupported (upload first via upload_group_file / upload_private_file)');
return null;
}
const fileName = String(data.name ?? data.filename ?? data.fileName ?? '').trim();
const fileSize = intOr(data.size ?? data.fileSize, 0);
const md5Hex = String(data.md5 ?? data.md5Hex ?? '').trim();
const sha1Hex = String(data.sha1 ?? data.sha1Hex ?? '').trim();
// file_hash is the c2c-file server-issued addon string — needed
// on the wire when re-sending a previously-uploaded c2c file.
// get_private_file_url callers already pass it through, so honour
// the same field naming here.
const fileHash = String(data.file_hash ?? data.fileHash ?? '').trim();
const elem: MessageElement = { type: 'file', fileId };
if (fileName) elem.fileName = fileName;
if (fileSize > 0) elem.fileSize = fileSize;
if (md5Hex) elem.md5Hex = md5Hex;
if (sha1Hex) elem.sha1Hex = sha1Hex;
if (fileHash) elem.fileHash = fileHash;
return elem;
}
default:
console.warn(`[MsgParser] unsupported segment type: ${type}`);
return null;
}
}
function segmentPayload(seg: MessageSegment): Record<string, unknown> {
const topLevel = { ...seg } as Record<string, unknown>;
delete topLevel.type;
delete topLevel.data;
const nested = (seg.data && typeof seg.data === 'object' && !Array.isArray(seg.data))
? seg.data
: {};
return { ...topLevel, ...nested };
}
// --- Public API ---
/**
* Parse an OneBot11 message value into internal MessageElement array.
* Supports:
* - string (plain text or CQ code string)
* - array of { type, data } segments (JSON segment format)
*
* If autoEscape is true, the string is treated as plain text (no CQ parsing).
*/
export async function parseMessage(message: JsonValue, autoEscape: boolean, options?: ParseMessageOptions): Promise<MessageElement[]> {
if (typeof message === 'string') {
if (autoEscape) {
return message ? [{ type: 'text', text: message }] : [];
}
return parseFromCQString(message, options);
}
if (isSegmentArray(message)) {
const elements: MessageElement[] = [];
for (const seg of message) {
const data = segmentPayload(seg);
const elem = await segmentToElement(seg.type, data, options);
if (elem) elements.push(elem);
}
return elements;
}
// Single segment object
if (typeof message === 'object' && message !== null && !Array.isArray(message)) {
const seg = message as unknown as MessageSegment;
if (seg.type) {
const data = segmentPayload(seg);
const elem = await segmentToElement(seg.type, data, options);
return elem ? [elem] : [];
}
}
return [];
}
+231
View File
@@ -0,0 +1,231 @@
import fs from 'fs';
import { DatabaseSync } from 'node:sqlite';
import path from 'path';
import type { JsonObject, MessageMeta } from './types';
export class MessageStore {
private readonly db: DatabaseSync;
constructor(dbPath: string) {
const dir = path.dirname(dbPath);
fs.mkdirSync(dir, { recursive: true });
// Replace .json extension with .db if present
const finalPath = dbPath.replace(/\.json$/, '.db');
this.db = new DatabaseSync(finalPath);
this.db.exec('PRAGMA journal_mode = WAL');
this.db.exec('PRAGMA synchronous = NORMAL');
this.initSchema();
}
close(): void {
this.db.close();
}
storeEvent(
messageId: number,
isGroup: boolean,
sessionId: number,
sequence: number,
eventName: string,
event: JsonObject
): void {
if (!isValidMessageId(messageId)) return;
const json = JSON.stringify(event);
const timestamp = toInt(event.time);
this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp, data)
VALUES (?, ?, ?, ?, ?, 0, 0, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
event_name = excluded.event_name,
timestamp = excluded.timestamp,
data = excluded.data`
).run(messageId, isGroup ? 1 : 0, sessionId, sequence, eventName, timestamp, json);
}
storeMeta(messageId: number, meta: MessageMeta): void {
if (!isValidMessageId(messageId)) return;
this.db.prepare(
`INSERT INTO messages
(message_hash, is_group, session_id, sequence, event_name, client_sequence, random, timestamp)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
ON CONFLICT(message_hash) DO UPDATE SET
is_group = excluded.is_group,
session_id = excluded.session_id,
sequence = excluded.sequence,
event_name = excluded.event_name,
client_sequence = excluded.client_sequence,
random = excluded.random,
timestamp = excluded.timestamp`
).run(
messageId,
meta.isGroup ? 1 : 0,
meta.targetId,
meta.sequence,
meta.eventName,
meta.clientSequence,
meta.random,
meta.timestamp
);
}
findEvent(messageId: number): JsonObject | null {
if (!isValidMessageId(messageId)) return null;
const row = this.db.prepare(
'SELECT data FROM messages WHERE message_hash = ? AND data IS NOT NULL',
).get(messageId) as { data: string } | undefined;
if (!row?.data) return null;
try {
return JSON.parse(row.data) as JsonObject;
} catch {
return null;
}
}
findMeta(messageId: number): MessageMeta | null {
if (!isValidMessageId(messageId)) return null;
const row = this.db.prepare(
'SELECT is_group, session_id, sequence, event_name, client_sequence, random, timestamp FROM messages WHERE message_hash = ?',
).get(messageId) as {
is_group: number;
session_id: number;
sequence: number;
event_name: string;
client_sequence: number;
random: number;
timestamp: number;
} | undefined;
if (!row) return null;
return {
isGroup: row.is_group === 1,
targetId: row.session_id,
sequence: row.sequence,
eventName: row.event_name,
clientSequence: row.client_sequence,
random: row.random,
timestamp: row.timestamp,
};
}
resolveReplySequence(isGroup: boolean, sessionId: number, messageId: number): number | null {
if (!Number.isInteger(sessionId) || sessionId <= 0 || !isValidMessageId(messageId)) {
return null;
}
// For private messages, we cannot rely on session_id matching because:
// - When receiving: session_id is the sender's UIN
// - When sending reply: sessionId parameter is the recipient's UIN (who we're sending to)
// So for private messages, we only match by message_hash and is_group flag.
const row = isGroup
? this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 1 AND session_id = ? AND message_hash = ?
LIMIT 1`
).get(sessionId, messageId) as { sequence: number } | undefined
: this.db.prepare(
`SELECT sequence
FROM messages
WHERE is_group = 0 AND message_hash = ?
LIMIT 1`
).get(messageId) as { sequence: number } | undefined;
if (!row || !Number.isInteger(row.sequence) || row.sequence <= 0) {
return null;
}
return row.sequence;
}
listSessionEvents(
isGroup: boolean,
sessionId: number,
count = 20,
anchorSequence?: number,
): JsonObject[] {
if (!Number.isInteger(sessionId) || sessionId <= 0) return [];
const limit = normalizePositiveInt(count, 20, 200);
const hasAnchor = Number.isInteger(anchorSequence) && (anchorSequence as number) > 0;
const anchor = hasAnchor ? (anchorSequence as number) : 0;
const rows = hasAnchor
? this.db.prepare(
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL AND sequence <= ?
ORDER BY sequence DESC
LIMIT ?`
).all(isGroup ? 1 : 0, sessionId, anchor, limit)
: this.db.prepare(
`SELECT data
FROM messages
WHERE is_group = ? AND session_id = ? AND data IS NOT NULL
ORDER BY sequence DESC
LIMIT ?`
).all(isGroup ? 1 : 0, sessionId, limit);
const result: JsonObject[] = [];
for (const row of rows as Array<{ data: string }>) {
if (!row?.data) continue;
try {
const parsed = JSON.parse(row.data) as JsonObject;
result.push(parsed);
} catch {
// Ignore malformed rows to avoid breaking history APIs.
}
}
// Keep chronological order (oldest -> newest) for API consumers.
result.reverse();
return result;
}
private initSchema(): void {
this.db.exec(`
CREATE TABLE IF NOT EXISTS messages (
message_hash INTEGER PRIMARY KEY,
is_group INTEGER NOT NULL,
session_id INTEGER NOT NULL,
sequence INTEGER NOT NULL,
event_name TEXT NOT NULL,
client_sequence INTEGER NOT NULL DEFAULT 0,
random INTEGER NOT NULL DEFAULT 0,
timestamp INTEGER NOT NULL DEFAULT 0,
data TEXT
)
`);
this.db.exec('CREATE INDEX IF NOT EXISTS idx_messages_session_seq ON messages(is_group, session_id, sequence)');
}
}
function isValidMessageId(messageId: number): boolean {
return Number.isInteger(messageId) && messageId !== 0;
}
function toInt(value: unknown): number {
if (typeof value === 'number' && Number.isFinite(value)) return Math.trunc(value);
if (typeof value === 'string' && value.trim()) {
const parsed = Number(value);
if (Number.isFinite(parsed)) return Math.trunc(parsed);
}
return 0;
}
function normalizePositiveInt(value: number, fallback: number, max: number): number {
if (!Number.isFinite(value)) return fallback;
const n = Math.trunc(value);
if (n <= 0) return fallback;
if (n > max) return max;
return n;
}
@@ -0,0 +1,235 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import type { IdentityService } from '@snowluma/bridge/identity-service';
import type { OneBotInstanceContext } from '../instance-context';
import type { JsonObject } from '../types';
export function getLoginInfo(ref: OneBotInstanceContext): { userId: number; nickname: string } {
const userId = parseInt(ref.uin, 10) || 0;
const nickname = ref.bridge.identity.nickname || ref.uin;
return { userId, nickname };
}
// Keep refreshes scoped. A broad "refresh all members in all groups" call can
// turn one OneBot request into N OIDB calls, which is risky for busy clients.
async function refreshSingleGroupMembers(bridge: BridgeInterface, groupId: number): Promise<void> {
try {
await bridge.apis.contacts.fetchGroupMemberList(groupId);
} catch {
// Use cached data.
}
}
export async function getFriendList(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const friends = await bridge.apis.contacts.fetchFriendList();
return friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
} catch {
return bridge.identity.friends.map(f => ({
user_id: f.uin as any,
nickname: f.nickname as any,
remark: f.remark as any,
}));
}
}
export async function getGroupList(
bridge: BridgeInterface,
noCache?: boolean,
): Promise<JsonObject[]> {
try {
if (noCache || bridge.identity.groups.length === 0) {
await bridge.apis.contacts.fetchGroupList();
}
} catch {
// Use cached data.
}
return bridge.identity.groups.map(g => ({
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
}));
}
export async function getGroupInfo(
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !bridge.identity.findGroup(groupId)) {
try {
await bridge.apis.contacts.fetchGroupList();
} catch {
// Use cached data.
}
}
const g = bridge.identity.findGroup(groupId);
if (!g) return null;
return {
group_id: g.groupId as any,
group_name: g.groupName as any,
member_count: g.memberCount as any,
max_member_count: g.memberMax as any,
};
}
export async function getGroupMemberList(
bridge: BridgeInterface,
groupId: number,
noCache?: boolean,
): Promise<JsonObject[]> {
if (noCache) {
await refreshSingleGroupMembers(bridge, groupId);
return getCachedGroupMembers(bridge.identity, groupId);
}
try {
const members = await bridge.apis.contacts.fetchGroupMemberList(groupId);
return members.map(m => formatGroupMember(groupId, m));
} catch {
return getCachedGroupMembers(bridge.identity, groupId);
}
}
export async function getGroupMemberInfo(
bridge: BridgeInterface,
groupId: number,
userId: number,
noCache?: boolean,
): Promise<JsonObject | null> {
if (noCache || !bridge.identity.findGroupMember(groupId, userId)) {
await refreshSingleGroupMembers(bridge, groupId);
}
const m = bridge.identity.findGroupMember(groupId, userId);
if (!m) return null;
return formatGroupMember(groupId, m);
}
export async function getGroupFiles(
bridge: BridgeInterface,
groupId: number,
folderId?: string,
): Promise<JsonObject> {
const result = await bridge.apis.groupFile.list(groupId, folderId ?? '/');
return {
files: result.files.map((file) => ({
group_id: groupId as any,
file_id: file.fileId as any,
file_name: file.fileName as any,
busid: file.busId as any,
file_size: file.fileSize as any,
upload_time: file.uploadTime as any,
dead_time: file.deadTime as any,
modify_time: file.modifyTime as any,
download_times: file.downloadTimes as any,
uploader: file.uploader as any,
uploader_name: file.uploaderName as any,
} as JsonObject)) as any,
folders: result.folders.map((folder) => ({
group_id: groupId as any,
folder_id: folder.folderId as any,
folder_name: folder.folderName as any,
create_time: folder.createTime as any,
creator: folder.creator as any,
create_name: folder.creatorName as any,
total_file_count: folder.totalFileCount as any,
} as JsonObject)) as any,
};
}
export async function getStrangerInfo(
bridge: BridgeInterface,
userId: number,
): Promise<JsonObject | null> {
try {
const p = await bridge.apis.contacts.fetchUserProfile(userId);
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
};
} catch {
const p = bridge.identity.findUserProfile(userId);
if (!p) return null;
return {
user_id: p.uin as any,
nickname: p.nickname as any,
sex: p.sex as any,
age: p.age as any,
};
}
}
export async function getGroupSystemMessages(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const reqs = await bridge.apis.contacts.fetchGroupRequests();
return reqs.map(r => ({
group_id: r.groupId,
group_name: r.groupName,
request_id: r.sequence,
requester_uin: r.targetUin,
requester_nick: r.targetName,
message: r.comment,
flag: `${r.eventType}:${r.groupId}:${r.targetUid}`,
} as JsonObject));
} catch {
return [];
}
}
export async function getDownloadRKeys(bridge: BridgeInterface): Promise<JsonObject[]> {
try {
const rkeys = await bridge.apis.contacts.fetchDownloadRKeys();
return rkeys.map(r => ({
rkey: r.rkey,
type: r.type,
ttl: r.ttlSeconds,
create_time: r.createTime,
} as JsonObject));
} catch {
return [];
}
}
function getCachedGroupMembers(identity: IdentityService, groupId: number): JsonObject[] {
const g = identity.findGroup(groupId);
if (!g) return [];
const result: JsonObject[] = [];
for (const [, member] of g.members) {
result.push(formatGroupMember(groupId, member));
}
return result;
}
function formatGroupMember(
groupId: number,
member: {
uin: number;
nickname: string;
card: string;
joinTime: number;
lastSentTime: number;
level: number;
role: string;
title: string;
},
): JsonObject {
return {
group_id: groupId as any,
user_id: member.uin as any,
nickname: member.nickname as any,
card: member.card as any,
sex: 'unknown' as any,
age: 0 as any,
join_time: member.joinTime as any,
last_sent_time: member.lastSentTime as any,
level: String(member.level) as any,
role: member.role as any,
title: member.title as any,
};
}
@@ -0,0 +1,53 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
import { createLogger } from '@snowluma/common/logger';
import type { MediaStore } from '../media-store';
import type { JsonObject } from '../types';
const log = createLogger('OneBot');
export async function getImageInfo(
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findImage(file);
if (!cached) return null;
const url = cached.url || cached.imageUrl || '';
return {
file: url || cached.file,
url,
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
export async function getRecordInfo(
bridge: BridgeInterface,
mediaStore: MediaStore,
file: string,
): Promise<JsonObject | null> {
const cached = mediaStore.findRecord(file);
if (!cached) return null;
// Re-resolve via OIDB if the cached URL is missing or empty.
// Mirrors NapCat's getPttUrl path: GetGroupPttUrl / GetPttUrl by fileUuid.
let url = cached.url;
if (!url && cached.mediaNode) {
try {
url = cached.isGroup
? await bridge.apis.groupFile.getPttUrl(cached.sessionId, cached.mediaNode)
: await bridge.apis.groupFile.getPrivatePttUrl(cached.mediaNode);
if (url) {
mediaStore.updateRecordUrl(file, url);
}
} catch (err) {
log.warn('get_record url refetch failed: %s', err instanceof Error ? err.message : String(err));
}
}
return {
file: url || cached.file,
url: url || '',
file_size: String(cached.fileSize ?? 0),
file_name: cached.fileName || cached.file,
};
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,38 @@
import type { BridgeInterface } from '@snowluma/core/bridge-interface';
export async function handleGroupAddRequest(
bridge: BridgeInterface,
flag: string,
approve: boolean,
reason: string,
): Promise<void> {
// flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter)
const parts = flag.split(':');
if (parts.length < 3) throw new Error('invalid group request flag');
const requestType = parts[0];
const groupId = parseInt(parts[1], 10);
const targetUid = parts.slice(2).join(':');
if (!groupId) throw new Error('invalid group_id in flag');
if (!targetUid) throw new Error('invalid request target in flag');
const requests = await bridge.apis.contacts.fetchGroupRequests();
const matching = requests.find((r) => {
if (r.groupId !== groupId) return false;
if (requestType === 'add') return r.targetUid === targetUid;
if (requestType === 'invite') return r.invitorUid === targetUid;
return false;
}) || requests.find(r => r.groupId === groupId);
if (!matching) {
throw new Error('matching group request not found');
}
await bridge.apis.groupAdmin.setAddRequest(
groupId,
matching.sequence,
matching.eventType,
approve,
reason,
matching.filtered,
);
}
+56
View File
@@ -0,0 +1,56 @@
import type { ApiHandler } from '../api-handler';
import type { DispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
export interface NetworkAdapterContext {
/** Self UIN as string — written into outbound headers. */
uin: string;
/** Shared API dispatcher used by request/response style adapters. */
api: ApiHandler;
/** Build a lifecycle event payload (connect/enable/disable). */
buildLifecycleEvent(subType: 'connect' | 'enable' | 'disable'): JsonObject;
/** Build a heartbeat event payload. */
buildHeartbeatEvent(): JsonObject;
}
export enum NetworkReloadType {
/** Configuration unchanged or only soft fields updated. */
Normal = 0,
/** Underlying socket/listener restarted in place. */
Reopened = 1,
/** Was running, now closed. */
Closed = 2,
/** Was idle, now opened. */
Opened = 3,
}
export abstract class IOneBotNetworkAdapter<C extends NetworkBase> {
readonly name: string;
protected config: C;
protected readonly ctx: NetworkAdapterContext;
protected isEnabled = false;
constructor(name: string, config: C, ctx: NetworkAdapterContext) {
this.name = name;
// Defensive copy so reload diffs never mutate the caller's object.
this.config = structuredClone(config);
this.ctx = ctx;
}
/** Whether the adapter is currently accepting/relaying events. */
get isActive(): boolean { return this.isEnabled; }
/** Snapshot of the active config (read-only). */
get currentConfig(): Readonly<C> { return this.config; }
abstract open(): void | Promise<void>;
abstract close(): void | Promise<void>;
abstract reload(config: C): NetworkReloadType | Promise<NetworkReloadType>;
/**
* Receive one fully-shaped OneBot event for forwarding. Adapters that
* don't push events (e.g. HTTP request-response servers) override with a
* no-op.
*/
abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise<void>;
}
@@ -0,0 +1,136 @@
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { HttpClientNetwork, JsonObject } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { executeQuickOperation } from './quick-operation';
const moduleLog = createLogger('OneBot.POST');
const DEFAULT_TIMEOUT_MS = 5000;
export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private readonly log: Logger;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.isEnabled = true;
}
close(): void {
this.isEnabled = false;
}
async reload(next: HttpClientNetwork): Promise<NetworkReloadType> {
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
const newSig = bindingSignature(next);
const sigChanged = newSig !== this.signature_;
this.signature_ = newSig;
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled) return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
void this.postEvent(json, event).catch((err) => {
this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
}
private async postEvent(payload: string, event: JsonObject): Promise<void> {
if (!this.isEnabled) return;
const headers: Record<string, string> = {
'Content-Type': 'application/json',
'User-Agent': 'OneBot',
'X-Self-ID': this.ctx.uin,
};
if (this.config.accessToken) {
headers['X-Signature'] = await computeHmacSha1(this.config.accessToken, payload);
}
const timeoutMs = this.config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
try {
const response = await fetch(this.config.url, {
method: 'POST',
headers,
body: payload,
signal: AbortSignal.timeout(timeoutMs),
});
if (response.ok) {
const contentType = response.headers.get('content-type') ?? '';
if (contentType.includes('application/json')) {
const body = await response.text();
if (body.trim()) {
await this.handleQuickOperation(event, body);
}
}
} else {
this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status);
}
} catch (error) {
if (this.isEnabled) {
this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error));
}
}
}
private async handleQuickOperation(event: JsonObject, responseBody: string): Promise<void> {
try {
const operation = JSON.parse(responseBody) as Record<string, unknown>;
if (!operation || typeof operation !== 'object') return;
await executeQuickOperation(event, operation, this.ctx.api);
} catch (error) {
this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error));
}
}
}
function bindingSignature(net: HttpClientNetwork): string {
return `${net.url}#${net.accessToken ?? ''}#${net.timeoutMs ?? DEFAULT_TIMEOUT_MS}`;
}
async function computeHmacSha1(secret: string, payload: string): Promise<string> {
const { createHmac } = await import('crypto');
return 'sha1=' + createHmac('sha1', secret).update(payload).digest('hex');
}
@@ -0,0 +1,260 @@
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse,
} from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import type { DispatchPayload } from '../event-filter';
import type { HttpServerNetwork, JsonObject, JsonValue } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath } from './utils';
const moduleLog = createLogger('OneBot.HTTP');
export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork> {
private server: Server | null = null;
private readonly log: Logger;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
// HTTP server never receives events — `isActive` purely tracks the
// bound listener so the network manager can skip dispatch cleanly.
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && !this.server) return;
this.isEnabled = false;
this.server?.close();
this.server = null;
}
async reload(next: HttpServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
// HTTP server only acts on inbound requests; it doesn't push events.
onEvent(_event: JsonObject, _payload: DispatchPayload): void { /* no-op */ }
private startServer(): void {
const server = createServer((req, res) => {
void this.handleRequest(req, res);
});
this.server = server;
server.on('listening', () => {
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
normalizePath(this.config.path ?? '/'),
);
});
server.on('error', (err) => {
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
server.listen(this.config.port, this.config.host ?? '0.0.0.0');
}
private async handleRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
// Read `path` + `accessToken` fresh from `this.config` on every
// request so config hot-reloads (`reload()` overwrites `this.config`
// in place) take effect on the very next request without
// re-binding the listener. Matches the ws-server / http-post /
// ws-client adapters, which all read `this.config.accessToken`
// inline at the point of use.
const expectedPath = normalizePath(this.config.path ?? '/');
const accessToken = this.config.accessToken ?? '';
const parsedUrl = new URL(req.url ?? '/', 'http://127.0.0.1');
const incomingPath = parsedUrl.pathname;
const ep = expectedPath.endsWith('/') ? expectedPath : expectedPath + '/';
let action = '';
if (incomingPath === expectedPath || incomingPath === expectedPath + '/') {
action = '';
} else if (incomingPath.startsWith(ep)) {
action = incomingPath.substring(ep.length);
} else {
writeJson(res, 404, { status: 'failed', retcode: 1404, data: null, wording: 'not found' });
return;
}
if (!isAuthorized(req, accessToken)) {
writeJson(res, 401, { status: 'failed', retcode: 1401, data: null, wording: 'unauthorized' });
return;
}
if (req.method === 'GET' && !action) {
writeJson(res, 200, { status: 'ok', retcode: 0, data: { online: true } });
return;
}
try {
let params: Record<string, unknown> = {};
let echo: unknown;
if (req.method === 'GET') {
parsedUrl.searchParams.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
} else if (req.method === 'POST') {
const bodyContent = await readRequestBody(req);
if (bodyContent.trim()) {
const contentType = req.headers['content-type'] ?? '';
if (contentType.includes('application/x-www-form-urlencoded')) {
const parsed = new URLSearchParams(bodyContent);
parsed.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
if (params.action && !action) {
action = String(params.action);
delete params.action;
}
if (params.echo !== undefined) {
echo = params.echo;
delete params.echo;
}
} else if (contentType.includes('application/json') || !contentType) {
try {
const parsedBody = JSON.parse(bodyContent);
if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) {
if (parsedBody.action && !action) action = String(parsedBody.action);
if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) {
params = parsedBody.params as Record<string, unknown>;
} else {
params = parsedBody as Record<string, unknown>;
}
echo = parsedBody.echo;
}
} catch {
if (contentType.includes('application/json')) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' });
return;
}
// 无 content-type,JSON 失败则 fallback 到 urlencoded
const parsed = new URLSearchParams(bodyContent);
parsed.forEach((value, key) => {
try {
params[key] = JSON.parse(value);
} catch {
params[key] = value;
}
});
if (params.action && !action) {
action = String(params.action);
delete params.action;
}
if (params.echo !== undefined) {
echo = params.echo;
delete params.echo;
}
}
} else {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` });
return;
}
}
} else {
writeJson(res, 405, { status: 'failed', retcode: 1400, data: null, wording: 'method not allowed' });
return;
}
if (!action) {
writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: missing action' });
return;
}
const response = await this.ctx.api.handle(action, params as JsonObject);
if (echo !== undefined) {
response.echo = echo as JsonValue;
}
writeJson(res, 200, response);
} catch (error) {
const wording = error instanceof Error ? error.message : 'internal error';
writeJson(res, 500, { status: 'failed', retcode: 1200, data: null, wording });
}
}
}
function bindingSignature(net: HttpServerNetwork): string {
// `accessToken` deliberately omitted: it's read per-request from
// `this.config`, so a token change doesn't need to re-bind the
// listener. Including it here would cause a `close()` + `listen()`
// round trip on every token edit — a needless port-rebind that, on
// some hosts, races with the OS releasing the port and lands the
// server in a half-broken state where the old token still
// authenticates because the EADDRINUSE-failing new server never
// replaced the old one. `host`/`port`/`path` still gate a restart
// because Node's HTTP `Server.listen()` binds the socket on those.
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path ?? '/')}`;
}
function readRequestBody(req: IncomingMessage, maxBytes = 2 * 1024 * 1024): Promise<string> {
return new Promise((resolve, reject) => {
const chunks: Buffer[] = [];
let total = 0;
req.on('data', (chunk: Buffer) => {
total += chunk.length;
if (total > maxBytes) {
reject(new Error('request body too large'));
req.destroy();
return;
}
chunks.push(chunk);
});
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
req.on('error', reject);
});
}
function writeJson(res: ServerResponse, statusCode: number, data: unknown): void {
res.statusCode = statusCode;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(data));
}
+8
View File
@@ -0,0 +1,8 @@
export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
export { HttpPostAdapter } from './http-post-adapter';
export { HttpServerAdapter } from './http-server-adapter';
export { OneBotNetworkManager } from './network-manager';
export { executeQuickOperation } from './quick-operation';
export { WsClientAdapter } from './ws-client-adapter';
export { WsServerAdapter } from './ws-server-adapter';
@@ -0,0 +1,99 @@
import { createLogger } from '@snowluma/common/logger';
import { buildDispatchPayload } from '../event-filter';
import type { JsonObject, NetworkBase } from '../types';
import { IOneBotNetworkAdapter } from './adapter';
const log = createLogger('OneBot.Network');
type AnyAdapter = IOneBotNetworkAdapter<NetworkBase>;
export class OneBotNetworkManager {
private readonly adapters = new Map<string, AnyAdapter>();
register<C extends NetworkBase>(adapter: IOneBotNetworkAdapter<C>): void {
const existing = this.adapters.get(adapter.name);
if (existing) {
// Replacing an adapter under the same name — close the previous one
// before storing the new instance to keep ports/sockets clean.
log.info('replacing adapter [%s]', adapter.name);
void Promise.resolve(existing.close()).catch(() => { /* best-effort */ });
}
this.adapters.set(adapter.name, adapter as AnyAdapter);
}
has(name: string): boolean { return this.adapters.has(name); }
get(name: string): AnyAdapter | null {
return this.adapters.get(name) ?? null;
}
list(): AnyAdapter[] { return [...this.adapters.values()]; }
hasActiveAdapters(): boolean {
for (const a of this.adapters.values()) if (a.isActive) return true;
return false;
}
async openAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.open();
} catch (err) {
log.error('adapter [%s] open failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
}
async closeAll(): Promise<void> {
const tasks = this.list().map(async (a) => {
try {
await a.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', a.name, errMessage(err));
}
});
await Promise.all(tasks);
this.adapters.clear();
}
async closeOne(name: string): Promise<void> {
const adapter = this.adapters.get(name);
if (!adapter) return;
this.adapters.delete(name);
try {
await adapter.close();
} catch (err) {
log.warn('adapter [%s] close failed: %s', adapter.name, errMessage(err));
}
}
/**
* Dispatch one canonical OneBot event to every active adapter in parallel.
* The dispatch payload is built once so each adapter pays only the cost
* of picking the right pre-serialized variant.
*
* Errors thrown inside an adapter are isolated — one bad adapter never
* blocks the others.
*/
async emitEvent(event: JsonObject): Promise<void> {
if (!this.hasActiveAdapters()) return;
const payload = buildDispatchPayload(event);
const tasks: Promise<unknown>[] = [];
for (const adapter of this.adapters.values()) {
if (!adapter.isActive) continue;
tasks.push(
Promise.resolve()
.then(() => adapter.onEvent(event, payload))
.catch((err) => {
log.warn('adapter [%s] onEvent error: %s', adapter.name, errMessage(err));
}),
);
}
await Promise.allSettled(tasks);
}
}
function errMessage(err: unknown): string {
return err instanceof Error ? err.message : String(err);
}
@@ -0,0 +1,82 @@
import type { ApiHandler } from '../api-handler';
import type { JsonObject, JsonValue } from '../types';
export async function executeQuickOperation(
event: JsonObject,
operation: Record<string, unknown>,
api: ApiHandler,
): Promise<void> {
const postType = event.post_type as string;
if (postType === 'message') {
if (operation.reply !== undefined && operation.reply !== null && operation.reply !== '') {
const messageType = event.message_type as string;
const autoEscape = !!operation.auto_escape;
if (messageType === 'group') {
const params: JsonObject = {
group_id: event.group_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
};
if (operation.at_sender !== false && event.user_id) {
const atSegment = { type: 'at', data: { qq: String(event.user_id) } };
if (typeof operation.reply === 'string') {
params.message = [atSegment, { type: 'text', data: { text: operation.reply as string } }] as JsonValue;
params.auto_escape = false;
} else if (Array.isArray(operation.reply)) {
params.message = [atSegment, ...(operation.reply as unknown[])] as JsonValue;
}
}
await api.handle('send_group_msg', params);
} else if (messageType === 'private') {
await api.handle('send_private_msg', {
user_id: event.user_id as number,
message: operation.reply as JsonValue,
auto_escape: autoEscape,
});
}
}
if (operation.delete) {
await api.handle('delete_msg', { message_id: event.message_id as number });
}
if (operation.ban && event.message_type === 'group') {
const duration = typeof operation.ban_duration === 'number' ? operation.ban_duration : 1800;
await api.handle('set_group_ban', {
group_id: event.group_id as number,
user_id: event.user_id as number,
duration: duration as JsonValue,
});
}
if (operation.kick && event.message_type === 'group') {
await api.handle('set_group_kick', {
group_id: event.group_id as number,
user_id: event.user_id as number,
reject_add_request: !!operation.reject_add_request,
});
}
}
if (postType === 'request') {
if (operation.approve !== undefined) {
const requestType = event.request_type as string;
if (requestType === 'friend') {
await api.handle('set_friend_add_request', {
flag: event.flag as string,
approve: operation.approve as JsonValue,
remark: (operation.remark ?? '') as JsonValue,
});
} else if (requestType === 'group') {
await api.handle('set_group_add_request', {
flag: event.flag as string,
sub_type: event.sub_type as string,
approve: operation.approve as JsonValue,
reason: (operation.reason ?? '') as JsonValue,
});
}
}
}
}
+56
View File
@@ -0,0 +1,56 @@
import type { WebSocket } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
/** Validate a request's bearer token / `?access_token=` query against the configured token. */
export function isAuthorized(request: IncomingMessage, token: string): boolean {
if (!token) return true;
const auth = request.headers.authorization ?? '';
if (auth === `Bearer ${token}`) return true;
try {
const url = new URL(request.url ?? '/', 'http://127.0.0.1');
if (url.searchParams.get('access_token') === token) return true;
} catch { /* ignore malformed URLs */ }
return false;
}
/** Convert anything ws can hand us into a UTF-8 string. */
export function rawDataToString(raw: Buffer | string | ArrayBuffer | ArrayBufferView | Buffer[]): string {
if (typeof raw === 'string') return raw;
if (Buffer.isBuffer(raw)) return raw.toString('utf8');
if (Array.isArray(raw)) return Buffer.concat(raw).toString('utf8');
if (raw instanceof ArrayBuffer) return Buffer.from(new Uint8Array(raw)).toString('utf8');
if (ArrayBuffer.isView(raw)) {
return Buffer.from(raw.buffer, raw.byteOffset, raw.byteLength).toString('utf8');
}
return '';
}
/** Best-effort send: drops payload if the socket isn't OPEN, reports send errors. */
export function safeSend(socket: WebSocket, payload: string, onError?: (err: Error) => void): void {
if (socket.readyState !== 1 /* WebSocket.OPEN */) return;
socket.send(payload, (error?: Error | null) => {
if (error && onError) onError(error);
});
}
/** Best-effort close, treats already-closed sockets as a no-op. */
export function safeClose(socket: WebSocket, code = 1000, reason = 'normal'): void {
if (socket.readyState === 3 /* CLOSED */ || socket.readyState === 2 /* CLOSING */) return;
socket.close(code, reason);
}
/** Normalize an HTTP/WS path to a comparable form (strip trailing slash, default to "/"). */
export function normalizePath(pathValue: string | undefined): string {
const path = (pathValue ?? '/').trim() || '/';
if (path === '/') return '/';
return path.endsWith('/') ? path.slice(0, -1) : path;
}
/** Parse the `pathname` from a (potentially relative) WebSocket request URL. */
export function parseRequestPath(urlValue: string): string {
try {
return new URL(urlValue, 'ws://127.0.0.1').pathname;
} catch {
return '/';
}
}
@@ -0,0 +1,176 @@
import { WebSocket } from '@snowluma/websocket';
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsClientNetwork, WsRole } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Client');
const DEFAULT_RECONNECT_INTERVAL_MS = 5000;
export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
private socket: WebSocket | null = null;
private reconnectTimer: NodeJS.Timeout | null = null;
private options: EventReportOptions;
private role: WsRole;
private explicitlyClosed = false;
private readonly log: Logger;
constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.role = config.role ?? 'Universal';
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
if (!this.config.url) return;
this.explicitlyClosed = false;
this.isEnabled = true;
this.connect();
}
close(): void {
this.explicitlyClosed = true;
this.isEnabled = false;
this.cancelReconnect();
if (this.socket) {
safeClose(this.socket);
this.socket = null;
}
}
async reload(next: WsClientNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false && !!next.url;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
this.role = next.role ?? 'Universal';
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || !this.socket) return;
if (this.role !== 'Event' && this.role !== 'Universal') return;
const json = pickDispatchJson(payload, this.options);
if (json === null) return;
safeSend(this.socket, json);
}
private connect(): void {
if (this.explicitlyClosed) return;
if (!this.config.url) return;
if (this.socket) return;
const headers: Record<string, string> = {
'User-Agent': 'OneBot/11',
'X-Self-ID': this.ctx.uin,
'X-Client-Role': this.role,
};
if (this.config.accessToken) {
headers.Authorization = `Bearer ${this.config.accessToken}`;
}
const socket = new WebSocket(this.config.url, { headers });
this.socket = socket;
socket.on('open', () => {
this.log.info('[%s] connected %s', this.name, this.config.url);
this.sendBootstrapMetaEvents(socket);
});
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, raw).catch((err) => {
this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err));
});
});
socket.on('close', () => {
this.socket = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.scheduleReconnect();
});
socket.on('error', (err: Error) => {
this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err));
});
}
private scheduleReconnect(): void {
if (this.reconnectTimer) return;
if (this.explicitlyClosed) return;
const interval = Math.max(1000, this.config.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS);
const timer = setTimeout(() => {
this.reconnectTimer = null;
if (this.explicitlyClosed || !this.isEnabled) return;
this.connect();
}, interval);
timer.unref?.();
this.reconnectTimer = timer;
}
private cancelReconnect(): void {
if (!this.reconnectTimer) return;
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
private async handleApiMessage(socket: WebSocket, raw: Buffer | string): Promise<void> {
if (this.role !== 'Api' && this.role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
if (this.role !== 'Event' && this.role !== 'Universal') return;
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function bindingSignature(net: WsClientNetwork): string {
return `${net.url}#${net.role ?? 'Universal'}#${Math.max(1000, net.reconnectIntervalMs ?? DEFAULT_RECONNECT_INTERVAL_MS)}#${net.accessToken ?? ''}`;
}
@@ -0,0 +1,184 @@
import { WebSocket, WebSocketServer } from '@snowluma/websocket';
import type { IncomingMessage } from 'http';
import { createLogger, type Logger } from '@snowluma/common/logger';
import {
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
type DispatchPayload,
type EventReportOptions,
} from '../event-filter';
import type { JsonObject, WsRole, WsServerNetwork } from '../types';
import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter';
import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils';
const moduleLog = createLogger('OneBot.WS-Server');
interface ForwardConn {
socket: WebSocket;
role: WsRole;
options: EventReportOptions;
}
export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
return this.isEnabled;
}
open(): void {
if (this.isEnabled) return;
if (this.config.enabled === false) return;
this.startServer();
this.isEnabled = true;
}
close(): void {
if (!this.isEnabled && this.connections.size === 0 && !this.wss) return;
// Final lifecycle broadcast before tearing down so attached event clients
// see the disable transition.
const lifecycle = this.ctx.buildLifecycleEvent('disable');
for (const conn of this.connections.values()) {
if (conn.role === 'Api') continue;
const shaped = shapeEventForAdapter(lifecycle, conn.options);
if (!shaped) continue;
safeSend(conn.socket, JSON.stringify(shaped));
}
this.isEnabled = false;
for (const ws of [...this.connections.keys()]) safeClose(ws);
this.connections.clear();
this.wss?.close();
this.wss = null;
}
async reload(next: WsServerNetwork): Promise<NetworkReloadType> {
const prevSig = bindingSignature(this.config);
const wasEnabled = this.isEnabled;
const willEnable = next.enabled !== false;
this.config = structuredClone(next);
this.options = resolveReportOptions(next);
for (const conn of this.connections.values()) conn.options = this.options;
const sigChanged = prevSig !== bindingSignature(next);
if (sigChanged && wasEnabled) {
this.close();
if (willEnable) {
this.open();
return NetworkReloadType.Reopened;
}
return NetworkReloadType.Closed;
}
if (!wasEnabled && willEnable) {
this.open();
return NetworkReloadType.Opened;
}
if (wasEnabled && !willEnable) {
this.close();
return NetworkReloadType.Closed;
}
return NetworkReloadType.Normal;
}
onEvent(_event: JsonObject, payload: DispatchPayload): void {
if (!this.isEnabled || this.connections.size === 0) return;
for (const conn of this.connections.values()) {
if (conn.role !== 'Event' && conn.role !== 'Universal') continue;
const json = pickDispatchJson(payload, conn.options);
if (json === null) continue;
safeSend(conn.socket, json);
}
}
private startServer(): void {
const wss = new WebSocketServer({
host: this.config.host ?? '0.0.0.0',
port: this.config.port,
path: this.config.path ?? '/',
});
this.wss = wss;
wss.on('listening', () => {
this.log.success(
'[%s] listening %s:%d%s',
this.name,
this.config.host ?? '0.0.0.0',
this.config.port,
this.config.path ?? '/',
);
});
wss.on('error', (err: Error) => {
this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err));
});
wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request));
}
private onConnection(socket: WebSocket, request: IncomingMessage): void {
if (!isAuthorized(request, this.config.accessToken ?? '')) {
safeClose(socket, 1008, 'invalid access token');
return;
}
const role = this.config.role ?? classifyForwardRole(request);
const conn: ForwardConn = { socket, role, options: this.options };
this.connections.set(socket, conn);
socket.on('message', (raw: Buffer) => {
void this.handleApiMessage(socket, role, raw);
});
socket.on('close', () => this.connections.delete(socket));
socket.on('error', (err: Error) => {
this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err));
});
if (role === 'Event' || role === 'Universal') {
this.sendBootstrapMetaEvents(socket);
}
}
private async handleApiMessage(socket: WebSocket, role: WsRole, raw: Buffer | string): Promise<void> {
if (role !== 'Api' && role !== 'Universal') return;
const text = rawDataToString(raw);
if (!text) return;
const response = await this.ctx.api.processRequest(text);
safeSend(socket, response);
}
private sendBootstrapMetaEvents(socket: WebSocket): void {
const events = [
this.ctx.buildLifecycleEvent('connect'),
this.ctx.buildLifecycleEvent('enable'),
this.ctx.buildHeartbeatEvent(),
];
for (const event of events) {
const shaped = shapeEventForAdapter(event, this.options);
if (!shaped) continue;
safeSend(socket, JSON.stringify(shaped));
}
}
}
function classifyForwardRole(request: IncomingMessage): WsRole {
const path = parseRequestPath(request.url ?? '/');
if (path.endsWith('/api')) return 'Api';
if (path.endsWith('/event')) return 'Event';
return 'Universal';
}
function bindingSignature(net: WsServerNetwork): string {
return `${net.host ?? '0.0.0.0'}:${net.port}${normalizePath(net.path)}#${net.role ?? 'auto'}#${net.accessToken ?? ''}`;
}
+121
View File
@@ -0,0 +1,121 @@
// Plain JSON types now live in @snowluma/common/json so @snowluma/bridge
// (event-format / receive parsers) can talk about JSON payloads without
// importing OneBot. Re-exported here so the legacy import shape stays
// supported — `import { JsonValue } from '<…>/onebot/types'` keeps working.
export type { JsonPrimitive, JsonValue, JsonObject, JsonArray } from '@snowluma/common/json';
import type { JsonValue, JsonObject } from '@snowluma/common/json';
export interface ApiResponse {
status: 'ok' | 'failed';
retcode: number;
data: JsonValue;
echo?: JsonValue;
wording?: string;
}
export interface OneBotRequest {
action: string;
params?: JsonObject;
echo?: JsonValue;
}
export type WsRole = 'Api' | 'Event' | 'Universal';
export type MessageFormat = 'array' | 'string';
export type NetworkKind = 'httpServers' | 'httpClients' | 'wsServers' | 'wsClients';
/**
* Fields shared by every network adapter. `messageFormat` and
* `reportSelfMessage` live on the adapter itself — there is no global default
* fallback; each adapter is fully self-describing.
*
* The `name` is a free-form identifier scoped to the adapter's array; it is
* used for hot-reload bookkeeping and as a label in logs / WebUI.
*/
export interface NetworkBase {
name: string;
/** When `false`, the adapter is configured but inactive. Defaults to `true`. */
enabled?: boolean;
accessToken?: string;
/** Output format for this adapter. */
messageFormat: MessageFormat;
/** When `true`, this adapter receives `post_type='message_sent'` self events. */
reportSelfMessage: boolean;
}
export interface HttpServerNetwork extends NetworkBase {
host?: string;
port: number;
path?: string;
}
export interface HttpClientNetwork extends NetworkBase {
url: string;
timeoutMs?: number;
}
export interface WsServerNetwork extends NetworkBase {
host?: string;
port: number;
path?: string;
role?: WsRole;
}
export interface WsClientNetwork extends NetworkBase {
url: string;
role?: WsRole;
reconnectIntervalMs?: number;
}
/**
* Network adapters grouped by type. Each adapter is identified by `name`
* within its own array; hot-reload works on a per-(kind, name) basis.
*/
export interface OneBotNetworks {
httpServers: HttpServerNetwork[];
httpClients: HttpClientNetwork[];
wsServers: WsServerNetwork[];
wsClients: WsClientNetwork[];
}
/** Per-UIN OneBot configuration. */
export interface OneBotConfig {
networks: OneBotNetworks;
/** Music card signing service URL (optional). */
musicSignUrl?: string;
}
export interface MessageMeta {
isGroup: boolean;
targetId: number;
sequence: number;
eventName: string;
clientSequence: number;
random: number;
timestamp: number;
}
export const RETCODE = {
ACTION_FAILED: 100,
INTERNAL_ERROR: 1200,
BAD_REQUEST: 1400,
UNKNOWN_ACTION: 1404,
} as const;
export function okResponse(data: JsonValue = null): ApiResponse {
return {
status: 'ok',
retcode: 0,
data,
};
}
export function failedResponse(retcode: number, wording: string): ApiResponse {
return {
status: 'failed',
retcode,
data: null,
wording,
};
}
@@ -0,0 +1,130 @@
// Tests for ApiHandler's central dispatch logging.
// Verifies that every action call emits a debug entry line, failures
// fold into a warn line with stack, and unknown actions are surfaced.
// Also covers the summarizeParams helper used to keep the entry log
// from blowing the line width.
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { ApiHandler } from '../src/api-handler';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
import { summarizeParams } from '@snowluma/common/log-summary';
// Minimal context — we never reach the real action handlers; we
// register our own via registerAction.
function emptyContext(): any {
return {
bridge: {},
getLoginInfo: () => ({ userId: 0, nickname: '' }),
isOnline: () => true,
getMessage: () => null,
getMessageMeta: () => null,
sendPrivateMessage: async () => ({ messageId: 0 }),
sendGroupMessage: async () => ({ messageId: 0 }),
deleteMessage: async () => {},
canSendImage: () => true,
canSendRecord: () => true,
getFriendList: async () => [],
getImageInfo: async () => null,
getRecordInfo: async () => null,
};
}
let captured: LogEntry[];
let unsub: () => void;
const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL;
beforeEach(() => {
process.env.SNOWLUMA_LOG_LEVEL = 'debug';
captured = [];
unsub = subscribeLogs((e) => captured.push(e));
});
afterEach(() => {
unsub();
if (savedLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
else process.env.SNOWLUMA_LOG_LEVEL = savedLogLevel;
});
describe('summarizeParams', () => {
it('renders flat scalar fields as k=v pairs', () => {
const out = summarizeParams({ group_id: 12345, auto_escape: false, foo: 'bar' });
expect(out).toBe('group_id=12345 auto_escape=false foo="bar"');
});
it('truncates long string values with an ellipsis', () => {
const long = 'x'.repeat(80);
const out = summarizeParams({ s: long });
expect(out).toMatch(/^s="x{40}\.\.\."$/);
});
it('collapses arrays and nested objects rather than dumping them', () => {
const out = summarizeParams({ messages: [1, 2, 3, 4], meta: { a: 1, b: 2 } });
expect(out).toBe('messages=[len=4] meta={...}');
});
it('caps the total line and tags the cut with ellipsis', () => {
const params: Record<string, number> = {};
for (let i = 0; i < 30; i++) params[`field_with_some_padding_${i}`] = i;
const out = summarizeParams(params);
expect(out.length).toBeLessThan(220);
expect(out.endsWith('...')).toBe(true);
});
it('handles null / undefined inputs gracefully', () => {
expect(summarizeParams(null)).toBe('{}');
expect(summarizeParams(undefined)).toBe('{}');
});
});
describe('ApiHandler dispatch logging', () => {
it('emits a debug entry under [Bridge.Action] when an action is called', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null }));
await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] });
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry).toBeDefined();
expect(entry!.uin).toBe(12345);
expect(entry!.message).toContain('echo');
expect(entry!.message).toContain('group_id=67890');
expect(entry!.message).toContain('message=[len=3]');
});
it('emits a warn line with the error stack when the handler throws', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('boom', async () => {
throw new Error('kapow');
});
const result = await handler.handle('boom', {});
expect(result.status).toBe('failed');
const warn = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'warn');
expect(warn).toBeDefined();
expect(warn!.message).toContain('boom');
expect(warn!.message).toContain('kapow');
// stack contains the test file path; just check that something stack-shaped is appended
expect(warn!.message).toMatch(/at\s+/);
});
it('logs unknown actions at debug level', async () => {
const handler = new ApiHandler(emptyContext(), 99);
await handler.handle('not_a_real_action', {});
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action'));
expect(entry).toBeDefined();
expect(entry!.level).toBe('debug');
});
it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => {
const handler = new ApiHandler(emptyContext());
handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null }));
await handler.handle('ping', {});
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry).toBeDefined();
expect(entry!.uin).toBeUndefined();
});
});
+203
View File
@@ -0,0 +1,203 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import os from 'os';
import path from 'path';
import { loadOneBotConfig, makeDefaultOneBotConfig, saveOneBotConfig } from '../src/config';
const TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
describe('makeDefaultOneBotConfig', () => {
it('returns default unified networks structure', () => {
const config = makeDefaultOneBotConfig();
expect(config.networks.httpServers).toHaveLength(1);
expect(config.networks.httpServers[0].name).toBe('http-default');
expect(config.networks.httpServers[0].host).toBe('0.0.0.0');
expect(config.networks.httpServers[0].port).toBe(3000);
expect(config.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
expect(config.networks.httpServers[0].messageFormat).toBe('array');
expect(config.networks.httpServers[0].reportSelfMessage).toBe(false);
expect(config.networks.httpClients).toEqual([]);
expect(config.networks.wsServers).toHaveLength(1);
expect(config.networks.wsServers[0].port).toBe(3001);
expect(config.networks.wsServers[0].role).toBe('Universal');
expect(config.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
expect(config.networks.wsServers[0].messageFormat).toBe('array');
expect(config.networks.wsServers[0].reportSelfMessage).toBe(false);
expect(config.networks.wsClients).toEqual([]);
expect(config.musicSignUrl).toBe('');
});
});
describe('loadOneBotConfig', () => {
let tempDir: string;
let prevCwd: string;
beforeEach(() => {
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-onebot-config-'));
prevCwd = process.cwd();
process.chdir(tempDir);
});
afterEach(() => {
process.chdir(prevCwd);
fs.rmSync(tempDir, { recursive: true, force: true });
});
it('creates and persists default config when none exists', () => {
const uin = '10001';
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toHaveLength(1);
const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8'));
expect(onDisk.networks).toBeDefined();
expect(Array.isArray(onDisk.networks.httpServers)).toBe(true);
expect(onDisk.networks.httpServers[0].name).toBe('http-default');
expect(onDisk.networks.httpServers[0].accessToken).toMatch(TOKEN_PATTERN);
expect(onDisk.networks.wsServers[0].accessToken).toMatch(TOKEN_PATTERN);
// Legacy keys must not appear in the persisted file.
expect(onDisk.httpServers).toBeUndefined();
expect(onDisk.wsServers).toBeUndefined();
});
it('migrates legacy per-type arrays into networks groups', () => {
const uin = '10002';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
const legacy = {
httpServers: [{ host: '0.0.0.0', port: 3100, path: '/', accessToken: 'tok' }],
httpPostEndpoints: [{ name: 'main-bot', url: 'http://127.0.0.1:5700' }],
wsServers: [{ host: '0.0.0.0', port: 3101 }],
wsClients: [{ url: 'ws://127.0.0.1:8080' }],
musicSignUrl: 'https://example.com/sign',
messageFormat: 'string',
reportSelfMessage: true,
};
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8');
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toHaveLength(1);
expect(config.networks.httpServers[0].port).toBe(3100);
expect(config.networks.httpServers[0].accessToken).toBe('tok');
expect(config.networks.httpServers[0].messageFormat).toBe('string');
expect(config.networks.httpServers[0].reportSelfMessage).toBe(true);
expect(config.networks.httpClients).toHaveLength(1);
expect(config.networks.httpClients[0].name).toBe('main-bot');
expect(config.networks.httpClients[0].url).toBe('http://127.0.0.1:5700');
expect(config.networks.httpClients[0].messageFormat).toBe('string');
expect(config.networks.httpClients[0].reportSelfMessage).toBe(true);
expect(config.networks.wsServers).toHaveLength(1);
expect(config.networks.wsServers[0].port).toBe(3101);
expect(config.networks.wsServers[0].messageFormat).toBe('string');
expect(config.networks.wsServers[0].reportSelfMessage).toBe(true);
expect(config.networks.wsClients).toHaveLength(1);
expect(config.networks.wsClients[0].url).toBe('ws://127.0.0.1:8080');
expect(config.networks.wsClients[0].messageFormat).toBe('string');
expect(config.networks.wsClients[0].reportSelfMessage).toBe(true);
expect(config.musicSignUrl).toBe('https://example.com/sign');
// File should now be in unified format on disk.
const onDisk = JSON.parse(fs.readFileSync(path.join(dir, `onebot_${uin}.json`), 'utf8'));
expect(onDisk.networks).toBeDefined();
expect(onDisk.httpServers).toBeUndefined();
expect(onDisk.httpPostEndpoints).toBeUndefined();
expect(onDisk.messageFormat).toBeUndefined();
expect(onDisk.reportSelfMessage).toBeUndefined();
expect(onDisk.networks.httpServers[0].messageFormat).toBe('string');
expect(onDisk.networks.httpServers[0].reportSelfMessage).toBe(true);
});
it('round-trips per-adapter overrides through save/load', () => {
const uin = '10003';
const config = makeDefaultOneBotConfig();
config.networks.httpClients.push({
name: 'self-mirror',
url: 'http://127.0.0.1:9000',
messageFormat: 'string',
reportSelfMessage: true,
});
saveOneBotConfig(uin, config);
const reloaded = loadOneBotConfig(uin);
expect(reloaded.networks.httpClients).toHaveLength(1);
expect(reloaded.networks.httpClients[0].name).toBe('self-mirror');
expect(reloaded.networks.httpClients[0].messageFormat).toBe('string');
expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true);
});
it('does not write to disk by default (read-only contract)', () => {
const uin = '10006';
const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`);
// Default call must not materialize the file or mint a fresh access token.
const config = loadOneBotConfig(uin);
expect(config.networks.httpServers).toHaveLength(1);
expect(fs.existsSync(cfgPath)).toBe(false);
// Explicit opt-in still writes.
loadOneBotConfig(uin, { persistDefaults: true });
expect(fs.existsSync(cfgPath)).toBe(true);
});
it('respects an operator-emptied adapter list instead of seeding defaults back', () => {
const uin = '10007';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] },
musicSignUrl: '',
}), 'utf8');
const config = loadOneBotConfig(uin, { persistDefaults: true });
expect(config.networks.httpServers).toEqual([]);
expect(config.networks.wsServers).toEqual([]);
});
it('migrates legacy lowercase WsRole values into canonical uppercase form', () => {
const uin = '10005';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
networks: {
httpServers: [],
httpClients: [],
wsServers: [
{ name: 'ws-legacy', host: '0.0.0.0', port: 3201, path: '/', role: 'universal', messageFormat: 'array', reportSelfMessage: false },
],
wsClients: [
{ name: 'wsc-legacy', url: 'ws://127.0.0.1:8080', role: 'event', messageFormat: 'array', reportSelfMessage: false },
],
},
}), 'utf8');
const config = loadOneBotConfig(uin);
expect(config.networks.wsServers).toHaveLength(1);
expect(config.networks.wsServers[0].role).toBe('Universal');
expect(config.networks.wsClients).toHaveLength(1);
expect(config.networks.wsClients[0].role).toBe('Event');
});
it('auto-generates names for legacy entries that lack one', () => {
const uin = '10004';
const dir = path.join(tempDir, 'config');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({
httpServers: [
{ port: 3000 },
{ port: 3001 },
],
}), 'utf8');
const config = loadOneBotConfig(uin);
const names = config.networks.httpServers.map((n) => n.name);
expect(names).toHaveLength(2);
expect(new Set(names).size).toBe(2); // unique
expect(names.every((n) => n.length > 0)).toBe(true);
expect(config.networks.httpServers.every((n) => n.messageFormat === 'array')).toBe(true);
expect(config.networks.httpServers.every((n) => n.reportSelfMessage === false)).toBe(true);
});
});
@@ -0,0 +1,316 @@
// First real OneBot unit test that exercises a module purely through
// BridgeInterface — no concrete Bridge, no SQLite, no native packet
// sender, no BridgeManager. This is the testability win that PR4 + PR5
// were supposed to unlock; the file exists to prove it.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type {
FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo,
} from '@snowluma/bridge/qq-info';
import {
getFriendList,
getGroupInfo,
getGroupList,
getGroupMemberInfo,
getGroupMemberList,
getLoginInfo,
getStrangerInfo,
} from '../src/modules/contact-actions';
import type { OneBotInstanceContext } from '../src/instance-context';
/**
* A typed BridgeInterface where every property is undefined by default;
* accessing an un-stubbed property throws with a clear message so tests
* fail loudly if they exercise a code path the fake hasn't been told
* about. Tests just spread the methods they care about.
*/
// `apisAutoPromote` lets tests written before #6 (which stubbed flat
// methods like `fetchFriendList: vi.fn()` on bridge directly) keep
// working without restructuring — the helper rewrites flat stubs into
// the new `apis.<area>.method` shape automatically. New code can also
// pass `apis: { contacts: { … } }` explicitly; the two merge.
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const area = APIS_ROUTING[k];
if (area) {
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][k] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
/** Same Proxy trick for the IdentityService surface that contact-actions touches. */
function fakeIdentity(overrides: Record<string, unknown> = {}): BridgeInterface['identity'] {
return new Proxy(overrides as any, {
get(target, prop) {
if (prop in target) return target[prop];
throw new Error(`fakeIdentity: '${String(prop)}' was not stubbed for this test`);
},
});
}
// ─── Fixture builders ───
function makeFriend(uin: number, nickname: string, remark = ''): FriendInfo {
return { uin, uid: `u_${uin}`, nickname, remark };
}
function makeGroup(groupId: number, groupName: string, members: GroupMemberInfo[] = []): QQGroupInfo {
return {
groupId, groupName, remark: '',
memberCount: members.length, memberMax: 500,
members: new Map(members.map((m) => [m.uin, m])),
};
}
function makeMember(uin: number, nickname: string, card = ''): GroupMemberInfo {
return {
uin, uid: `u_${uin}`, nickname, card,
role: 'member', level: 1, title: '',
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
};
}
function makeProfile(uin: number, nickname: string, sex: 'male' | 'female' | 'unknown' = 'unknown', age = 0): UserProfileInfo {
return {
uin, uid: `u_${uin}`, nickname, remark: '', qid: '', sex, age, sign: '', avatar: '',
};
}
// ─── Tests ───
describe('onebot/contact-actions / getLoginInfo', () => {
it('returns user_id parsed from uin and nickname from identity', () => {
const ref = {
uin: '10001',
bridge: fakeBridge({ identity: fakeIdentity({ nickname: 'self-nick' }) }),
} as unknown as OneBotInstanceContext;
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: 'self-nick' });
});
it('falls back to the uin string when identity nickname is empty', () => {
const ref = {
uin: '10001',
bridge: fakeBridge({ identity: fakeIdentity({ nickname: '' }) }),
} as unknown as OneBotInstanceContext;
expect(getLoginInfo(ref)).toEqual({ userId: 10001, nickname: '10001' });
});
});
describe('onebot/contact-actions / getFriendList', () => {
it('returns the fetched list mapped to OneBot shape', async () => {
const bridge = fakeBridge({
fetchFriendList: vi.fn(async () => [makeFriend(22222, 'alice', 'best-friend')]),
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 22222, nickname: 'alice', remark: 'best-friend' }]);
expect(bridge.apis.contacts.fetchFriendList).toHaveBeenCalledOnce();
});
it('falls back to identity.friends on fetch failure', async () => {
const cached = [makeFriend(33333, 'bob')];
const bridge = fakeBridge({
fetchFriendList: vi.fn(async () => { throw new Error('network down'); }),
identity: fakeIdentity({ friends: cached }),
});
const out = await getFriendList(bridge);
expect(out).toEqual([{ user_id: 33333, nickname: 'bob', remark: '' }]);
});
});
describe('onebot/contact-actions / getGroupList', () => {
it('triggers fetch when the in-memory roster is empty', async () => {
const fetched = [makeGroup(100, 'Group A')];
// `groups` starts empty; the fetch callback flips it to mimic
// bridge.apis.contacts.fetchGroupList writing back through identity.rememberGroups.
let groups: QQGroupInfo[] = [];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => { groups = fetched; return fetched; }),
identity: fakeIdentity({
get groups() { return groups; },
}),
});
const out = await getGroupList(bridge);
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
expect(out).toEqual([{
group_id: 100, group_name: 'Group A',
member_count: 0, max_member_count: 500,
}]);
});
it('skips fetch when cache is populated and noCache is omitted', async () => {
const cached = [makeGroup(200, 'Group B')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge);
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
});
it('forces fetch when noCache=true even with a populated cache', async () => {
const cached = [makeGroup(300, 'Group C')];
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => cached),
identity: fakeIdentity({ groups: cached }),
});
await getGroupList(bridge, true);
expect(bridge.apis.contacts.fetchGroupList).toHaveBeenCalledOnce();
});
it('serves the stale cache when the fetch path throws', 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' });
});
});
describe('onebot/contact-actions / getGroupInfo', () => {
it('returns the cached group without refreshing when group is known and noCache is false', async () => {
const cached = makeGroup(500, 'Group E');
const findGroup = vi.fn((groupId: number) => groupId === 500 ? cached : null);
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ findGroup }),
});
const out = await getGroupInfo(bridge, 500);
expect(out).toMatchObject({ group_id: 500, group_name: 'Group E' });
expect(bridge.apis.contacts.fetchGroupList).not.toHaveBeenCalled();
});
it('triggers fetch when the group is unknown to the cache', async () => {
const cached = makeGroup(600, 'Group F');
let known = false;
const findGroup = vi.fn((groupId: number) => (known && groupId === 600) ? cached : null);
const fetchGroupList = vi.fn(async () => { known = true; return [cached]; });
const bridge = fakeBridge({
fetchGroupList,
identity: fakeIdentity({ findGroup }),
});
const out = await getGroupInfo(bridge, 600);
expect(fetchGroupList).toHaveBeenCalledOnce();
expect(out).toMatchObject({ group_id: 600, group_name: 'Group F' });
});
it('returns null when the group remains unknown after fetch', async () => {
const bridge = fakeBridge({
fetchGroupList: vi.fn(async () => []),
identity: fakeIdentity({ findGroup: () => null }),
});
expect(await getGroupInfo(bridge, 700)).toBeNull();
});
});
describe('onebot/contact-actions / getGroupMemberList', () => {
it('returns the fetched roster mapped to OneBot shape', async () => {
const members = [makeMember(11, 'alice', 'A'), makeMember(22, 'bob', 'B')];
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => members),
});
const out = await getGroupMemberList(bridge, 800);
expect(out).toHaveLength(2);
expect(out[0]).toMatchObject({ group_id: 800, user_id: 11, nickname: 'alice', card: 'A' });
});
it('falls back to the cached roster when fetch fails', async () => {
const cached = makeGroup(900, '', [makeMember(33, 'cached')]);
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({
findGroup: (gid: number) => gid === 900 ? cached : null,
}),
});
const out = await getGroupMemberList(bridge, 900);
expect(out).toHaveLength(1);
expect(out[0]).toMatchObject({ user_id: 33, nickname: 'cached' });
});
it('returns [] when no roster is known and fetch fails', async () => {
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({ findGroup: () => null }),
});
expect(await getGroupMemberList(bridge, 999)).toEqual([]);
});
});
describe('onebot/contact-actions / getGroupMemberInfo', () => {
it('returns the cached member when present and noCache is false', async () => {
const member = makeMember(44, 'dave', 'D');
const bridge = fakeBridge({
fetchGroupMemberList: vi.fn(async () => []),
identity: fakeIdentity({
findGroupMember: (gid: number, uin: number) =>
gid === 1000 && uin === 44 ? member : null,
}),
});
const out = await getGroupMemberInfo(bridge, 1000, 44);
expect(out).toMatchObject({ user_id: 44, nickname: 'dave', card: 'D' });
expect(bridge.apis.contacts.fetchGroupMemberList).not.toHaveBeenCalled();
});
it('triggers fetch when member is unknown and re-queries the cache', async () => {
const member = makeMember(55, 'eve');
let known = false;
const findGroupMember = vi.fn((gid: number, uin: number) =>
(known && gid === 1100 && uin === 55) ? member : null,
);
const fetchGroupMemberList = vi.fn(async () => { known = true; return [member]; });
const bridge = fakeBridge({
fetchGroupMemberList,
identity: fakeIdentity({ findGroupMember }),
});
const out = await getGroupMemberInfo(bridge, 1100, 55);
expect(fetchGroupMemberList).toHaveBeenCalledOnce();
expect(out).toMatchObject({ user_id: 55, nickname: 'eve' });
});
});
describe('onebot/contact-actions / getStrangerInfo', () => {
it('returns a fetched profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => makeProfile(55555, 'Eve', 'female', 25)),
});
const out = await getStrangerInfo(bridge, 55555);
expect(out).toMatchObject({ user_id: 55555, nickname: 'Eve', sex: 'female', age: 25 });
});
it('falls back to identity.findUserProfile when fetch fails but the profile is cached', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({
findUserProfile: (uin: number) =>
uin === 66666 ? makeProfile(66666, 'Frank', 'male', 30) : null,
}),
});
const out = await getStrangerInfo(bridge, 66666);
expect(out).toMatchObject({ user_id: 66666, nickname: 'Frank' });
});
it('returns null when neither fetch nor cache produces a profile', async () => {
const bridge = fakeBridge({
fetchUserProfile: vi.fn(async () => { throw new Error('net'); }),
identity: fakeIdentity({ findUserProfile: () => null }),
});
expect(await getStrangerInfo(bridge, 99999)).toBeNull();
});
});
@@ -0,0 +1,627 @@
import { describe, expect, it } from 'vitest';
import {
convertEvent,
elementsToOneBotSegments,
type ConverterContext,
} from '../src/event-converter';
import {
buildDispatchPayload,
pickDispatchJson,
resolveReportOptions,
shapeEventForAdapter,
} from '../src/event-filter';
import type {
FriendMessage,
GroupMessage,
MessageElement,
QQEventVariant,
TempMessage,
} from '@snowluma/bridge/events';
const SELF_ID = 10001;
const PEER_UIN = 22222;
const GROUP_ID = 99999;
/** Minimal ConverterContext with no resolvers (all null). Per-test
* helpers override individual fields when they need a stub. */
function bareCtx(overrides: Partial<ConverterContext> = {}): ConverterContext {
return {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
...overrides,
};
}
function makeFriendMessage(senderUin: number): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin,
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
msgSeq: 1,
msgId: 1,
elements: [{ type: 'text', text: 'hi' }],
};
}
function makeGroupMessage(senderUin: number): GroupMessage {
return {
kind: 'group_message',
time: 1700000000,
selfUin: SELF_ID,
groupId: 99999,
senderUin,
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 1,
msgId: 1,
elements: [{ type: 'text', text: 'hi' }],
};
}
function makeTempMessage(senderUin: number): TempMessage {
return {
kind: 'temp_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin,
groupId: 99999,
senderNick: senderUin === SELF_ID ? 'me' : 'peer',
msgSeq: 1,
elements: [{ type: 'text', text: 'hi' }],
};
}
describe('convertEvent — message kinds', () => {
it('friend_message peer → post_type "message", sub_type "friend"', async () => {
const out = await convertEvent(bareCtx(), makeFriendMessage(PEER_UIN));
expect(out).not.toBeNull();
expect(out!.post_type).toBe('message');
expect(out!.message_type).toBe('private');
expect(out!.sub_type).toBe('friend');
expect(out!.user_id).toBe(PEER_UIN);
expect(out!.self_id).toBe(SELF_ID);
expect(out!.raw_message).toBe('hi');
});
it('friend_message self → post_type "message_sent"', async () => {
const out = await convertEvent(bareCtx(), makeFriendMessage(SELF_ID));
expect(out!.post_type).toBe('message_sent');
});
it('group_message peer → post_type "message", sub_type "normal", group_id set', async () => {
const out = await convertEvent(bareCtx(), makeGroupMessage(PEER_UIN));
expect(out!.post_type).toBe('message');
expect(out!.message_type).toBe('group');
expect(out!.sub_type).toBe('normal');
expect(out!.group_id).toBe(GROUP_ID);
});
it('group_message self → post_type "message_sent"', async () => {
const out = await convertEvent(bareCtx(), makeGroupMessage(SELF_ID));
expect(out!.post_type).toBe('message_sent');
});
it('temp_message peer → post_type "message", sub_type "group"', async () => {
const out = await convertEvent(bareCtx(), makeTempMessage(PEER_UIN));
expect(out!.post_type).toBe('message');
expect(out!.sub_type).toBe('group');
});
it('temp_message self → post_type "message_sent"', async () => {
const out = await convertEvent(bareCtx(), makeTempMessage(SELF_ID));
expect(out!.post_type).toBe('message_sent');
expect(out!.sub_type).toBe('group');
});
it('messageIdResolver overrides the raw msgSeq', async () => {
const ctx = bareCtx({ messageIdResolver: (_g, _s, seq) => seq * 10 });
const out = await convertEvent(ctx, makeFriendMessage(PEER_UIN));
expect(out!.message_id).toBe(10);
});
});
describe('convertEvent — notice kinds', () => {
it('group_member_join: same-actor approve, else invite', async () => {
const approve = await convertEvent(bareCtx(), {
kind: 'group_member_join',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: PEER_UIN,
} as QQEventVariant);
expect(approve!.notice_type).toBe('group_increase');
expect(approve!.sub_type).toBe('approve');
const invite = await convertEvent(bareCtx(), {
kind: 'group_member_join',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333,
} as QQEventVariant);
expect(invite!.sub_type).toBe('invite');
});
it('group_member_leave: leave / kick / kick_me', async () => {
const leave = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 0, isKick: false,
} as QQEventVariant);
expect(leave!.sub_type).toBe('leave');
const kick = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, isKick: true,
} as QQEventVariant);
expect(kick!.sub_type).toBe('kick');
const kickMe = await convertEvent(bareCtx(), {
kind: 'group_member_leave',
time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: SELF_ID, operatorUin: 33333, isKick: true,
} as QQEventVariant);
expect(kickMe!.sub_type).toBe('kick_me');
});
it('group_mute: ban vs lift_ban driven by duration', async () => {
const ban = await convertEvent(bareCtx(), {
kind: 'group_mute', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, duration: 600,
} as QQEventVariant);
expect(ban!.sub_type).toBe('ban');
expect(ban!.duration).toBe(600);
const lift = await convertEvent(bareCtx(), {
kind: 'group_mute', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, operatorUin: 33333, duration: 0,
} as QQEventVariant);
expect(lift!.sub_type).toBe('lift_ban');
});
it('group_admin: set vs unset', async () => {
const set = await convertEvent(bareCtx(), {
kind: 'group_admin', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, set: true,
} as QQEventVariant);
expect(set!.notice_type).toBe('group_admin');
expect(set!.sub_type).toBe('set');
const unset = await convertEvent(bareCtx(), {
kind: 'group_admin', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, set: false,
} as QQEventVariant);
expect(unset!.sub_type).toBe('unset');
});
it('friend_recall: passes through user + sequence-as-message_id', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_recall', time: 1, selfUin: SELF_ID,
userUin: PEER_UIN, msgSeq: 77,
} as QQEventVariant);
expect(out!.notice_type).toBe('friend_recall');
expect(out!.user_id).toBe(PEER_UIN);
expect(out!.message_id).toBe(77);
});
it('group_recall: carries operator, author, message_id', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_recall', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
operatorUin: 33333, authorUin: PEER_UIN, msgSeq: 99,
} as QQEventVariant);
expect(out!.notice_type).toBe('group_recall');
expect(out!.operator_id).toBe(33333);
expect(out!.user_id).toBe(PEER_UIN);
expect(out!.message_id).toBe(99);
});
it('friend_poke: notice/notify/poke with target_id + action fields', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_poke', time: 1, selfUin: SELF_ID,
userUin: PEER_UIN, targetUin: SELF_ID,
action: '戳了戳', suffix: '一下', actionImgUrl: 'http://x',
} as QQEventVariant);
expect(out!.notice_type).toBe('notify');
expect(out!.sub_type).toBe('poke');
expect(out!.target_id).toBe(SELF_ID);
expect(out!.action).toBe('戳了戳');
});
it('group_poke: same shape as friend_poke + group_id', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_poke', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, targetUin: SELF_ID,
action: '戳', suffix: '', actionImgUrl: '',
} as QQEventVariant);
expect(out!.notice_type).toBe('notify');
expect(out!.sub_type).toBe('poke');
expect(out!.group_id).toBe(GROUP_ID);
});
it('group_essence: add vs delete + carries random + sequence', async () => {
const add = await convertEvent(bareCtx(), {
kind: 'group_essence', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
senderUin: PEER_UIN, operatorUin: 33333, msgSeq: 50, random: 123,
set: true,
} as QQEventVariant);
expect(add!.notice_type).toBe('essence');
expect(add!.sub_type).toBe('add');
expect(add!.random).toBe(123);
expect(add!.message_seq).toBe(50);
const del = await convertEvent(bareCtx(), {
kind: 'group_essence', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
senderUin: PEER_UIN, operatorUin: 33333, msgSeq: 50, random: 123,
set: false,
} as QQEventVariant);
expect(del!.sub_type).toBe('delete');
});
it('group_file_upload: emits group_upload with file metadata', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_file_upload', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
userUin: PEER_UIN, fileId: 'f1', fileName: 'doc.txt',
fileSize: 1024, busId: 102,
} as QQEventVariant);
expect(out!.notice_type).toBe('group_upload');
expect((out!.file as Record<string, unknown>).id).toBe('f1');
expect((out!.file as Record<string, unknown>).size).toBe(1024);
});
it('friend_add: emits friend_add notice', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_add', time: 1, selfUin: SELF_ID, userUin: PEER_UIN,
} as QQEventVariant);
expect(out!.notice_type).toBe('friend_add');
expect(out!.user_id).toBe(PEER_UIN);
});
});
describe('convertEvent — request kinds', () => {
it('friend_request: request/friend with comment + flag', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'friend_request', time: 1, selfUin: SELF_ID,
fromUin: PEER_UIN, message: '加个好友', flag: 'flag-abc',
} as QQEventVariant);
expect(out!.post_type).toBe('request');
expect(out!.request_type).toBe('friend');
expect(out!.comment).toBe('加个好友');
expect(out!.flag).toBe('flag-abc');
});
it('group_invite: request/group with sub_type defaulting to "invite"', async () => {
const out = await convertEvent(bareCtx(), {
kind: 'group_invite', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
fromUin: PEER_UIN, message: '邀请', flag: 'gflag', subType: '',
} as QQEventVariant);
expect(out!.post_type).toBe('request');
expect(out!.request_type).toBe('group');
expect(out!.sub_type).toBe('invite');
const withSubType = await convertEvent(bareCtx(), {
kind: 'group_invite', time: 1, selfUin: SELF_ID, groupId: GROUP_ID,
fromUin: PEER_UIN, message: '', flag: 'gflag', subType: 'add',
} as QQEventVariant);
expect(withSubType!.sub_type).toBe('add');
});
});
describe('convertEvent — message elements (13 segment types)', () => {
// Round-trips one element through elementsToOneBotSegments and
// asserts the OneBot segment shape. Resolvers are wired only when
// the element type needs them. JsonArray's index type is JsonValue
// (a union); cast back to the segment shape so test bodies can read
// `.type` and `.data` without typeguarding every line.
type Segment = { type: string; data: Record<string, unknown> };
async function segment(element: MessageElement, opts: Partial<ConverterContext> = {}): Promise<Segment> {
const ctx = bareCtx(opts);
const segments = await elementsToOneBotSegments(
[element], false, PEER_UIN,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
return segments[0] as unknown as Segment;
}
it('text -> { type:"text", data:{ text } }', async () => {
const seg = await segment({ type: 'text', text: 'hello' });
expect(seg).toEqual({ type: 'text', data: { text: 'hello' } });
});
it('face -> { type:"face", data:{ id: stringified } }', async () => {
const seg = await segment({ type: 'face', faceId: 12 });
expect(seg).toEqual({ type: 'face', data: { id: '12' } });
});
it('image: uses imageUrlResolver when wired, falls back to element.imageUrl', async () => {
const seg = await segment(
{ type: 'image', fileId: 'fid', imageUrl: 'http://fallback' },
{ imageUrlResolver: () => 'http://resolved' },
);
expect(seg.type).toBe('image');
expect((seg.data as Record<string, unknown>).url).toBe('http://resolved');
expect((seg.data as Record<string, unknown>).file).toBe('fid');
expect((seg.data as Record<string, unknown>).sub_type).toBe(0);
expect((seg.data as Record<string, unknown>).summary).toBe('');
});
it('image without resolver uses element.imageUrl', async () => {
const seg = await segment({ type: 'image', fileId: 'fid', imageUrl: 'http://x' });
expect((seg.data as Record<string, unknown>).url).toBe('http://x');
});
it('image: forwards optional sub_type and summary for custom emoji/stickers', async () => {
const seg = await segment({
type: 'image',
fileId: 'fid',
imageUrl: 'http://x',
subType: 1,
summary: '[动画表情]',
});
expect(seg).toEqual({
type: 'image',
data: {
url: 'http://x',
file: 'fid',
sub_type: 1,
summary: '[动画表情]',
},
});
});
it('at: targetUin -> qq string', async () => {
const seg = await segment({ type: 'at', targetUin: PEER_UIN });
expect(seg).toEqual({ type: 'at', data: { qq: String(PEER_UIN) } });
});
it('at all: uid="all" -> qq:"all"', async () => {
const seg = await segment({ type: 'at', uid: 'all', targetUin: 0 });
expect((seg.data as Record<string, unknown>).qq).toBe('all');
});
it('reply: replySeq is resolved through messageIdResolver when wired', async () => {
const seg = await segment(
{ type: 'reply', replySeq: 5 },
{ messageIdResolver: () => 9999 },
);
expect(seg).toEqual({ type: 'reply', data: { id: '9999' } });
});
it('reply: replySeq=0 -> id "0", no resolver call', async () => {
let resolverCalls = 0;
const seg = await segment(
{ type: 'reply', replySeq: 0 },
{ messageIdResolver: () => { resolverCalls++; return 1; } },
);
expect((seg.data as Record<string, unknown>).id).toBe('0');
expect(resolverCalls).toBe(0);
});
it('record: uses mediaUrlResolver for url', async () => {
const seg = await segment(
{ type: 'record', fileName: 'a.silk', fileId: 'fid', url: 'fallback' },
{ mediaUrlResolver: async () => 'resolved' },
);
expect(seg.type).toBe('record');
expect((seg.data as Record<string, unknown>).url).toBe('resolved');
expect((seg.data as Record<string, unknown>).file).toBe('a.silk');
});
it('video: same shape as record', async () => {
const seg = await segment(
{ type: 'video', fileName: 'a.mp4', fileId: 'fid', url: 'fallback' },
{ mediaUrlResolver: async () => 'resolved' },
);
expect(seg.type).toBe('video');
expect((seg.data as Record<string, unknown>).url).toBe('resolved');
});
it('json: text is forwarded as data.data', async () => {
const seg = await segment({ type: 'json', text: '{"a":1}' });
expect(seg).toEqual({ type: 'json', data: { data: '{"a":1}' } });
});
it('xml: text + resid (defaults to 35)', async () => {
const seg = await segment({ type: 'xml', text: '<x/>' });
expect((seg.data as Record<string, unknown>).resid).toBe(35);
const seg2 = await segment({ type: 'xml', text: '<x/>', subType: 50 });
expect((seg2.data as Record<string, unknown>).resid).toBe(50);
});
it('file: name + size + id + url + file_hash, url via mediaUrlResolver', async () => {
const seg = await segment(
{ type: 'file', fileName: 'doc.pdf', fileSize: 7, fileId: 'fid', fileHash: 'h' },
{ mediaUrlResolver: async () => 'http://download' },
);
expect(seg.type).toBe('file');
expect(seg.data).toEqual({
name: 'doc.pdf', size: 7, id: 'fid', url: 'http://download', file_hash: 'h',
});
});
it('mface: text + tab_id + sub_type', async () => {
const seg = await segment({ type: 'mface', text: 'sticker', faceId: 7, subType: 2 });
expect(seg).toEqual({ type: 'mface', data: { name: 'sticker', tab_id: 7, sub_type: 2 } });
});
it('poke: subType forwarded as data.type', async () => {
const seg = await segment({ type: 'poke', subType: 3 });
expect(seg).toEqual({ type: 'poke', data: { type: 3 } });
});
it('mediaSegmentSink fires once per image/record/video segment', async () => {
const calls: string[] = [];
const sink = (mediaType: string) => { calls.push(mediaType); };
const ctx = bareCtx({
mediaSegmentSink: sink as ConverterContext['mediaSegmentSink'],
mediaUrlResolver: async () => '',
});
await elementsToOneBotSegments(
[
{ type: 'image', fileId: 'i', imageUrl: '' },
{ type: 'record', fileName: 'r.silk', fileId: 'r' },
{ type: 'video', fileName: 'v.mp4', fileId: 'v' },
{ type: 'text', text: 'not media' },
],
true, GROUP_ID,
ctx.imageUrlResolver, ctx.mediaUrlResolver, ctx.messageIdResolver, ctx.mediaSegmentSink,
);
expect(calls).toEqual(['image', 'record', 'video']);
});
});
describe('shapeEventForAdapter', () => {
const baseEvent = {
time: 1,
self_id: SELF_ID,
post_type: 'message_sent' as const,
message_type: 'private',
sub_type: 'friend',
message_id: 7,
user_id: SELF_ID,
message: [{ type: 'text', data: { text: 'hello' } }],
raw_message: 'hello',
font: 0,
sender: { user_id: SELF_ID, nickname: 'me', sex: 'unknown', age: 0 },
};
it('drops self message_sent when adapter has reportSelfMessage=false', () => {
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
expect(shapeEventForAdapter(baseEvent, opts)).toBeNull();
});
it('keeps self message_sent when adapter has reportSelfMessage=true', () => {
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
const shaped = shapeEventForAdapter(baseEvent, opts);
expect(shaped).not.toBeNull();
expect(shaped!.post_type).toBe('message_sent');
});
it('rewrites message to CQ string when format=string', () => {
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: true });
const shaped = shapeEventForAdapter(baseEvent, opts);
expect(shaped).not.toBeNull();
expect(shaped!.message).toBe('hello');
// raw_message is preserved untouched.
expect(shaped!.raw_message).toBe('hello');
});
it('keeps message as array when format=array (default)', () => {
const opts = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
const shaped = shapeEventForAdapter(baseEvent, opts);
expect(Array.isArray(shaped!.message)).toBe(true);
});
it('defaults partially-deserialized adapters to array format and no self report', () => {
const opts = resolveReportOptions({});
expect(opts.messageFormat).toBe('array');
expect(opts.reportSelfMessage).toBe(false);
});
it('passes through non-message events unchanged', () => {
const noticeEvent = {
time: 1,
self_id: SELF_ID,
post_type: 'notice',
notice_type: 'group_increase',
group_id: 1,
user_id: 2,
};
const opts = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
expect(shapeEventForAdapter(noticeEvent, opts)).toBe(noticeEvent);
});
});
describe('buildDispatchPayload + pickDispatchJson', () => {
const messageEvent = {
time: 1,
self_id: SELF_ID,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 7,
user_id: PEER_UIN,
message: [{ type: 'text', data: { text: 'hello' } }],
raw_message: 'hello',
font: 0,
sender: { user_id: PEER_UIN, nickname: 'peer', sex: 'unknown', age: 0 },
};
const selfMessageEvent = { ...messageEvent, post_type: 'message_sent', user_id: SELF_ID };
const noticeEvent = {
time: 1,
self_id: SELF_ID,
post_type: 'notice',
notice_type: 'group_increase',
group_id: 1,
user_id: 2,
};
it('builds at most two distinct JSON variants for a message event', () => {
const payload = buildDispatchPayload(messageEvent);
expect(payload.isSelfMessage).toBe(false);
const arr = JSON.parse(payload.arrayJson);
const str = JSON.parse(payload.stringJson);
expect(Array.isArray(arr.message)).toBe(true);
expect(typeof str.message).toBe('string');
expect(str.message).toBe('hello');
expect(str.raw_message).toBe('hello');
// every other field should be byte-identical
const { message: _arrMsg, ...arrRest } = arr;
const { message: _strMsg, ...strRest } = str;
expect(arrRest).toEqual(strRest);
});
it('flags self messages and uses identical JSON for non-message events', () => {
const selfPayload = buildDispatchPayload(selfMessageEvent);
expect(selfPayload.isSelfMessage).toBe(true);
const noticePayload = buildDispatchPayload(noticeEvent);
expect(noticePayload.isSelfMessage).toBe(false);
// Non-message events do not need a separate string variant.
expect(noticePayload.arrayJson).toBe(noticePayload.stringJson);
});
it('routes connections to the right pre-serialized variant in O(1)', () => {
const payload = buildDispatchPayload(messageEvent);
const arrayOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
const stringOpt = resolveReportOptions({ messageFormat: 'string', reportSelfMessage: false });
expect(pickDispatchJson(payload, arrayOpt)).toBe(payload.arrayJson);
expect(pickDispatchJson(payload, stringOpt)).toBe(payload.stringJson);
});
it('drops self-message dispatches for adapters that opt out', () => {
const payload = buildDispatchPayload(selfMessageEvent);
const offOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: false });
expect(pickDispatchJson(payload, offOpt)).toBeNull();
const onOpt = resolveReportOptions({ messageFormat: 'array', reportSelfMessage: true });
const json = pickDispatchJson(payload, onOpt);
expect(json).not.toBeNull();
expect(JSON.parse(json!).post_type).toBe('message_sent');
});
it('serializes only twice regardless of fan-out size', () => {
const payload = buildDispatchPayload(messageEvent);
// Mixed fleet of adapters with different formats / self-report options.
const adapters = Array.from({ length: 50 }, (_, i) => i % 2 === 0
? { messageFormat: 'array' as const, reportSelfMessage: false }
: { messageFormat: 'string' as const, reportSelfMessage: true },
);
const seen = new Set(
adapters
.map((opts) => pickDispatchJson(payload, opts))
.filter((j): j is string => j !== null),
);
// No matter the fan-out, only at most the two prebuilt strings appear.
expect(seen.size).toBeLessThanOrEqual(2);
expect(seen.has(payload.arrayJson)).toBe(true);
expect(seen.has(payload.stringJson)).toBe(true);
});
});
@@ -0,0 +1,206 @@
import { describe, expect, it, vi } from 'vitest';
import { BridgeEventBus } from '@snowluma/bridge/event-bus';
// Wrap convertEvent in a vi.fn that delegates to the real impl by
// default, so one test can override it to return null without making
// the others lose the real conversion behavior.
vi.mock('../src/event-converter', async () => {
const actual = await vi.importActual<typeof import('../src/event-converter')>('../src/event-converter');
return { ...actual, convertEvent: vi.fn(actual.convertEvent) };
});
import { convertEvent, type ConverterContext } from '../src/event-converter';
import { registerEventPipeline } from '../src/event-pipeline';
import type { OneBotInstanceContext } from '../src/instance-context';
import type {
FriendMessage,
GroupMessage,
GroupMemberJoin,
TempMessage,
QQEventVariant,
} from '@snowluma/bridge/events';
import type { JsonObject, MessageMeta } from '../src/types';
const SELF_UIN = '10001';
const SELF_ID = 10001;
const PEER_UIN = 22222;
const GROUP_ID = 99999;
interface FakeBridge {
events: BridgeEventBus;
}
function makeFriendMessage(): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
msgSeq: 11,
msgId: 555,
elements: [{ type: 'text', text: 'hi' }],
};
}
function makeGroupMessage(): GroupMessage {
return {
kind: 'group_message',
time: 1700000000,
selfUin: SELF_ID,
groupId: GROUP_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 22,
msgId: 777,
elements: [{ type: 'text', text: 'group' }],
};
}
function makeTempMessage(): TempMessage {
return {
kind: 'temp_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin: PEER_UIN,
groupId: GROUP_ID,
senderNick: 'peer',
msgSeq: 33,
elements: [{ type: 'text', text: 'temp' }],
};
}
function makeMemberJoin(): GroupMemberJoin {
return {
kind: 'group_member_join',
time: 1700000000,
selfUin: SELF_ID,
groupId: GROUP_ID,
userUin: PEER_UIN,
operatorUin: PEER_UIN,
};
}
function makeContext(extra: Partial<OneBotInstanceContext> = {}): {
ctx: OneBotInstanceContext;
bus: BridgeEventBus;
metaCalls: Array<{ id: number; meta: MessageMeta }>;
dispatchCalls: JsonObject[];
} {
const bus = new BridgeEventBus();
const fakeBridge: FakeBridge = { events: bus };
const converterCtx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: null,
};
const metaCalls: Array<{ id: number; meta: MessageMeta }> = [];
const dispatchCalls: JsonObject[] = [];
const ctx: OneBotInstanceContext = {
uin: SELF_UIN,
selfId: SELF_ID,
bridge: fakeBridge as never,
messageStore: {} as never,
mediaStore: {} as never,
converterCtx,
config: { networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] } } as never,
cacheMessageMeta: (id, meta) => { metaCalls.push({ id, meta }); },
dispatchEvent: (event) => { dispatchCalls.push(event); },
...extra,
};
return { ctx, bus, metaCalls, dispatchCalls };
}
describe('registerEventPipeline', () => {
it('caches meta and dispatches a converted event for friend_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
expect(metaCalls).toHaveLength(1);
expect(metaCalls[0].meta.isGroup).toBe(false);
expect(metaCalls[0].meta.targetId).toBe(PEER_UIN);
expect(metaCalls[0].meta.sequence).toBe(11);
expect(metaCalls[0].meta.random).toBe(555);
expect(dispatchCalls).toHaveLength(1);
expect(dispatchCalls[0].post_type).toBe('message');
expect(dispatchCalls[0].message_type).toBe('private');
});
it('caches meta and dispatches for group_message', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeGroupMessage());
expect(metaCalls[0].meta.isGroup).toBe(true);
expect(metaCalls[0].meta.targetId).toBe(GROUP_ID);
expect(dispatchCalls[0].message_type).toBe('group');
});
it('caches meta with random=0 for temp_message and dispatches as private+sub_type=group', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeTempMessage());
expect(metaCalls[0].meta.isGroup).toBe(false);
expect(metaCalls[0].meta.random).toBe(0);
expect(dispatchCalls[0].message_type).toBe('private');
expect(dispatchCalls[0].sub_type).toBe('group');
});
it('dispatches notice events without seeding meta', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeMemberJoin());
expect(metaCalls).toHaveLength(0);
expect(dispatchCalls).toHaveLength(1);
expect(dispatchCalls[0].notice_type).toBe('group_increase');
});
it('returns a disposer that fully unsubscribes', async () => {
const { ctx, bus, metaCalls, dispatchCalls } = makeContext();
const dispose = registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
expect(dispatchCalls).toHaveLength(1);
dispose();
await bus.emit(makeFriendMessage());
// No new calls after dispose.
expect(dispatchCalls).toHaveLength(1);
expect(metaCalls).toHaveLength(1);
});
it('dispatches a separate event for every kind in parallel', async () => {
const { ctx, bus, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
const events: QQEventVariant[] = [makeFriendMessage(), makeGroupMessage(), makeMemberJoin(), makeTempMessage()];
await Promise.all(events.map((e) => bus.emit(e)));
expect(dispatchCalls).toHaveLength(events.length);
});
it('skips dispatch for kinds without a converter mapping (no crash)', async () => {
// Force convertEvent to return null for one call; assert the pipeline
// honours the `if (!converted) return;` guard.
vi.mocked(convertEvent).mockResolvedValueOnce(null);
const { ctx, bus, dispatchCalls } = makeContext();
registerEventPipeline(ctx);
await bus.emit(makeFriendMessage());
expect(dispatchCalls).toHaveLength(0);
});
});
@@ -0,0 +1,586 @@
// End-to-end OneBot action tests for the napcat-parity surface added in
// Tier 1 + Tier 2: send_packet, bot_exit, nc_*, group-todo, AI voice,
// and the rewired ignored-notifies family. We drive everything through
// the public `ApiHandler.handle()` entry point so the wiring (including
// param coercion, retcode shape) is part of what's under test.
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { ApiHandler, type ApiActionContext } from '../src/api-handler';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '@snowluma/bridge/qq-info';
import type { MessageMeta } from '../src/types';
function fakeMeta(overrides: Partial<MessageMeta> = {}): MessageMeta {
return {
isGroup: true,
targetId: 100,
sequence: 555,
eventName: 'group_message',
clientSequence: 0,
random: 0,
timestamp: 0,
...overrides,
};
}
/**
* Build a BridgeInterface stub that throws on any method we haven't
* pre-stubbed for the test. Same pattern as contact-actions.test.ts —
* keeps tests honest about which surface they actually need.
*/
// Maps flat method names → [area, newMethodName] on the ApiHub under
// the #6 refactor. Auto-promotion lets tests written against the
// pre-refactor flat surface (`fetchGroupRequests: vi.fn()`) keep
// working without per-test restructure, even when the new method name
// drops the redundant `Group`/`File` prefix.
const APIS_ROUTING: Record<string, [string, string]> = {
fetchFriendList: ['contacts', 'fetchFriendList'],
fetchGroupList: ['contacts', 'fetchGroupList'],
fetchGroupMemberList: ['contacts', 'fetchGroupMemberList'],
fetchUserProfile: ['contacts', 'fetchUserProfile'],
fetchGroupRequests: ['contacts', 'fetchGroupRequests'],
fetchDownloadRKeys: ['contacts', 'fetchDownloadRKeys'],
// GroupFileApi: methods drop `Group`/`File`/`Folder` suffix where
// the area name already says it.
deleteGroupFileFolder: ['groupFile', 'deleteFolder'],
fetchGroupPttUrlByNode: ['groupFile', 'getPttUrl'],
// InteractionApi: methods drop the redundant `Group` prefix.
sendLike: ['interaction', 'sendLike'],
setGroupReaction: ['interaction', 'setReaction'],
// ProfileApi: a few methods rename (getProfileLike → getLike).
setOnlineStatus: ['profile', 'setOnlineStatus'],
setDiyOnlineStatus: ['profile', 'setDiyOnlineStatus'],
setProfile: ['profile', 'setProfile'],
setSelfLongNick: ['profile', 'setSelfLongNick'],
setInputStatus: ['profile', 'setInputStatus'],
setAvatar: ['profile', 'setAvatar'],
setGroupAvatar: ['profile', 'setGroupAvatar'],
fetchCustomFace: ['profile', 'fetchCustomFace'],
getProfileLike: ['profile', 'getLike'],
getUnidirectionalFriendList: ['profile', 'getUnidirectionalFriendList'],
// FriendApi: handleRequest/delete/setRemark.
setFriendRemark: ['friend', 'setRemark'],
deleteFriend: ['friend', 'delete'],
setFriendAddRequest: ['friend', 'handleRequest'],
// ExtrasApi: group todo / stranger status / AI voice.
setGroupTodo: ['extras', 'setGroupTodo'],
completeGroupTodo: ['extras', 'completeGroupTodo'],
cancelGroupTodo: ['extras', 'cancelGroupTodo'],
getStrangerStatus: ['extras', 'getStrangerStatus'],
fetchAiVoiceList: ['extras', 'fetchAiVoiceList'],
fetchAiVoice: ['extras', 'fetchAiVoice'],
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const route = APIS_ROUTING[k];
if (route) {
const [area, newName] = route;
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][newName] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
},
});
}
/**
* Build the minimum ApiActionContext needed for the tested actions.
* Anything not stubbed throws on access — keeps the dependency surface
* explicit. Only fields the tested actions read are populated.
*/
function fakeCtx(bridge: BridgeInterface, overrides: Partial<ApiActionContext> = {}): ApiActionContext {
const base = {
bridge,
getMessageMeta: () => null,
getMessage: () => null,
getLoginInfo: () => ({ userId: 1, nickname: '' }),
isOnline: () => true,
canSendImage: () => true,
canSendRecord: () => true,
getDownloadRKeys: async () => [],
...overrides,
};
return new Proxy(base as ApiActionContext, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeCtx: '${String(prop)}' was not stubbed`);
},
});
}
function makeHandler(ctx: ApiActionContext): ApiHandler {
return new ApiHandler(ctx);
}
// ─── Tier 1: send_packet / .send_packet ───
describe('extended-actions / send_packet', () => {
it('hex-decodes data, calls Bridge.sendRawPacket, hex-encodes the response', async () => {
const sendRawPacket: BridgeInterface['sendRawPacket'] = vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from([0xDE, 0xAD, 0xBE, 0xEF]),
}));
const bridge = fakeBridge({ sendRawPacket });
const h = makeHandler(fakeCtx(bridge));
const res = await h.handle('send_packet', { cmd: 'Some.Cmd', data: 'cafebabe', rsp: true });
const spy = vi.mocked(sendRawPacket);
expect(spy).toHaveBeenCalledOnce();
const sentBody = spy.mock.calls[0]![1];
expect(Buffer.from(sentBody).toString('hex')).toBe('cafebabe');
expect(res).toMatchObject({ status: 'ok', retcode: 0, data: 'deadbeef' });
});
it('.send_packet shares the same handler', async () => {
const sendRawPacket = vi.fn(async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '', responseData: Buffer.alloc(0),
}));
const h = makeHandler(fakeCtx(fakeBridge({ sendRawPacket: sendRawPacket as any })));
const res = await h.handle('.send_packet', { cmd: 'C', data: '' });
expect(res.status).toBe('ok');
expect(sendRawPacket).toHaveBeenCalledOnce();
});
it('with rsp=false returns null and ignores responseData', async () => {
const bridge = fakeBridge({
sendRawPacket: (async () => ({
success: true, gotResponse: true, errorCode: 0, errorMessage: '',
responseData: Buffer.from('00ff', 'hex'),
})) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '', rsp: false });
expect(res).toMatchObject({ status: 'ok', data: null });
});
it('rejects missing cmd', async () => {
const bridge = fakeBridge({ sendRawPacket: vi.fn() as any });
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: '', data: '' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
it('rejects malformed hex', async () => {
const sendRawPacket = vi.fn();
const bridge = fakeBridge({ sendRawPacket: sendRawPacket as any });
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'ZZZZ' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
expect(sendRawPacket).not.toHaveBeenCalled();
});
it('rejects odd-length hex', async () => {
const bridge = fakeBridge({ sendRawPacket: vi.fn() as any });
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: 'abc' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
it('propagates wire-level failure as action_failed', async () => {
const bridge = fakeBridge({
sendRawPacket: (async () => ({
success: false, gotResponse: false, errorCode: -1, errorMessage: 'no sender', responseData: null,
})) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_packet', { cmd: 'C', data: '' });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'no sender' });
});
});
// ─── Tier 1: bot_exit ───
describe('extended-actions / bot_exit', () => {
let exitSpy: ReturnType<typeof vi.spyOn>;
beforeEach(() => {
vi.useFakeTimers();
exitSpy = vi.spyOn(process, 'exit').mockImplementation(((_code?: number) => undefined) as any);
});
afterEach(() => {
vi.useRealTimers();
exitSpy.mockRestore();
});
it('returns ok immediately, then exits on the deferred timer', async () => {
const h = makeHandler(fakeCtx(fakeBridge()));
const res = await h.handle('bot_exit', {});
expect(res).toMatchObject({ status: 'ok', retcode: 0 });
expect(exitSpy).not.toHaveBeenCalled();
vi.advanceTimersByTime(100);
expect(exitSpy).toHaveBeenCalledWith(0);
});
});
// ─── Tier 1: nc_get_packet_status / nc_get_rkey ───
describe('extended-actions / nc_get_packet_status', () => {
it('reports healthy with no dependency on bridge', async () => {
const h = makeHandler(fakeCtx(fakeBridge()));
const res = await h.handle('nc_get_packet_status', {});
expect(res).toEqual({ status: 'ok', retcode: 0, data: null });
});
});
describe('extended-actions / nc_get_rkey', () => {
it('reuses the same data the get_rkey handler returns', async () => {
const ctx = fakeCtx(fakeBridge(), {
getDownloadRKeys: async () => [{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }],
});
const h = makeHandler(ctx);
const a = await h.handle('get_rkey', {});
const b = await h.handle('nc_get_rkey', {});
expect(b).toEqual(a);
expect(b.data).toEqual([{ rkey: 'abc', type: 1, ttl: 60, create_time: 1 }]);
});
});
// ─── Tier 1: group-request ignored / shut list / ignore-add ───
function fakeFilteredRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 999,
groupName: 'g',
targetUid: 'u_t',
targetUin: 5555,
targetName: 'target',
invitorUid: 'u_i',
invitorUin: 7777,
invitorName: 'inviter',
operatorUid: 'u_o',
operatorUin: 8888,
operatorName: 'op',
sequence: 42,
state: 1,
eventType: 7,
comment: 'pls',
filtered: true,
...overrides,
};
}
describe('extended-actions / get_group_ignored_notifies', () => {
it('maps filtered fetchGroupRequests(true) into the napcat shape', async () => {
const fetchGroupRequests = vi.fn(async (filtered: boolean) =>
filtered ? [fakeFilteredRequest()] : []
);
const bridge = fakeBridge({ fetchGroupRequests: fetchGroupRequests as any });
const h = makeHandler(fakeCtx(bridge));
const res = await h.handle('get_group_ignored_notifies', {});
expect(fetchGroupRequests).toHaveBeenCalledWith(true);
expect(res.status).toBe('ok');
expect(res.data).toEqual([{
group_id: 999,
group_name: 'g',
request_id: 42,
requester_uin: 5555,
requester_nick: 'target',
message: 'pls',
checked: false, // state == 1 → un-checked
actor: 8888,
invitor_uin: 7777,
invitor_nick: 'inviter',
flag: '7:999:u_t:filtered',
}]);
});
it('returns [] when the fetch throws', async () => {
const bridge = fakeBridge({
fetchGroupRequests: (async () => { throw new Error('boom'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignored_notifies', {});
expect(res).toMatchObject({ status: 'ok', data: [] });
});
});
describe('extended-actions / get_group_ignore_add_request', () => {
it('projects the same filtered list into napcat\'s ignore-add-request shape', async () => {
const bridge = fakeBridge({
fetchGroupRequests: (async () => [fakeFilteredRequest({ state: 2 })]) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_group_ignore_add_request', {});
expect(res.status).toBe('ok');
expect(res.data).toEqual([{
request_id: 42,
invitor_uin: 7777,
invitor_nick: 'inviter',
group_id: 999,
message: 'pls',
group_name: 'g',
checked: true, // state == 2 → checked
actor: 8888,
requester_nick: 'target',
}]);
});
});
describe('extended-actions / get_group_shut_list', () => {
it('returns empty list (oidb not yet wrapped)', async () => {
const res = await makeHandler(fakeCtx(fakeBridge())).handle('get_group_shut_list', {});
expect(res).toEqual({ status: 'ok', retcode: 0, data: [] });
});
});
// ─── Tier 1: delete_group_folder alias ───
describe('extended-actions / delete_group_folder', () => {
it('forwards to bridge.deleteGroupFileFolder', async () => {
const deleteGroupFileFolder = vi.fn(async () => {});
const bridge = fakeBridge({ deleteGroupFileFolder: deleteGroupFileFolder as any });
const res = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', {
group_id: 100, folder_id: 'fid-1',
});
expect(deleteGroupFileFolder).toHaveBeenCalledWith(100, 'fid-1');
expect(res.status).toBe('ok');
});
it('rejects missing fields', async () => {
const bridge = fakeBridge({ deleteGroupFileFolder: vi.fn() as any });
const r1 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { folder_id: 'x' });
const r2 = await makeHandler(fakeCtx(bridge)).handle('delete_group_folder', { group_id: 1 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
// ─── Tier 2: group todo ───
describe('extended-actions / set_/complete_/cancel_group_todo', () => {
it.each([
['set_group_todo', 'setGroupTodo'],
['complete_group_todo', 'completeGroupTodo'],
['cancel_group_todo', 'cancelGroupTodo'],
] as const)('%s resolves message meta then calls bridge.%s with the sequence', async (action, method) => {
const bridgeMethod = vi.fn(async () => {});
const bridge = fakeBridge({ [method]: bridgeMethod } as any);
const ctx = fakeCtx(bridge, {
getMessageMeta: (id: number) => id === 7 ? fakeMeta({ targetId: 100, sequence: 555 }) : null,
});
const res = await makeHandler(ctx).handle(action, { group_id: 100, message_id: 7 });
expect(res.status).toBe('ok');
expect(bridgeMethod).toHaveBeenCalledWith(100, 555n);
});
it('rejects when message meta is missing', async () => {
const ctx = fakeCtx(fakeBridge(), { getMessageMeta: () => null });
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 1, message_id: 9999 });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'message not found' });
});
it('rejects when message belongs to a different chat', async () => {
const ctx = fakeCtx(fakeBridge(), {
getMessageMeta: () => fakeMeta({ targetId: 222 }),
});
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects when message is a private message', async () => {
const ctx = fakeCtx(fakeBridge(), {
getMessageMeta: () => fakeMeta({ isGroup: false }),
});
const res = await makeHandler(ctx).handle('set_group_todo', { group_id: 100, message_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects missing params', async () => {
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { message_id: 1 });
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('set_group_todo', { group_id: 1 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
// ─── Tier 2: nc_get_user_status ───
describe('extended-actions / nc_get_user_status', () => {
it('returns whatever bridge.getStrangerStatus reports', async () => {
const getStrangerStatus = vi.fn(async () => ({ status: 10, ext_status: 0x1234 }));
const bridge = fakeBridge({ getStrangerStatus: getStrangerStatus as any });
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 999 });
expect(getStrangerStatus).toHaveBeenCalledWith(999);
expect(res).toMatchObject({ status: 'ok', data: { status: 10, ext_status: 0x1234 } });
});
it('reports action_failed when bridge returns null', async () => {
const bridge = fakeBridge({ getStrangerStatus: (async () => null) as any });
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', { user_id: 1 });
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
it('rejects missing user_id', async () => {
const bridge = fakeBridge({ getStrangerStatus: vi.fn() as any });
const res = await makeHandler(fakeCtx(bridge)).handle('nc_get_user_status', {});
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
});
});
// ─── Tier 2: AI voice trio ───
describe('extended-actions / get_ai_characters', () => {
it('flattens server categories into {type, characters[]}', async () => {
const fetchAiVoiceList = vi.fn(async () => [{
category: 'cute',
voices: [
{ voiceId: 'v1', voiceDisplayName: 'V1', voiceExampleUrl: 'http://a' },
{ voiceId: 'v2', voiceDisplayName: 'V2', voiceExampleUrl: 'http://b' },
],
}]);
const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any });
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', {
group_id: 100, chat_type: 1,
});
expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1);
expect(res.data).toEqual([{
type: 'cute',
characters: [
{ character_id: 'v1', character_name: 'V1', preview_url: 'http://a' },
{ character_id: 'v2', character_name: 'V2', preview_url: 'http://b' },
],
}]);
});
it('defaults chat_type to 1 (Sound) when unspecified', async () => {
const fetchAiVoiceList = vi.fn(async () => []);
const bridge = fakeBridge({ fetchAiVoiceList: fetchAiVoiceList as any });
await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 });
expect(fetchAiVoiceList).toHaveBeenCalledWith(100, 1);
});
it('surfaces bridge errors as action_failed', async () => {
const bridge = fakeBridge({
fetchAiVoiceList: (async () => { throw new Error('rate limited'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_characters', { group_id: 100 });
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'rate limited' });
});
});
describe('extended-actions / get_ai_record', () => {
it('feeds IndexNode from fetchAiVoice into fetchGroupPttUrlByNode and returns the URL', async () => {
const node = { fileUuid: 'voice-uuid' };
const fetchAiVoice = vi.fn(async () => node);
const fetchGroupPttUrlByNode = vi.fn(async () => 'http://voice.silk');
const bridge = fakeBridge({
fetchAiVoice: fetchAiVoice as any,
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', {
group_id: 100, character: 'v1', text: 'hello',
});
expect(fetchAiVoice).toHaveBeenCalledWith(100, 'v1', 'hello', 1);
expect(fetchGroupPttUrlByNode).toHaveBeenCalledWith(100, node);
expect(res).toMatchObject({ status: 'ok', data: 'http://voice.silk' });
});
it('rejects missing fields', async () => {
const r1 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { character: 'v', text: 't' });
const r2 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, text: 't' });
const r3 = await makeHandler(fakeCtx(fakeBridge())).handle('get_ai_record', { group_id: 1, character: 'v' });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r3).toMatchObject({ status: 'failed', retcode: 1400 });
});
it('reports action_failed when synthesis exhausts retries', async () => {
const bridge = fakeBridge({
fetchAiVoice: (async () => { throw new Error('AI voice synthesis did not complete'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('get_ai_record', {
group_id: 1, character: 'v', text: 't',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100 });
});
});
describe('extended-actions / send_group_ai_record', () => {
it('side-effects fetchAiVoice (no URL fetch) and returns message_id=0', async () => {
const fetchAiVoice = vi.fn(async () => ({ fileUuid: 'uuid' }));
const fetchGroupPttUrlByNode = vi.fn();
const bridge = fakeBridge({
fetchAiVoice: fetchAiVoice as any,
fetchGroupPttUrlByNode: fetchGroupPttUrlByNode as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('send_group_ai_record', {
group_id: 100, character: 'v', text: 'hi',
});
expect(fetchAiVoice).toHaveBeenCalledOnce();
expect(fetchGroupPttUrlByNode).not.toHaveBeenCalled();
expect(res).toMatchObject({ status: 'ok', data: { message_id: 0 } });
});
});
// ─── Tier 3: set_diy_online_status ───
describe('extended-actions / set_diy_online_status', () => {
it('coerces face_id / face_type from string-or-number and forwards to bridge.setDiyOnlineStatus', async () => {
const setDiyOnlineStatus = vi.fn(async () => {});
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', {
face_id: '1234',
face_type: '2',
wording: '摸鱼中',
});
expect(res.status).toBe('ok');
expect(setDiyOnlineStatus).toHaveBeenCalledWith(1234, '摸鱼中', 2);
});
it('defaults face_type to 1 when omitted, wording to empty string', async () => {
const setDiyOnlineStatus = vi.fn(async () => {});
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', { face_id: 99 });
expect(setDiyOnlineStatus).toHaveBeenCalledWith(99, '', 1);
});
it('rejects missing face_id', async () => {
const setDiyOnlineStatus = vi.fn();
const bridge = fakeBridge({ setDiyOnlineStatus: setDiyOnlineStatus as any });
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', { wording: 'x' });
expect(res).toMatchObject({ status: 'failed', retcode: 1400 });
expect(setDiyOnlineStatus).not.toHaveBeenCalled();
});
it('surfaces bridge errors as action_failed with the original message', async () => {
const bridge = fakeBridge({
setDiyOnlineStatus: (async () => { throw new Error('denied'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('set_diy_online_status', {
face_id: 1, wording: 'x',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'denied' });
});
});
// ─── set_group_portrait (Lagrange-protocol highway upload, cmdId 3000) ───
describe('extended-actions / set_group_portrait', () => {
it('forwards group_id + file to bridge.setGroupAvatar', async () => {
const setGroupAvatar = vi.fn(async () => {});
const bridge = fakeBridge({ setGroupAvatar: setGroupAvatar as any });
const res = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', {
group_id: 12345, file: '/tmp/avatar.png',
});
expect(res.status).toBe('ok');
expect(setGroupAvatar).toHaveBeenCalledWith(12345, '/tmp/avatar.png');
});
it('rejects missing group_id or file', async () => {
const setGroupAvatar = vi.fn();
const bridge = fakeBridge({ setGroupAvatar: setGroupAvatar as any });
const r1 = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', { file: 'x' });
const r2 = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', { group_id: 1 });
expect(r1).toMatchObject({ status: 'failed', retcode: 1400 });
expect(r2).toMatchObject({ status: 'failed', retcode: 1400 });
expect(setGroupAvatar).not.toHaveBeenCalled();
});
it('surfaces highway / decode errors as action_failed', async () => {
const bridge = fakeBridge({
setGroupAvatar: (async () => { throw new Error('highway 500'); }) as any,
});
const res = await makeHandler(fakeCtx(bridge)).handle('set_group_portrait', {
group_id: 1, file: 'x.png',
});
expect(res).toMatchObject({ status: 'failed', retcode: 100, wording: 'highway 500' });
});
});
@@ -0,0 +1,220 @@
// Regression coverage for nested forward (forward-inside-forward).
//
// `parseForwardNodes` detects an all-`{type:'node'}` content array,
// recursively builds the inner `ForwardNodePayload[]`, and attaches it
// to the outer node as `innerForward`. `uploadForwardNodes` then drives
// the recursive long-msg upload + ARK-preview generation + msgBody
// piggyback in one pass over the tree — modelled on NapCat's
// `uploadForwardedNodesPacket` (`dev/NapCatQQ/.../SendMsg.ts:208`).
//
// These tests stub `bridge.uploadForwardNodes` so we can inspect the
// payload that the upload pipeline receives: outer nodes carry an
// `innerForward` field holding the parsed inner chain, and the
// upload helper is invoked exactly ONCE (the recursive walk happens
// inside the real implementation; mocks see only the top call).
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context';
import {
sendGroupForwardMessage,
sendPrivateForwardMessage,
} from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
describe('forward — nested {type:"node"} content', () => {
it('group: nested forward attaches inner chain to outer node via `innerForward`', async () => {
// Single upload call, but the outer payload now carries an
// `innerForward` field with the recursively-parsed inner chain.
// The real `uploadForwardNodes` (the production module) walks
// that tree and does the recursive long-msg uploads with NapCat
// piggyback — we're just testing the parse-side handoff here.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'OUTER_RESID');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'outer',
content: [{
type: 'node',
data: {
user_id: 222, nickname: 'inner',
content: [{ type: 'text', data: { text: 'hello from inner' } }],
},
}],
},
}];
const result = await sendGroupForwardMessage(ctx, 12345, messages as any);
// Exactly one upload call: the production-side recursive walker
// owns the inner upload, the OneBot parser just hands off the tree.
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [outerNodes, outerGroupId] = uploadForwardNodes.mock.calls[0]!;
expect(outerGroupId).toBe(12345);
const outerNode = (outerNodes as any[])[0]!;
expect(outerNode.userUin).toBe(111);
// Outer node's `elements` is empty — the upload pipeline replaces
// it with the real ARK preview once it has the inner res_id.
expect(outerNode.elements).toEqual([]);
// The inner chain rides along as `innerForward`.
expect(Array.isArray(outerNode.innerForward)).toBe(true);
expect(outerNode.innerForward).toHaveLength(1);
expect(outerNode.innerForward[0]).toMatchObject({
userUin: 222,
nickname: 'inner',
elements: [{ type: 'text', text: 'hello from inner' }],
});
expect(result.forwardId).toBe('OUTER_RESID');
expect(sendGroupMessage).toHaveBeenCalledOnce();
});
it('private: nested forward threads userId into uploadForwardNodes', async () => {
// Same shape but routed via sendPrivateForwardMessage. The c2c path
// passes `userId` instead of `groupId` so the upload pipeline can
// pick up the recipient's UID scene for any inner media element.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RESID');
const sendPrivateMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
}));
const bridge = fakeBridge({ apis: { message: { sendPrivate: sendPrivateMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'outer',
content: [{
type: 'node',
data: {
user_id: 222, nickname: 'inner',
content: [{ type: 'text', data: { text: 'hi' } }],
},
}],
},
}];
await sendPrivateForwardMessage(ctx, 67890, messages as any);
// Single call, c2c-scoped (groupId undefined, userId = recipient).
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const call = uploadForwardNodes.mock.calls[0]!;
expect(call[1]).toBeUndefined();
expect(call[2]).toBe(67890);
// Inner chain attached via `innerForward`.
const outerNode = (call[0] as any[])[0]!;
expect(outerNode.innerForward).toHaveLength(1);
expect(outerNode.innerForward[0]!.userUin).toBe(222);
});
it('rejects nesting deeper than 3 levels', async () => {
// Build a 4-level nested chain. NapCat caps at 3 too, going further
// wastes long-msg uploads and risks one inner upload timing out
// and aborting the whole tree. Better to fail loud here.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'X');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
function wrap(content: any, depth: number): any {
if (depth === 0) return [{ type: 'text', data: { text: 'leaf' } }];
return [{
type: 'node',
data: { user_id: 100 + depth, nickname: `lvl-${depth}`, content: wrap(content, depth - 1) },
}];
}
await expect(
sendGroupForwardMessage(ctx, 12345, wrap(null, 4) as any),
).rejects.toThrow(/depth/);
});
it('flat content (no nesting) still goes through the unchanged path', async () => {
// Backwards-compat: a single-level forward with plain text nodes
// calls uploadForwardNodes exactly once and never touches the
// recursive branch.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [
{ type: 'node', data: { user_id: 111, nickname: 'a', content: [{ type: 'text', data: { text: 'one' } }] } },
{ type: 'node', data: { user_id: 222, nickname: 'b', content: [{ type: 'text', data: { text: 'two' } }] } },
];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
const [nodes] = uploadForwardNodes.mock.calls[0]!;
expect((nodes as any[])).toHaveLength(2);
expect((nodes as any[])[0]!.elements).toEqual([{ type: 'text', text: 'one' }]);
expect((nodes as any[])[1]!.elements).toEqual([{ type: 'text', text: 'two' }]);
});
it('mixed content (some {type:"node"} + non-node) falls back to flat parsing — does NOT recurse', async () => {
// Recursion only kicks in when *all* content entries are nodes —
// mixed content is ambiguous (do the non-node parts belong to the
// outer node or are they parallel siblings?), so we keep the legacy
// behaviour and let parseMessage handle it. Non-node parts come
// through, node parts get parsed via `case 'node':` and then
// dropped by element-builder. A user who wants nested forward
// should pass a pure node list.
const uploadForwardNodes = vi.fn(async (_nodes: any[], _groupId?: number, _userId?: number) => 'RES');
const sendGroupMessage = vi.fn(async () => ({
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 0,
}));
const bridge = fakeBridge({ apis: { message: { sendGroup: sendGroupMessage }, forward: { upload: uploadForwardNodes } } } as any);
const ctx = makeCtx(bridge);
const messages = [{
type: 'node',
data: {
user_id: 111, nickname: 'mixed',
content: [
{ type: 'text', data: { text: 'a sibling' } },
{ type: 'node', data: { user_id: 222, content: [{ type: 'text', data: { text: 'lost' } }] } },
],
},
}];
await sendGroupForwardMessage(ctx, 12345, messages as any);
expect(uploadForwardNodes).toHaveBeenCalledOnce();
// Only the text element survives — the legacy "node MessageElement"
// that parseMessage produces is opaque to the element-builder.
const [nodes] = uploadForwardNodes.mock.calls[0]!;
const elements = (nodes as any[])[0]!.elements;
expect(elements.some((e: any) => e.type === 'text' && e.text === 'a sibling')).toBe(true);
});
});
@@ -0,0 +1,213 @@
// Tests for the Event0x2DC subType=16 (GroupMsgEmojiLike) end-to-end:
// - decoder strips the 7-byte prefix and decodes GroupReactNotify
// - field13==35 yields a GroupMsgEmojiLikeEvent
// - field13!=35 surfaces under MsgPush.Unknown and emits nothing
// - converter shape matches the gocqhttp / NapCat extension layout
// - formatEvent prints something readable in the [Event] log
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import { protobuf_encode } from '@snowluma/proton';
import type { GroupReactNotify } from '@snowluma/proto-defs/notify';
import { decodeEvent0x2DC } from '@snowluma/bridge/msg-push/decoders/event-0x2dc';
import type { MsgPushContext } from '@snowluma/bridge/msg-push/context';
import { IdentityService } from '@snowluma/bridge/identity-service';
import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '@snowluma/bridge/events';
import { convertGroupMsgEmojiLike } from '../src/event-converter/to-notice';
import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/message-id';
import { formatEvent } from '@snowluma/bridge/format';
import { subscribeLogs, type LogEntry } from '@snowluma/common/logger';
const SELF_UIN = '10001';
const GROUP_ID = 123456789;
function makeIdentity(): IdentityService {
return IdentityService.memory(SELF_UIN);
}
/** Build the raw bytes QQ would push into ctx.content for subType=16:
* a 7-byte magic prefix followed by an encoded GroupReactNotify. */
function buildReactContent(notify: Record<string, unknown>): Uint8Array {
const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]);
const body = protobuf_encode<GroupReactNotify>(notify as GroupReactNotify);
const out = new Uint8Array(prefix.length + body.length);
out.set(prefix, 0);
out.set(body, prefix.length);
return out;
}
function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext {
return {
head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 },
fromUin: 0,
fromUid: '',
selfUin: Number(SELF_UIN),
content,
body: undefined,
responseHead: undefined,
identity,
};
}
describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => {
it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 4242n },
groupReactionDataContent: {
code: '76',
count: 1,
operatorUid: 'u_operator_xxx',
type: 1, // add
},
},
},
},
});
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
expect(event).toBeDefined();
expect(event.kind).toBe('group_msg_emoji_like');
expect(event.groupId).toBe(GROUP_ID);
expect(event.operatorUid).toBe('u_operator_xxx');
expect(event.emojiId).toBe('76');
expect(event.msgSeq).toBe(4242);
expect(event.count).toBe(1);
expect(event.isAdd).toBe(true);
});
it('decodes type=2 as react remove (isAdd=false)', () => {
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 35,
groupReactionData: {
data: {
data: {
groupReactionTarget: { seq: 1n },
groupReactionDataContent: {
code: '⭐',
count: 1,
operatorUid: 'u_x',
type: 2,
},
},
},
},
});
const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[];
expect(event.isAdd).toBe(false);
expect(event.emojiId).toBe('⭐');
});
it('drops the packet and logs to MsgPush.Unknown when field13 is not 35', () => {
const captured: LogEntry[] = [];
const unsub = subscribeLogs((e) => captured.push(e));
const content = buildReactContent({
groupUin: BigInt(GROUP_ID),
field13: 99, // not 35
groupReactionData: {
data: { data: { groupReactionDataContent: { code: 'x', operatorUid: 'u_y' } } },
},
});
const result = decodeEvent0x2DC(makeCtx(content));
unsub();
expect(result).toHaveLength(0);
const unknown = captured.find((e) =>
e.scope === 'MsgPush.Unknown' && /field13=99/.test(e.message));
expect(unknown).toBeDefined();
});
it('returns empty when content is shorter than the prefix length', () => {
const tooShort = new Uint8Array([1, 2, 3]); // < 7 bytes
expect(decodeEvent0x2DC(makeCtx(tooShort))).toEqual([]);
});
});
describe('convertGroupMsgEmojiLike — OneBot notice shape', () => {
const baseEvent: GroupMsgEmojiLikeEvent = {
kind: 'group_msg_emoji_like',
time: 1735000000,
selfUin: 10001,
groupId: 123456789,
operatorUin: 99999,
operatorUid: 'u_x',
msgSeq: 4242,
emojiId: '76',
count: 1,
isAdd: true,
};
// Real production wiring puts a hashMessageIdInt32-based resolver
// on the ctx; mirror that so message_id is the same value the
// bot would have minted for the original message.
const ctx = {
selfId: 10001,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: (_isGroup: boolean, sessionId: number, sequence: number, eventName: string) =>
hashMessageIdInt32(sequence, sessionId, eventName),
mediaSegmentSink: null,
} as never;
it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => {
const out = convertGroupMsgEmojiLike(ctx, baseEvent);
expect(out.post_type).toBe('notice');
expect(out.notice_type).toBe('group_msg_emoji_like');
expect(out.sub_type).toBe('add');
expect(out.group_id).toBe(123456789);
expect(out.user_id).toBe(99999);
expect(out.operator_id).toBe(99999);
expect(out.message_seq).toBe(4242);
expect(out.message_id).toBe(hashMessageIdInt32(4242, 123456789, GROUP_MESSAGE_EVENT));
expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]);
});
it('flips sub_type to remove when isAdd is false', () => {
const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false });
expect(out.sub_type).toBe('remove');
});
});
describe('formatEvent — group_msg_emoji_like', () => {
let savedLevel: string | undefined;
beforeEach(() => { savedLevel = process.env.SNOWLUMA_LOG_LEVEL; });
afterEach(() => {
if (savedLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL;
else process.env.SNOWLUMA_LOG_LEVEL = savedLevel;
});
it('renders a one-line summary with group, operator and emoji id', () => {
const identity = IdentityService.memory(SELF_UIN);
identity.rememberGroups([{
groupId: GROUP_ID, groupName: 'TestGroup', remark: '',
memberCount: 1, memberMax: 500, members: new Map(),
}]);
identity.rememberGroupMembers(GROUP_ID, [{
uin: 99999, uid: 'u_x', nickname: 'Alice', card: '',
role: 'member', level: 0, title: '',
joinTime: 0, lastSentTime: 0, shutUpTime: 0,
}]);
const event: QQEventVariant = {
kind: 'group_msg_emoji_like',
time: 0, selfUin: Number(SELF_UIN),
groupId: GROUP_ID,
operatorUin: 99999, operatorUid: 'u_x',
msgSeq: 100, emojiId: '76', count: 1, isAdd: true,
};
const line = formatEvent(identity, event);
expect(line).toBeDefined();
expect(line).toContain('TestGroup');
expect(line).toContain('Alice');
expect(line).toContain('[76]');
expect(line).toContain('msgSeq=100');
});
});
@@ -0,0 +1,149 @@
// Tests for HTTP server adapter content-type parsing (POST body).
// Covers: application/x-www-form-urlencoded, application/json,
// no content-type fallback, and unsupported content-type rejection.
import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest';
import http from 'http';
import { HttpServerAdapter } from '../src/network/http-server-adapter';
import type { NetworkAdapterContext } from '../src/network/adapter';
import type { HttpServerNetwork } from '../src/types';
// ─── Helpers ───
function fakeCtx(handleFn: (action: string, params: Record<string, unknown>) => unknown): NetworkAdapterContext {
return {
uin: '10001',
api: {
handle: vi.fn(async (action: string, params: Record<string, unknown>) => {
const data = handleFn(action, params);
return { status: 'ok', retcode: 0, data };
}),
} as any,
buildLifecycleEvent: vi.fn(() => ({})),
buildHeartbeatEvent: vi.fn(() => ({})),
};
}
function post(port: number, path: string, body: string, headers: Record<string, string> = {}): Promise<{ status: number; body: any }> {
return new Promise((resolve, reject) => {
const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => {
const chunks: Buffer[] = [];
res.on('data', (c) => chunks.push(c));
res.on('end', () => {
const raw = Buffer.concat(chunks).toString('utf8');
try {
resolve({ status: res.statusCode!, body: JSON.parse(raw) });
} catch {
resolve({ status: res.statusCode!, body: raw });
}
});
});
req.on('error', reject);
req.end(body);
});
}
// ─── Tests ───
describe('HttpServerAdapter content-type parsing', () => {
let adapter: HttpServerAdapter;
let handleFn: ReturnType<typeof vi.fn<(action: string, params: Record<string, unknown>) => unknown>>;
const PORT = 19876;
beforeAll(async () => {
handleFn = vi.fn((_action: string, params: Record<string, unknown>) => params);
const ctx = fakeCtx(handleFn);
const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false };
adapter = new HttpServerAdapter('test-http', config, ctx);
adapter.open();
// Wait for server to be listening
await new Promise((resolve) => setTimeout(resolve, 100));
});
afterAll(() => {
adapter.close();
});
it('should parse application/json body', async () => {
const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), {
'content-type': 'application/json',
});
expect(res.status).toBe(200);
expect(res.body.status).toBe('ok');
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' });
});
it('should parse application/x-www-form-urlencoded body', async () => {
handleFn.mockClear();
const body = 'group_id=456&message=hello';
const res = await post(PORT, '/send_message', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(res.body.status).toBe('ok');
expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' });
});
it('should JSON-parse values in urlencoded body', async () => {
handleFn.mockClear();
const body = 'user_id=789&data={"nested":true}';
const res = await post(PORT, '/get_info', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } });
});
it('should extract action from urlencoded body when path has no action', async () => {
handleFn.mockClear();
const body = 'action=get_status&key=value';
const res = await post(PORT, '/', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' });
});
it('should extract echo from urlencoded body', async () => {
handleFn.mockClear();
const body = 'action=test_action&echo=12345&foo=bar';
const res = await post(PORT, '/', body, {
'content-type': 'application/x-www-form-urlencoded',
});
expect(res.status).toBe(200);
expect(res.body.echo).toBe(12345);
expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' });
});
it('should reject unsupported content-type with 400', async () => {
const res = await post(PORT, '/send_message', '<xml></xml>', {
'content-type': 'application/xml',
});
expect(res.status).toBe(400);
expect(res.body.wording).toContain('unsupported content-type');
});
it('should reject invalid JSON with explicit application/json content-type', async () => {
const res = await post(PORT, '/send_message', 'not-json{{{', {
'content-type': 'application/json',
});
expect(res.status).toBe(400);
expect(res.body.wording).toContain('invalid json');
});
it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => {
handleFn.mockClear();
const body = 'action=fallback_action&param1=value1';
const res = await post(PORT, '/', body, {});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' });
});
it('should parse JSON when no content-type and body is valid JSON', async () => {
handleFn.mockClear();
const body = JSON.stringify({ action: 'json_action', params: { x: 1 } });
const res = await post(PORT, '/', body, {});
expect(res.status).toBe(200);
expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 });
});
});
@@ -0,0 +1,141 @@
// Hot-reload tests for HttpServerAdapter — pins the contract that
// `reload({ accessToken: <new> })` must take effect on the very next
// request without the listener being torn down. Earlier the adapter
// captured `accessToken` into a `startServer()` closure and relied on
// `bindingSignature` to trigger a `close()` + `open()` round-trip on
// token change; that race-prone path is gone and `handleRequest` now
// reads `this.config.accessToken` per request.
import { describe, expect, it, vi, afterEach } from 'vitest';
import http from 'http';
import type { AddressInfo } from 'net';
import { HttpServerAdapter } from '../src/network/http-server-adapter';
import { NetworkReloadType, type NetworkAdapterContext } from '../src/network/adapter';
import type { HttpServerNetwork } from '../src/types';
function fakeCtx(): NetworkAdapterContext {
return {
uin: '10001',
api: {
handle: vi.fn(async () => ({ status: 'ok', retcode: 0, data: { online: true } })),
} as any,
buildLifecycleEvent: vi.fn(() => ({})),
buildHeartbeatEvent: vi.fn(() => ({})),
};
}
function get(port: number, path: string, headers: Record<string, string> = {}): Promise<{ status: number }> {
return new Promise((resolve, reject) => {
const req = http.request(
{ hostname: '127.0.0.1', port, path, method: 'GET', headers },
(res) => {
res.on('data', () => { /* drain */ });
res.on('end', () => resolve({ status: res.statusCode! }));
},
);
req.on('error', reject);
req.end();
});
}
// Wait until the underlying http.Server has bound its port; tests that
// hit the socket too early get ECONNREFUSED on slow CI hosts.
async function waitForListen(adapter: HttpServerAdapter): Promise<number> {
for (let i = 0; i < 50; i++) {
const server = (adapter as any).server as http.Server | null;
const addr = server?.address() as AddressInfo | null | undefined;
if (addr && typeof addr === 'object') return addr.port;
await new Promise((r) => setTimeout(r, 20));
}
throw new Error('http server never started listening');
}
describe('HttpServerAdapter — accessToken hot reload', () => {
let adapter: HttpServerAdapter | null = null;
afterEach(() => {
adapter?.close();
adapter = null;
});
it('a swapped accessToken authorizes the new token on the next request — no listener re-bind', async () => {
const ctx = fakeCtx();
// port=0 → OS-assigned; the swap proves no re-bind happens because
// a re-bind would land on a different port and `waitForListen`
// would diverge from the original.
const config: HttpServerNetwork = {
name: 'hot', port: 0, enabled: true, accessToken: 'tok-1',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot', config, ctx);
adapter.open();
const portBefore = await waitForListen(adapter);
// Sanity: old token authorizes, anything else 401s.
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(200);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(401);
// Hot-swap the token.
await adapter.reload({ ...config, accessToken: 'tok-2' });
// Same port (no re-bind) — and the new token must take effect on
// the very next request.
const portAfter = ((adapter as any).server as http.Server).address() as AddressInfo;
expect(portAfter.port).toBe(portBefore);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-1' })).status).toBe(401);
expect((await get(portBefore, '/', { authorization: 'Bearer tok-2' })).status).toBe(200);
});
it('clearing accessToken to empty disables auth on the next request', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-clear', port: 0, enabled: true, accessToken: 'tok-1',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-clear', config, ctx);
adapter.open();
const port = await waitForListen(adapter);
expect((await get(port, '/')).status).toBe(401); // no token header → 401
await adapter.reload({ ...config, accessToken: '' });
expect((await get(port, '/')).status).toBe(200); // auth disabled
});
it('setting accessToken from empty enforces auth on the next request', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-add', port: 0, enabled: true,
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-add', config, ctx);
adapter.open();
const port = await waitForListen(adapter);
expect((await get(port, '/')).status).toBe(200); // no auth configured
await adapter.reload({ ...config, accessToken: 'tok-new' });
expect((await get(port, '/')).status).toBe(401); // auth now required
expect((await get(port, '/', { authorization: 'Bearer tok-new' })).status).toBe(200);
});
it('changing only accessToken returns NetworkReloadType.Normal — no Reopened/Closed', async () => {
const ctx = fakeCtx();
const config: HttpServerNetwork = {
name: 'hot-type', port: 0, enabled: true, accessToken: 'a',
messageFormat: 'array', reportSelfMessage: false,
};
adapter = new HttpServerAdapter('hot-type', config, ctx);
adapter.open();
await waitForListen(adapter);
const reloadType = await adapter.reload({ ...config, accessToken: 'b' });
// Without re-binding, the adapter reports `Normal` — anything but
// `Reopened` / `Closed` is acceptable; we mostly care that nothing
// touched the listener.
expect(reloadType).toBe(NetworkReloadType.Normal);
});
});
+127
View File
@@ -0,0 +1,127 @@
import { describe, it, expect, vi } from 'vitest';
import { MediaIndexer } from '../src/media-indexer';
import type { MessageElement } from '@snowluma/bridge/events';
function makeMediaStore() {
return {
rememberImage: vi.fn(),
rememberRecord: vi.fn(),
rememberVideo: vi.fn(),
};
}
describe('MediaIndexer', () => {
it('image: maps element fields into rememberImage with file fallback to fileId', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = {
type: 'image',
fileId: 'img-fid',
fileSize: 1024,
subType: 1,
summary: '[image]',
imageUrl: 'http://orig',
md5Hex: 'abcd',
sha1Hex: 'efgh',
width: 800,
height: 600,
picFormat: 1000,
};
indexer.remember('image', element, { url: 'http://x', file: '' }, true, 99999);
expect(store.rememberImage).toHaveBeenCalledOnce();
const arg = store.rememberImage.mock.calls[0]![0];
expect(arg).toMatchObject({
file: 'img-fid', // data.file was '', fell back to element.fileId
url: 'http://x',
fileSize: 1024,
subType: 1,
summary: '[image]',
imageUrl: 'http://orig',
isGroup: true,
sessionId: 99999,
md5Hex: 'abcd',
sha1Hex: 'efgh',
width: 800,
height: 600,
picFormat: 1000,
});
});
it('record: maps element fields into rememberRecord with file fallback chain', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = {
type: 'record',
fileId: 'rec-fid',
fileName: 'voice.amr',
fileSize: 2048,
duration: 5,
fileHash: 'h',
mediaNode: { fileUuid: 'uuid' },
md5Hex: 'm',
sha1Hex: 's',
voiceFormat: 1,
};
indexer.remember('record', element, { url: 'http://r', file: '' }, false, 12345);
const arg = store.rememberRecord.mock.calls[0]![0];
expect(arg.file).toBe('voice.amr'); // data.file '' → element.fileName
expect(arg.fileId).toBe('rec-fid');
expect(arg.duration).toBe(5);
expect(arg.isGroup).toBe(false);
expect(arg.sessionId).toBe(12345);
expect(arg.voiceFormat).toBe(1);
});
it('video: maps element fields into rememberVideo', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = {
type: 'video',
fileId: 'vid-fid',
fileName: 'clip.mp4',
fileSize: 99999,
duration: 30,
width: 1920,
height: 1080,
videoFormat: 2,
};
indexer.remember('video', element, { url: 'http://v', file: 'override.mp4' }, true, 11111);
const arg = store.rememberVideo.mock.calls[0]![0];
expect(arg.file).toBe('override.mp4'); // data.file used when non-empty
expect(arg.fileId).toBe('vid-fid');
expect(arg.duration).toBe(30);
expect(arg.width).toBe(1920);
expect(arg.videoFormat).toBe(2);
});
it('falls back to element.fileId when data.file AND element.fileName are missing (record)', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
const element: MessageElement = { type: 'record', fileId: 'only-fid' };
indexer.remember('record', element, { url: '', file: '' }, false, 1);
expect(store.rememberRecord.mock.calls[0]![0].file).toBe('only-fid');
});
it('defaults missing numeric fields to 0 / missing strings to ""', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
indexer.remember('image', { type: 'image' }, { url: '', file: '' }, false, 0);
const arg = store.rememberImage.mock.calls[0]![0];
expect(arg.fileSize).toBe(0);
expect(arg.subType).toBe(0);
expect(arg.summary).toBe('');
expect(arg.imageUrl).toBe('');
});
it('only the matching rememberX is called', () => {
const store = makeMediaStore();
const indexer = new MediaIndexer(store as any);
indexer.remember('image', { type: 'image' }, { url: '', file: 'a' }, true, 1);
expect(store.rememberImage).toHaveBeenCalledOnce();
expect(store.rememberRecord).not.toHaveBeenCalled();
expect(store.rememberVideo).not.toHaveBeenCalled();
});
});
+318
View File
@@ -0,0 +1,318 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
import fs from 'fs';
import path from 'path';
import { MediaStore } from '../src/media-store';
import { convertEvent, type ConverterContext } from '../src/event-converter';
import type { GroupMessage, FriendMessage, MessageElement } from '@snowluma/bridge/events';
const SELF_ID = 10001;
const PEER_UIN = 22222;
const GROUP_ID = 99999;
function imageElement(overrides: Partial<MessageElement> = {}): MessageElement {
return {
type: 'image',
fileId: 'abc.png',
fileSize: 4242,
imageUrl: 'https://example.com/abc.png',
...overrides,
};
}
function recordElement(overrides: Partial<MessageElement> = {}): MessageElement {
return {
type: 'record',
fileId: 'uuid-base64-fake',
fileName: 'silk_test.amr',
fileSize: 1024,
duration: 3,
fileHash: 'deadbeef',
mediaNode: { fileUuid: 'uuid-base64-fake', storeId: 1 },
...overrides,
};
}
function makeGroupMessage(elements: MessageElement[]): GroupMessage {
return {
kind: 'group_message',
time: 1700000000,
selfUin: SELF_ID,
groupId: GROUP_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
senderCard: '',
senderRole: 'member',
msgSeq: 1,
msgId: 1,
elements,
};
}
function makeFriendMessage(elements: MessageElement[]): FriendMessage {
return {
kind: 'friend_message',
time: 1700000000,
selfUin: SELF_ID,
senderUin: PEER_UIN,
senderNick: 'peer',
msgSeq: 1,
msgId: 1,
elements,
};
}
function tempDbPath(label: string): string {
return path.join('data', 'test', `media-${label}-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
}
describe('MediaStore basic semantics', () => {
const dbs: string[] = [];
beforeEach(() => {
dbs.length = 0;
});
afterEach(() => {
for (const dbPath of dbs) {
for (const ext of ['', '-wal', '-shm']) {
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
}
}
});
function open(label: string, max?: number): MediaStore {
const dbPath = tempDbPath(label);
dbs.push(dbPath);
return max !== undefined ? new MediaStore(dbPath, max) : new MediaStore(dbPath);
}
it('indexes images by file, fileName, and url', () => {
const store = open('img-keys');
store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 4242,
fileName: 'abc.png',
subType: 0,
summary: '',
imageUrl: 'https://example.com/abc.png',
isGroup: true,
sessionId: GROUP_ID,
});
expect(store.findImage('abc.png')?.fileSize).toBe(4242);
expect(store.findImage('https://example.com/abc.png')?.url).toBe('https://example.com/abc.png');
expect(store.findImage('missing.png')).toBeNull();
expect(store.findImage('')).toBeNull();
store.close();
});
it('indexes records by file, fileName, fileId, and url', () => {
const store = open('rec-keys');
store.rememberRecord({
file: 'silk_test.amr',
fileId: 'uuid-base64-fake',
url: 'https://example.com/voice.amr',
fileSize: 1024,
fileName: 'silk_test.amr',
duration: 3,
fileHash: 'deadbeef',
mediaNode: { fileUuid: 'uuid-base64-fake' },
isGroup: false,
sessionId: PEER_UIN,
});
expect(store.findRecord('silk_test.amr')?.duration).toBe(3);
expect(store.findRecord('uuid-base64-fake')?.fileId).toBe('uuid-base64-fake');
expect(store.findRecord('https://example.com/voice.amr')?.url).toBe('https://example.com/voice.amr');
expect(store.findRecord('nope')).toBeNull();
store.close();
});
it('updates URLs in place across all alias keys', () => {
const store = open('url-update');
store.rememberRecord({
file: 'silk_test.amr',
fileId: 'uuid-base64-fake',
url: '',
fileSize: 1024,
fileName: 'silk_test.amr',
duration: 3,
fileHash: '',
mediaNode: { fileUuid: 'uuid-base64-fake' },
isGroup: false,
sessionId: PEER_UIN,
});
store.updateRecordUrl('silk_test.amr', 'https://refreshed.example.com/voice.amr');
expect(store.findRecord('silk_test.amr')?.url).toBe('https://refreshed.example.com/voice.amr');
expect(store.findRecord('uuid-base64-fake')?.url).toBe('https://refreshed.example.com/voice.amr');
store.close();
});
it('survives close+reopen against the same db path', () => {
const dbPath = tempDbPath('persist');
dbs.push(dbPath);
{
const store = new MediaStore(dbPath);
store.rememberImage({
file: 'abc.png',
url: 'https://example.com/abc.png',
fileSize: 99,
fileName: 'abc.png',
subType: 0,
summary: '',
imageUrl: 'https://example.com/abc.png',
isGroup: true,
sessionId: GROUP_ID,
});
store.close();
}
{
const store = new MediaStore(dbPath);
const found = store.findImage('abc.png');
expect(found).not.toBeNull();
expect(found!.fileSize).toBe(99);
// Alias index must also persist.
expect(store.findImage('https://example.com/abc.png')?.fileSize).toBe(99);
store.close();
}
});
it('evicts old entries beyond the configured cap', () => {
// EVICT_EVERY_N_REMEMBERS = 64 inside the store; we exercise the eviction
// path by writing well past the cap so it triggers at least once.
const cap = 80;
const store = open('evict', cap);
for (let i = 0; i < 200; i++) {
store.rememberImage({
file: `file-${i}.png`,
url: `https://example.com/${i}.png`,
fileSize: i,
fileName: `file-${i}.png`,
subType: 0,
summary: '',
imageUrl: '',
isGroup: true,
sessionId: GROUP_ID,
});
}
const { images } = store.size();
expect(images).toBeLessThanOrEqual(cap);
// Most recent entries should still be present.
expect(store.findImage('file-199.png')?.fileSize).toBe(199);
store.close();
});
});
describe('convertEvent media segment sink → MediaStore wiring', () => {
const dbs: string[] = [];
afterEach(() => {
for (const dbPath of dbs) {
for (const ext of ['', '-wal', '-shm']) {
try { fs.unlinkSync(dbPath + ext); } catch { /* ignore */ }
}
}
dbs.length = 0;
});
it('emits sink invocations for image segments with the right context', async () => {
const sinkCalls: Array<{ type: string; isGroup: boolean; sessionId: number; file: string }> = [];
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: (type, _element, data, isGroup, sessionId) => {
sinkCalls.push({ type, isGroup, sessionId, file: String(data.file ?? '') });
},
};
await convertEvent(ctx, makeGroupMessage([imageElement()]));
await convertEvent(ctx, makeFriendMessage([recordElement()]));
expect(sinkCalls).toEqual([
{ type: 'image', isGroup: true, sessionId: GROUP_ID, file: 'abc.png' },
{ type: 'record', isGroup: false, sessionId: PEER_UIN, file: 'silk_test.amr' },
]);
});
it('lets the sink populate a MediaStore that get_image-style lookups can use', async () => {
const dbPath = tempDbPath('sink');
dbs.push(dbPath);
const store = new MediaStore(dbPath);
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: (element) => element.imageUrl ?? '',
mediaUrlResolver: async (element) => element.url ?? '',
messageIdResolver: null,
mediaSegmentSink: (type, element, data, isGroup, sessionId) => {
const url = typeof data.url === 'string' ? data.url : '';
const file = typeof data.file === 'string' ? data.file : '';
if (type === 'image') {
store.rememberImage({
file: file || element.fileId || '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileId ?? '',
subType: element.subType ?? 0,
summary: element.summary ?? '',
imageUrl: element.imageUrl ?? '',
isGroup,
sessionId,
});
} else {
store.rememberRecord({
file: file || element.fileName || element.fileId || '',
fileId: element.fileId ?? '',
url,
fileSize: element.fileSize ?? 0,
fileName: element.fileName ?? '',
duration: element.duration ?? 0,
fileHash: element.fileHash ?? '',
mediaNode: element.mediaNode,
isGroup,
sessionId,
});
}
},
};
await convertEvent(ctx, makeGroupMessage([imageElement()]));
await convertEvent(ctx, makeFriendMessage([recordElement()]));
const img = store.findImage('abc.png');
expect(img).not.toBeNull();
expect(img!.url).toBe('https://example.com/abc.png');
expect(img!.fileSize).toBe(4242);
expect(img!.isGroup).toBe(true);
expect(img!.sessionId).toBe(GROUP_ID);
const rec = store.findRecord('silk_test.amr');
expect(rec).not.toBeNull();
expect(rec!.fileId).toBe('uuid-base64-fake');
expect(rec!.duration).toBe(3);
expect(rec!.isGroup).toBe(false);
expect(rec!.sessionId).toBe(PEER_UIN);
// Alias lookup by fileUuid still works.
expect(store.findRecord('uuid-base64-fake')?.fileName).toBe('silk_test.amr');
store.close();
});
it('does not invoke the sink when no media segments are present', async () => {
let calls = 0;
const ctx: ConverterContext = {
selfId: SELF_ID,
imageUrlResolver: null,
mediaUrlResolver: null,
messageIdResolver: null,
mediaSegmentSink: () => { calls++; },
};
await convertEvent(ctx, makeGroupMessage([{ type: 'text', text: 'hello' }]));
expect(calls).toBe(0);
});
});
@@ -0,0 +1,147 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { MediaUrlResolver } from '../src/media-url-resolver';
import type { MessageElement } from '@snowluma/bridge/events';
// Minimal stand-ins for the two collaborators. Each test wires whatever
// subset of Bridge methods the element type exercises.
//
// MediaUrlResolver now reaches `bridge.apis.groupFile.{getUrl,
// getPrivateUrl, getPttUrl, getPrivatePttUrl, getVideoUrl,
// getPrivateVideoUrl}` per the #6 Api-on-ctx refactor. The helper here
// builds an `apis.groupFile` stub directly so tests can keep asserting
// "which file/url helper got called" without going through the
// `mockBridge` shared fixture.
function makeBridge(overrides: Record<string, ReturnType<typeof vi.fn>> = {}) {
return {
apis: {
groupFile: {
getUrl: overrides.getUrl ?? vi.fn(async () => 'http://group/file'),
getPrivateUrl: overrides.getPrivateUrl ?? vi.fn(async () => 'http://private/file'),
getPttUrl: overrides.getPttUrl ?? vi.fn(async () => 'http://group/ptt'),
getPrivatePttUrl: overrides.getPrivatePttUrl ?? vi.fn(async () => 'http://private/ptt'),
getVideoUrl: overrides.getVideoUrl ?? vi.fn(async () => 'http://group/video'),
getPrivateVideoUrl: overrides.getPrivateVideoUrl ?? vi.fn(async () => 'http://private/video'),
},
},
};
}
function makeRkey(overrides: { resolveMediaUrl?: ReturnType<typeof vi.fn> } = {}) {
return {
resolveMediaUrl: overrides.resolveMediaUrl ?? vi.fn(async (_bridge, el: MessageElement) => el.url ?? ''),
};
}
const MEDIA_NODE = { fileUuid: 'uuid-1' };
describe('MediaUrlResolver — file element', () => {
let bridge: ReturnType<typeof makeBridge>;
let rkey: ReturnType<typeof makeRkey>;
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
it('group + fileId: uses fetchGroupFileUrl, then applies rkey', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
const out = await resolver.resolve(element, true, 12345);
expect(bridge.apis.groupFile.getUrl).toHaveBeenCalledWith(12345, 'fid-x');
expect(element.url).toBe('http://group/file');
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
expect(out).toBe('http://group/file');
});
it('c2c + fileId + fileHash: uses fetchPrivateFileUrl', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x', fileHash: 'hash-y' };
await resolver.resolve(element, false, 67890);
expect(bridge.apis.groupFile.getPrivateUrl).toHaveBeenCalledWith(67890, 'fid-x', 'hash-y');
expect(element.url).toBe('http://private/file');
});
it('c2c + fileId but no fileHash: sets url to empty string (no bridge call)', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid-x' };
await resolver.resolve(element, false, 67890);
expect(bridge.apis.groupFile.getPrivateUrl).not.toHaveBeenCalled();
expect(element.url).toBe('');
});
});
describe('MediaUrlResolver — record / video element', () => {
let bridge: ReturnType<typeof makeBridge>;
let rkey: ReturnType<typeof makeRkey>;
beforeEach(() => { bridge = makeBridge(); rkey = makeRkey(); });
it('group record: uses fetchGroupPttUrlByNode', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
await resolver.resolve(element, true, 12345);
expect(bridge.apis.groupFile.getPttUrl).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(element.url).toBe('http://group/ptt');
});
it('c2c record: uses fetchPrivatePttUrlByNode (no sessionId argument)', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record', mediaNode: MEDIA_NODE };
await resolver.resolve(element, false, 67890);
expect(bridge.apis.groupFile.getPrivatePttUrl).toHaveBeenCalledWith(MEDIA_NODE);
expect(element.url).toBe('http://private/ptt');
});
it('group video: uses fetchGroupVideoUrlByNode', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
await resolver.resolve(element, true, 12345);
expect(bridge.apis.groupFile.getVideoUrl).toHaveBeenCalledWith(12345, MEDIA_NODE);
expect(element.url).toBe('http://group/video');
});
it('c2c video: uses fetchPrivateVideoUrlByNode', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'video', mediaNode: MEDIA_NODE };
await resolver.resolve(element, false, 67890);
expect(bridge.apis.groupFile.getPrivateVideoUrl).toHaveBeenCalledWith(MEDIA_NODE);
expect(element.url).toBe('http://private/video');
});
it('record without mediaNode: no bridge call, url untouched', async () => {
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'record' };
await resolver.resolve(element, true, 12345);
expect(bridge.apis.groupFile.getPttUrl).not.toHaveBeenCalled();
expect(element.url).toBeUndefined();
});
});
describe('MediaUrlResolver — short-circuits and resilience', () => {
it('element.url already set: no bridge call, just rkey pass', async () => {
const bridge = makeBridge();
const rkey = makeRkey();
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid', url: 'already-set' };
await resolver.resolve(element, true, 12345);
expect(bridge.apis.groupFile.getUrl).not.toHaveBeenCalled();
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
});
it('bridge throws: swallowed, rkey still applied', async () => {
const bridge = makeBridge({
getUrl: vi.fn(async () => { throw new Error('network down'); }),
});
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'rkey-fallback') });
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'file', fileId: 'fid' };
const out = await resolver.resolve(element, true, 12345);
expect(out).toBe('rkey-fallback');
expect(element.url).toBeUndefined(); // bridge threw before assignment
});
it('always calls rkey.resolveMediaUrl at the end', async () => {
const bridge = makeBridge();
const rkey = makeRkey({ resolveMediaUrl: vi.fn(async () => 'http://signed') });
const resolver = new MediaUrlResolver(bridge as any, rkey as any);
const element: MessageElement = { type: 'image' };
const out = await resolver.resolve(element, true, 12345);
expect(rkey.resolveMediaUrl).toHaveBeenCalledOnce();
expect(out).toBe('http://signed');
});
});
+49
View File
@@ -0,0 +1,49 @@
import { describe, it, expect } from 'vitest';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
describe('hashMessageIdInt32', () => {
it('returns consistent hash for same inputs', () => {
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
expect(id1).toBe(id2);
});
it('returns non-zero', () => {
// The function ensures id !== 0 by setting it to 1
const id = hashMessageIdInt32(0, 0, '');
expect(id).not.toBe(0);
});
it('returns different values for different sequences', () => {
const id1 = hashMessageIdInt32(1, 12345, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(2, 12345, GROUP_MESSAGE_EVENT);
expect(id1).not.toBe(id2);
});
it('returns different values for different sessions', () => {
const id1 = hashMessageIdInt32(100, 11111, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(100, 22222, GROUP_MESSAGE_EVENT);
expect(id1).not.toBe(id2);
});
it('returns different values for different event names', () => {
const id1 = hashMessageIdInt32(100, 12345, GROUP_MESSAGE_EVENT);
const id2 = hashMessageIdInt32(100, 12345, PRIVATE_MESSAGE_EVENT);
expect(id1).not.toBe(id2);
});
it('returns 32-bit integer', () => {
const id = hashMessageIdInt32(999999, 123456789, GROUP_MESSAGE_EVENT);
expect(id).toBeGreaterThanOrEqual(-2147483648);
expect(id).toBeLessThanOrEqual(2147483647);
});
it('handles non-finite inputs gracefully', () => {
const id1 = hashMessageIdInt32(NaN, 0, 'test');
const id2 = hashMessageIdInt32(Infinity, 0, 'test');
expect(typeof id1).toBe('number');
expect(typeof id2).toBe('number');
// Both should map to sequence=0
expect(id1).toBe(id2);
});
});
@@ -0,0 +1,483 @@
import fs from 'fs';
import os from 'os';
import path from 'path';
import { describe, it, expect, vi } from 'vitest';
import { protobuf_decode, protobuf_encode } from '@snowluma/proton';
import { parseMessage } from '../src/message-parser';
import { buildSendElems } from '@snowluma/bridge/element-builder';
import type { MentionExtraSend } from '@snowluma/proto-defs/action';
import type { OidbBase } from '@snowluma/proto-defs/oidb';
import type { NTV2UploadRichMediaResp } from '@snowluma/proto-defs/highway';
describe('parseMessage', () => {
describe('plain text', () => {
it('parses simple text', async () => {
const result = await parseMessage('hello world', false);
expect(result).toEqual([{ type: 'text', text: 'hello world' }]);
});
it('returns empty for empty string', async () => {
const result = await parseMessage('', false);
expect(result).toEqual([]);
});
it('autoEscape treats CQ codes as text', async () => {
const result = await parseMessage('[CQ:face,id=123]', true);
expect(result).toEqual([{ type: 'text', text: '[CQ:face,id=123]' }]);
});
});
describe('CQ code parsing', () => {
it('parses face CQ code', async () => {
const result = await parseMessage('[CQ:face,id=123]', false);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(123);
});
it('parses at CQ code', async () => {
const result = await parseMessage('[CQ:at,qq=12345]', false);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('at');
expect(result[0].targetUin).toBe(12345);
});
it('parses at all', async () => {
const result = await parseMessage('[CQ:at,qq=all]', false);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('at');
expect(result[0].targetUin).toBe(0);
});
it('parses mixed text and CQ codes', async () => {
const result = await parseMessage('Hello [CQ:face,id=1] World', false);
expect(result).toHaveLength(3);
expect(result[0]).toEqual({ type: 'text', text: 'Hello ' });
expect(result[1].type).toBe('face');
expect(result[2]).toEqual({ type: 'text', text: ' World' });
});
it('unescapes CQ special chars', async () => {
const result = await parseMessage('a&amp;b&#91;c&#93;d', false);
expect(result).toEqual([{ type: 'text', text: 'a&b[c]d' }]);
});
});
describe('JSON segment array', () => {
it('parses text segment', async () => {
const result = await parseMessage(
[{ type: 'text', data: { text: 'hello' } }] as any,
false,
);
expect(result).toEqual([{ type: 'text', text: 'hello' }]);
});
it('parses face segment', async () => {
const result = await parseMessage(
[{ type: 'face', data: { id: 123 } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(123);
});
it('parses image segment', async () => {
const result = await parseMessage(
[{ type: 'image', data: { file: 'https://example.com/img.png' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('image');
expect(result[0].url).toBe('https://example.com/img.png');
});
it('parses record segment from data.file', async () => {
const result = await parseMessage(
[{ type: 'record', data: { file: 'file:///tmp/voice.amr' } }] as any,
false,
);
expect(result).toEqual([{ type: 'record', url: 'file:///tmp/voice.amr' }]);
});
it('parses video segment from data.path and preserves thumb', async () => {
const result = await parseMessage(
[{ type: 'video', data: { path: '/tmp/clip.mp4', thumb: '/tmp/clip.png' } }] as any,
false,
);
expect(result).toEqual([{ type: 'video', url: '/tmp/clip.mp4', thumbUrl: '/tmp/clip.png' }]);
});
it('parses AstrBot-style Video segment with top-level media', async () => {
const result = await parseMessage(
[{ type: 'Video', media: 'file:////AstrBot/data/cache/BV-test.mp4' }] as any,
false,
);
expect(result).toEqual([{ type: 'video', url: 'file:////AstrBot/data/cache/BV-test.mp4', thumbUrl: undefined }]);
});
it('drops video segment with empty source', async () => {
const result = await parseMessage(
[{ type: 'video', data: {} }] as any,
false,
);
expect(result).toEqual([]);
});
it('parses record segment from data.path (NapCat parity)', async () => {
const result = await parseMessage(
[{ type: 'record', data: { path: 'C:\\voices\\hi.silk' } }] as any,
false,
);
expect(result).toEqual([{ type: 'record', url: 'C:\\voices\\hi.silk' }]);
});
it('drops record segment with empty source', async () => {
const result = await parseMessage(
[{ type: 'record', data: {} }] as any,
false,
);
expect(result).toEqual([]);
});
it('parses at segment', async () => {
const result = await parseMessage(
[{ type: 'at', data: { qq: 12345 } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('at');
expect(result[0].targetUin).toBe(12345);
});
it('uses at segment name for display text and preserves uid', async () => {
const result = await parseMessage(
[{ type: 'at', data: { qq: '123456', name: 'User', uid: 'u_test_uid' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
type: 'at',
targetUin: 123456,
uid: 'u_test_uid',
text: '@User ',
});
});
it('resolves missing at uid through parse options', async () => {
const result = await parseMessage(
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
false,
{ resolveMentionUid: async (targetUin) => targetUin === 123456 ? 'u_resolved_uid' : null },
);
expect(result).toHaveLength(1);
expect(result[0]).toMatchObject({
type: 'at',
targetUin: 123456,
uid: 'u_resolved_uid',
text: '@User ',
});
});
it('encodes mention extra with resolved uid for QQ notification', async () => {
const elements = await parseMessage(
[{ type: 'at', data: { qq: '123456', name: 'User' } }] as any,
false,
{ resolveMentionUid: () => 'u_resolved_uid' },
);
const protoElems = await buildSendElems(elements);
const reserve = protoElems[0].text?.pbReserve;
expect(reserve).toBeInstanceOf(Uint8Array);
const extra = protobuf_decode<MentionExtraSend>(reserve as Uint8Array);
expect(extra).toMatchObject({
type: 2,
uin: 123456,
uid: 'u_resolved_uid',
});
expect(protoElems[0].text?.str).toBe('@User ');
});
it('skips record send when SendContext is absent (graceful no-bridge path)', async () => {
// Without a SendContext, buildSendElems can't run highway upload —
// it should warn and drop the element instead of throwing into the
// ffmpegAddon (which would explode for callers that don't actually
// need to send).
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'record', data: { file: '/tmp/x.silk' } },
] as any,
false,
);
const protoElems = await buildSendElems(elements);
// Only the leading text should make it through.
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
});
it('skips video send when SendContext is absent (graceful no-bridge path)', async () => {
const elements = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'video', data: { file: '/tmp/x.mp4' } },
] as any,
false,
);
const protoElems = await buildSendElems(elements);
expect(protoElems).toHaveLength(1);
expect(protoElems[0].text?.str).toBe('hi ');
});
it('builds video commonElem through NTV2 fast-upload response', async () => {
const videoPath = path.join(os.tmpdir(), `snowluma-video-test-${process.pid}-${Date.now()}.mp4`);
fs.writeFileSync(videoPath, Buffer.from([0, 1, 2, 3]));
const responseData = protobuf_encode<OidbBase<NTV2UploadRichMediaResp>>({
command: 0x11EA,
subCommand: 100,
errorCode: 0,
body: {
respHead: { retCode: 0, message: '' },
upload: {
uKey: '',
msgInfo: {
msgInfoBody: [
{ index: { fileUuid: 'video-uuid' }, fileExist: true },
{ index: { fileUuid: 'thumb-uuid' }, fileExist: true },
],
extBizInfo: {
video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) },
},
},
subFileInfos: [{ uKey: '' }],
},
},
errorMsg: '',
reserved: 1,
});
const bridge = {
identity: { uin: '10000' },
sendRawPacket: vi.fn(async () => ({
success: true,
gotResponse: true,
errorCode: 0,
errorMessage: '',
responseData,
})),
} as any;
try {
const protoElems = await buildSendElems([{
type: 'video',
url: videoPath,
thumbUrl: 'base64://iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+/p9sAAAAASUVORK5CYII=',
}], { bridge, groupId: 123456 });
expect(bridge.sendRawPacket).toHaveBeenCalledTimes(1);
expect(bridge.sendRawPacket).toHaveBeenCalledWith('OidbSvcTrpcTcp.0x11ea_100', expect.any(Uint8Array));
expect(protoElems).toHaveLength(1);
expect(protoElems[0].commonElem?.serviceType).toBe(48);
expect(protoElems[0].commonElem?.businessType).toBe(21);
expect(protoElems[0].commonElem?.pbElem).toBeInstanceOf(Uint8Array);
} finally {
try { fs.unlinkSync(videoPath); } catch { /* ignore */ }
}
});
it('parses multiple segments', async () => {
const result = await parseMessage(
[
{ type: 'text', data: { text: 'hi ' } },
{ type: 'at', data: { qq: 999 } },
{ type: 'text', data: { text: ' there' } },
] as any,
false,
);
expect(result).toHaveLength(3);
expect(result[0].type).toBe('text');
expect(result[1].type).toBe('at');
expect(result[2].type).toBe('text');
});
it('skips unknown segment types', async () => {
const result = await parseMessage(
[
{ type: 'text', data: { text: 'ok' } },
{ type: 'unknown_type_xyz', data: {} },
] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('text');
});
});
describe('special segments', () => {
it('parses json segment', async () => {
const result = await parseMessage(
[{ type: 'json', data: { data: '{"app":"test"}' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBe('{"app":"test"}');
});
it('parses reply segment with resolveReplySequence', async () => {
const result = await parseMessage(
[{ type: 'reply', data: { id: 42 } }] as any,
false,
{ resolveReplySequence: (id) => id === 42 ? 100 : null },
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('reply');
expect(result[0].replySeq).toBe(100);
});
it('parses share as json card', async () => {
const result = await parseMessage(
[{ type: 'share', data: { url: 'https://example.com', title: 'Test' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBeDefined();
const parsed = JSON.parse(result[0].text!);
expect(parsed.app).toBe('com.tencent.structmsg');
expect(parsed.meta.news.title).toBe('Test');
});
it('parses rps as face', async () => {
const result = await parseMessage(
[{ type: 'rps', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(359);
});
it('parses dice as face', async () => {
const result = await parseMessage(
[{ type: 'dice', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('face');
expect(result[0].faceId).toBe(358);
});
it('parses shake as poke', async () => {
const result = await parseMessage(
[{ type: 'shake', data: {} }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('poke');
});
it('ignores anonymous segment', async () => {
const result = await parseMessage(
[
{ type: 'anonymous', data: {} },
{ type: 'text', data: { text: 'hi' } },
] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('text');
});
it('parses location as json card', async () => {
const result = await parseMessage(
[{ type: 'location', data: { lat: '39.9', lon: '116.3', title: 'Beijing' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBeDefined();
const parsed = JSON.parse(result[0].text!);
expect(parsed.app).toBe('com.tencent.map');
expect(parsed.meta.Location.lat).toBe('39.9');
});
it('parses contact as json card', async () => {
const result = await parseMessage(
[{ type: 'contact', data: { type: 'group', id: '12345' } }] as any,
false,
);
expect(result).toHaveLength(1);
expect(result[0].type).toBe('json');
expect(result[0].text).toBeDefined();
const parsed = JSON.parse(result[0].text!);
expect(parsed.meta.contact.type).toBe('group');
});
});
describe('single segment object', () => {
it('parses single segment object', async () => {
const result = await parseMessage(
{ type: 'text', data: { text: 'single' } } as any,
false,
);
expect(result).toEqual([{ type: 'text', text: 'single' }]);
});
});
describe('edge cases', () => {
it('returns empty for null', async () => {
const result = await parseMessage(null as any, false);
expect(result).toEqual([]);
});
it('returns empty for number', async () => {
const result = await parseMessage(42 as any, false);
expect(result).toEqual([]);
});
});
describe('file segment', () => {
// Closes the parser-side of the "upload says ok but message is
// empty" bug. Before this, `{type:'file', file_id:'…'}` segments
// fell through to the default warn-and-drop branch — which made
// `send_msg([{type:'file', file_id:'<uploaded>'}])` produce either
// a "message is empty" error or, when mixed with text, a message
// with the file segment quietly missing.
it('parses {type:"file", file_id:"x"} into a file MessageElement', async () => {
const result = await parseMessage(
[{ type: 'file', data: { file_id: 'fid-1', name: 'a.zip', size: 123 } } as any],
false,
);
expect(result).toEqual([
{ type: 'file', fileId: 'fid-1', fileName: 'a.zip', fileSize: 123 },
]);
});
it('drops a file segment with no file_id (upload-first contract)', async () => {
// Path-only segments aren't supported here — callers must
// upload via `upload_group_file` / `upload_private_file` first
// to obtain a file_id. Dropping with a warning is preferable
// to silently kicking off an upload from inside the message
// parser, which can't fail loudly without changing call sites.
const result = await parseMessage(
[{ type: 'file', data: { file: '/local/path/a.bin' } } as any],
false,
);
expect(result).toEqual([]);
});
it('accepts fileId / filename / fileName / md5 / sha1 aliases', async () => {
const result = await parseMessage(
[{
type: 'file',
data: { fileId: 'fid-2', filename: 'b.zip', fileSize: 456, md5: 'AB', sha1: 'CD' },
} as any],
false,
);
expect(result).toEqual([
{ type: 'file', fileId: 'fid-2', fileName: 'b.zip', fileSize: 456, md5Hex: 'AB', sha1Hex: 'CD' },
]);
});
});
});
+190
View File
@@ -0,0 +1,190 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { MessageStore } from '../src/message-store';
import { hashMessageIdInt32, GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT } from '../src/message-id';
import fs from 'fs';
import path from 'path';
describe('MessageStore', () => {
const testDbPath = path.join('data', 'test', 'messages-test.db');
let store: MessageStore;
beforeEach(() => {
// Clean up any existing test database
try {
fs.unlinkSync(testDbPath);
} catch {
// Ignore if file doesn't exist
}
store = new MessageStore(testDbPath);
});
afterEach(() => {
store.close();
// Clean up test database
try {
fs.unlinkSync(testDbPath);
} catch {
// Ignore cleanup errors
}
});
describe('resolveReplySequence', () => {
it('resolves group message reply sequence', () => {
const groupId = 123456;
const sequence = 100;
const messageId = hashMessageIdInt32(sequence, groupId, GROUP_MESSAGE_EVENT);
// Store a group message
store.storeMeta(messageId, {
isGroup: true,
targetId: groupId,
sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Resolve the reply sequence
const resolved = store.resolveReplySequence(true, groupId, messageId);
expect(resolved).toBe(sequence);
});
it('resolves private message reply sequence without session_id matching', () => {
// Simulate receiving a private message from user 111111
const senderUin = 111111;
const sequence = 200;
const messageId = hashMessageIdInt32(sequence, senderUin, PRIVATE_MESSAGE_EVENT);
// Store the received message (session_id is sender's UIN)
store.storeMeta(messageId, {
isGroup: false,
targetId: senderUin,
sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// When replying to this message, we send to the sender (who becomes the recipient)
// The key fix: resolveReplySequence should work even when sessionId doesn't match
const resolved = store.resolveReplySequence(false, senderUin, messageId);
expect(resolved).toBe(sequence);
// More importantly: it should also work when we pass a different sessionId
// (which was the bug - we were passing recipient UIN instead of sender UIN)
const differentUin = 999999;
const resolvedWithDifferentSession = store.resolveReplySequence(false, differentUin, messageId);
expect(resolvedWithDifferentSession).toBe(sequence);
});
it('returns null for non-existent message', () => {
const resolved = store.resolveReplySequence(true, 123456, 999999);
expect(resolved).toBeNull();
});
it('returns null for invalid messageId', () => {
const resolved = store.resolveReplySequence(true, 123456, 0);
expect(resolved).toBeNull();
});
it('returns null for invalid sessionId', () => {
const messageId = hashMessageIdInt32(100, 123456, GROUP_MESSAGE_EVENT);
const resolved = store.resolveReplySequence(true, 0, messageId);
expect(resolved).toBeNull();
});
it('distinguishes between group and private messages', () => {
const sessionId = 123456;
const sequence = 300;
// Store a group message
const groupMessageId = hashMessageIdInt32(sequence, sessionId, GROUP_MESSAGE_EVENT);
store.storeMeta(groupMessageId, {
isGroup: true,
targetId: sessionId,
sequence,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Store a private message with same sequence but different hash
const privateMessageId = hashMessageIdInt32(sequence, sessionId, PRIVATE_MESSAGE_EVENT);
store.storeMeta(privateMessageId, {
isGroup: false,
targetId: sessionId,
sequence,
eventName: PRIVATE_MESSAGE_EVENT,
clientSequence: 0,
random: 0,
timestamp: Date.now(),
});
// Should resolve correctly based on isGroup flag
const groupResolved = store.resolveReplySequence(true, sessionId, groupMessageId);
expect(groupResolved).toBe(sequence);
const privateResolved = store.resolveReplySequence(false, sessionId, privateMessageId);
expect(privateResolved).toBe(sequence);
// Should not cross-resolve
const wrongGroupResolve = store.resolveReplySequence(true, sessionId, privateMessageId);
expect(wrongGroupResolve).toBeNull();
const wrongPrivateResolve = store.resolveReplySequence(false, sessionId, groupMessageId);
expect(wrongPrivateResolve).toBeNull();
});
});
describe('storeEvent and findEvent', () => {
it('stores and retrieves event data', () => {
const messageId = 12345;
const event = {
post_type: 'message',
message_type: 'group',
message_id: messageId,
group_id: 123456,
message: 'test message',
time: Date.now(),
};
store.storeEvent(messageId, true, 123456, 100, GROUP_MESSAGE_EVENT, event);
const retrieved = store.findEvent(messageId);
expect(retrieved).toEqual(event);
});
it('returns null for non-existent event', () => {
const retrieved = store.findEvent(999999);
expect(retrieved).toBeNull();
});
});
describe('storeMeta and findMeta', () => {
it('stores and retrieves message meta', () => {
const messageId = 54321;
const meta = {
isGroup: true,
targetId: 123456,
sequence: 100,
eventName: GROUP_MESSAGE_EVENT,
clientSequence: 1,
random: 12345,
timestamp: Date.now(),
};
store.storeMeta(messageId, meta);
const retrieved = store.findMeta(messageId);
expect(retrieved).toEqual(meta);
});
it('returns null for non-existent meta', () => {
const retrieved = store.findMeta(999999);
expect(retrieved).toBeNull();
});
});
});
@@ -0,0 +1,180 @@
import { describe, expect, it } from 'vitest';
import { IOneBotNetworkAdapter, NetworkReloadType, OneBotNetworkManager } from '../src/network';
import type { NetworkAdapterContext } from '../src/network';
import type { JsonObject, NetworkBase } from '../src/types';
import type { DispatchPayload } from '../src/event-filter';
interface FakeNetworkConfig extends NetworkBase {
// Allows tests to influence behavior via config:
failOnEvent?: boolean;
}
class FakeAdapter extends IOneBotNetworkAdapter<FakeNetworkConfig> {
events: JsonObject[] = [];
opens = 0;
closes = 0;
reloads = 0;
// Last dispatch payload object identity, to assert it was reused per emit.
lastPayloads: DispatchPayload[] = [];
open(): void {
this.opens++;
if (this.config.enabled !== false) this.isEnabled = true;
}
close(): void {
this.closes++;
this.isEnabled = false;
}
reload(next: FakeNetworkConfig): NetworkReloadType {
this.reloads++;
this.config = structuredClone(next);
if (next.enabled === false && this.isEnabled) {
this.close();
return NetworkReloadType.Closed;
}
if (next.enabled !== false && !this.isEnabled) {
this.open();
return NetworkReloadType.Opened;
}
return NetworkReloadType.Normal;
}
onEvent(event: JsonObject, payload: DispatchPayload): void {
this.events.push(event);
this.lastPayloads.push(payload);
if (this.config.failOnEvent) throw new Error('boom');
}
}
const NULL_CTX: NetworkAdapterContext = {
uin: '10001',
api: { handle: async () => ({ status: 'failed', retcode: 0, data: null }), processRequest: async () => '' } as never,
buildLifecycleEvent: () => ({}),
buildHeartbeatEvent: () => ({}),
};
function makeAdapter(name: string, partial: Partial<FakeNetworkConfig> = {}): FakeAdapter {
const config: FakeNetworkConfig = {
name,
enabled: true,
messageFormat: 'array',
reportSelfMessage: false,
...partial,
};
return new FakeAdapter(name, config, NULL_CTX);
}
const SAMPLE_EVENT: JsonObject = {
time: 1,
self_id: 10001,
post_type: 'message',
message_type: 'private',
sub_type: 'friend',
message_id: 1,
user_id: 22222,
message: [{ type: 'text', data: { text: 'hi' } }],
raw_message: 'hi',
font: 0,
sender: { user_id: 22222, nickname: 'peer', sex: 'unknown', age: 0 },
};
describe('OneBotNetworkManager', () => {
it('opens and emits to every active adapter in parallel', async () => {
const mgr = new OneBotNetworkManager();
const a = makeAdapter('a');
const b = makeAdapter('b');
mgr.register(a);
mgr.register(b);
await mgr.openAll();
expect(a.opens).toBe(1);
expect(b.opens).toBe(1);
await mgr.emitEvent(SAMPLE_EVENT);
expect(a.events).toEqual([SAMPLE_EVENT]);
expect(b.events).toEqual([SAMPLE_EVENT]);
// Both adapters should receive the same payload reference (built once).
expect(a.lastPayloads[0]).toBe(b.lastPayloads[0]);
});
it('skips inactive adapters during emit', async () => {
const mgr = new OneBotNetworkManager();
const active = makeAdapter('active');
const idle = makeAdapter('idle', { enabled: false });
mgr.register(active);
mgr.register(idle);
await mgr.openAll();
await mgr.emitEvent(SAMPLE_EVENT);
expect(active.events).toHaveLength(1);
expect(idle.events).toHaveLength(0);
});
it('isolates adapter errors so one bad adapter does not block others', async () => {
const mgr = new OneBotNetworkManager();
const ok = makeAdapter('ok');
const bad = makeAdapter('bad', { failOnEvent: true });
mgr.register(ok);
mgr.register(bad);
await mgr.openAll();
await mgr.emitEvent(SAMPLE_EVENT);
// The good adapter still saw the event.
expect(ok.events).toHaveLength(1);
// The bad adapter logged the throw but didn't crash the manager.
expect(bad.events).toHaveLength(1);
});
it('replaces an existing adapter under the same name and closes the old one', async () => {
const mgr = new OneBotNetworkManager();
const first = makeAdapter('dup');
mgr.register(first);
await mgr.openAll();
const second = makeAdapter('dup');
mgr.register(second);
expect(mgr.get('dup')).toBe(second);
expect(first.closes).toBe(1);
});
it('closeOne shuts down a single adapter and removes it', async () => {
const mgr = new OneBotNetworkManager();
const a = makeAdapter('a');
const b = makeAdapter('b');
mgr.register(a);
mgr.register(b);
await mgr.openAll();
await mgr.closeOne('a');
expect(mgr.has('a')).toBe(false);
expect(a.closes).toBe(1);
expect(b.closes).toBe(0);
expect(mgr.hasActiveAdapters()).toBe(true);
});
it('closeAll clears every adapter', async () => {
const mgr = new OneBotNetworkManager();
const a = makeAdapter('a');
const b = makeAdapter('b');
mgr.register(a);
mgr.register(b);
await mgr.openAll();
await mgr.closeAll();
expect(mgr.list()).toHaveLength(0);
expect(a.closes).toBe(1);
expect(b.closes).toBe(1);
});
it('hasActiveAdapters reflects current state', async () => {
const mgr = new OneBotNetworkManager();
expect(mgr.hasActiveAdapters()).toBe(false);
const a = makeAdapter('a');
mgr.register(a);
expect(mgr.hasActiveAdapters()).toBe(false);
await mgr.openAll();
expect(mgr.hasActiveAdapters()).toBe(true);
await mgr.closeAll();
expect(mgr.hasActiveAdapters()).toBe(false);
});
});
@@ -0,0 +1,83 @@
import { describe, expect, it, vi } from 'vitest';
import { handleGroupAddRequest } from '../src/modules/request-actions';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { GroupRequestInfo } from '@snowluma/bridge/qq-info';
// See `contact-actions.test.ts` for the auto-promotion rationale.
const APIS_ROUTING: Record<string, string> = {
fetchFriendList: 'contacts', fetchGroupList: 'contacts',
fetchGroupMemberList: 'contacts', fetchUserProfile: 'contacts',
fetchGroupRequests: 'contacts', fetchDownloadRKeys: 'contacts',
};
function fakeBridge(overrides: Record<string, any> = {}): BridgeInterface {
const apisSynth: Record<string, Record<string, any>> = {};
for (const [k, v] of Object.entries(overrides)) {
const area = APIS_ROUTING[k];
if (area) {
if (!apisSynth[area]) apisSynth[area] = {};
apisSynth[area][k] = v;
}
}
const merged = { ...overrides, apis: { ...apisSynth, ...(overrides.apis ?? {}) } };
return new Proxy(merged as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`);
},
});
}
function fakeRequest(overrides: Partial<GroupRequestInfo> = {}): GroupRequestInfo {
return {
groupId: 999,
groupName: 'g',
targetUid: 'u_t',
targetUin: 5555,
targetName: 'target',
invitorUid: 'u_i',
invitorUin: 7777,
invitorName: 'inviter',
operatorUid: 'u_o',
operatorUin: 8888,
operatorName: 'op',
sequence: 42,
state: 1,
eventType: 7,
comment: 'pls',
filtered: false,
...overrides,
};
}
describe('onebot/modules/request-actions / handleGroupAddRequest', () => {
it('matches add requests by groupId and targetUid', async () => {
const setAddRequest = vi.fn(async () => {});
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }),
]),
apis: { groupAdmin: { setAddRequest } } as any,
});
await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok');
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false);
});
it('matches invite requests by groupId and invitorUid', async () => {
const setAddRequest = vi.fn(async () => {});
const bridge = fakeBridge({
fetchGroupRequests: vi.fn(async () => [
fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }),
]),
apis: { groupAdmin: { setAddRequest } } as any,
});
await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no');
expect(setAddRequest).toHaveBeenCalledOnce();
expect(setAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false);
});
});
@@ -0,0 +1,129 @@
// Regression coverage for the group-file-in-send_group_msg bug.
//
// Symptom in the wild: bot uploaded a group file via `upload_group_file`,
// then sent `{type:'file', file_id}` through `send_group_msg`; the
// element-builder wrapped it as `transElem(elemType=24, ...)` inside
// `richText.elems` and shipped a regular `MessageSvc.PbSendMsg`. The
// QQ-NT server rejected the message with `result=79` because that wire
// shape is RECEIVE-side only (rich-body-decoder unpacks it into a
// FileEntity for inbound messages, but the server's intake validator
// flags it on the send side).
//
// Fix: split file segments off at the OneBot layer (same pattern as
// the c2c-file split for private messages) and dispatch through
// `bridge.apis.groupFile.publish`, which calls dedicated OIDB
// `OidbSvcTrpcTcp.0x6d9_4` — Lagrange.Core V2's
// `GroupSendFileService.cs`.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context';
import { sendGroupMessage } from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null, resolveReplySequence: () => 0 } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
const goodReceipt = {
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
};
describe('send_group_msg with {type:"file"} segment', () => {
it('file-only message routes through apis.groupFile.publish (not apis.message.sendGroup)', async () => {
// Pure-file case — the elems[] path used to ship a transElem(24)
// and got result=79. The dedicated OIDB-0x6d9_4 route must take
// over for group file publishing.
const sendGroupMessage_bridge = vi.fn();
// Declare params on the fn so `mock.calls[0]` infers a tuple of
// [groupId, fileId] instead of `[]` (which makes the destructuring
// a tsc error under noUncheckedIndexedAccess).
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [{
type: 'file', data: { file_id: 'gfid-abc', name: 'doc.txt', size: 123 },
}] as any, false);
expect(publish).toHaveBeenCalledOnce();
expect(sendGroupMessage_bridge).not.toHaveBeenCalled();
const [groupId, fileId] = publish.mock.calls[0]!;
expect(groupId).toBe(12345);
expect(fileId).toBe('gfid-abc');
});
it('mixed text + file splits across two sends (text via elems[], file via OIDB)', async () => {
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn(async (_groupId: number, _fileId: string) => undefined);
const bridge = fakeBridge({
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'here is the file:' } },
{ type: 'file', data: { file_id: 'gfid-xyz', name: 'pkg.zip' } },
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(publish).toHaveBeenCalledOnce();
const [textGid, textElements] = sendGroupMessage_bridge.mock.calls[0]!;
expect(textGid).toBe(12345);
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
const [fileGid, fileFileId] = publish.mock.calls[0]!;
expect(fileGid).toBe(12345);
expect(fileFileId).toBe('gfid-xyz');
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// Same upload-by-reference contract as the c2c file path —
// missing file_id means there's nothing to publish.
const sendGroupMessage_bridge = vi.fn(async (_gid: number, _elements: any[]) => goodReceipt);
const publish = vi.fn();
const bridge = fakeBridge({
apis: {
message: { sendGroup: sendGroupMessage_bridge },
groupFile: { publish },
} as any,
resolveUserUid: vi.fn(),
} as any);
const ctx = makeCtx(bridge);
await sendGroupMessage(ctx, 12345, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
] as any, false);
expect(sendGroupMessage_bridge).toHaveBeenCalledOnce();
expect(publish).not.toHaveBeenCalled();
});
});
@@ -0,0 +1,230 @@
// Regression coverage for the c2c-file-in-send_private_msg bug.
//
// Symptom in the wild: bot called `send_private_msg` with a
// `{type:'file', file_id}` segment; the OneBot module passed it
// straight to `bridge.sendPrivateMessage(userId, [fileElement])`;
// `buildSendElems` warned ("file send via elems[] is group-only")
// and dropped it; the resulting wire send had 0 elems and the chat
// rendered "[空消息]".
//
// Fix: c2c file segments are split out at the OneBot layer in
// `sendPrivateMessage` and dispatched through `bridge.sendC2cFileMessage`
// (which writes `RichText.notOnlineFile`, the correct wire slot for
// c2c files). Matches NapCat's `SendMsg.ts:404-415` which splits
// FILE / VIDEO / ARK / PTT into their own sendMsg calls and never
// mixes them with the regular elems[] batch.
import { describe, expect, it, vi } from 'vitest';
import type { BridgeInterface } from '../../src/bridge/bridge-interface';
import type { OneBotInstanceContext } from '../src/instance-context';
import { sendPrivateMessage } from '../src/modules/message-actions';
function fakeBridge(overrides: Partial<BridgeInterface> = {}): BridgeInterface {
return new Proxy(overrides as BridgeInterface, {
get(target, prop) {
if (prop in target) return (target as any)[prop];
throw new Error(`fakeBridge: '${String(prop)}' was not stubbed for this test`);
},
});
}
function makeCtx(bridge: BridgeInterface): OneBotInstanceContext {
return {
uin: '10001',
bridge,
messageStore: { findEvent: () => null } as any,
cacheMessageMeta: vi.fn(),
mediaStore: {} as any,
musicSignUrl: '',
} as unknown as OneBotInstanceContext;
}
const goodReceipt = {
messageId: 1, sequence: 100, clientSequence: 0, random: 1, timestamp: 1700000000,
};
describe('send_private_msg with {type:"file"} segment', () => {
it('file-only message routes through sendC2cFileMessage (not sendPrivateMessage)', async () => {
// Pure-file case — the elems[] path would have dropped this entirely
// and shipped "[空消息]". The c2c file route must take over.
const sendPrivateMessage_bridge = vi.fn();
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const recallUploadedFile = vi.fn(() => undefined);
const bridge = fakeBridge({
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid,
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file',
data: { file_id: 'uuid-abc', name: 'doc.txt', size: 123, md5: '00112233' },
}] as any, false);
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
expect(sendPrivateMessage_bridge).not.toHaveBeenCalled();
const [uin, uid, info] = sendC2cFileMessage.mock.calls[0]!;
expect(uin).toBe(67890);
expect(uid).toBe('u_peer');
expect(info).toMatchObject({
fileId: 'uuid-abc',
fileName: 'doc.txt',
fileSize: 123,
});
// md5 decoded from hex (4 bytes for '00112233')
expect(info.fileMd5).toEqual(Buffer.from('00112233', 'hex'));
});
it('file-only with just file_id hydrates fileName/size/md5 from the upload cache', async () => {
// Reproduces the "0 B file" bug: a caller passes only `file_id` from
// a previous upload_private_file, with no size/md5/name. Without
// the cache lookup the wire packet ships fileSize=0/md5=empty and
// the recipient sees a 0-byte file. With the cache we recover the
// real tuple.
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const recallUploadedFile = vi.fn((id: string) => id === 'uuid-cached' ? {
fileId: 'uuid-cached',
scope: 'private' as const,
userId: 67890,
fileName: 'real-doc.pdf',
fileSize: 4096,
fileMd5: Buffer.from('aabbccddeeff', 'hex'),
fileSha1: new Uint8Array(20),
fileHash: 'srv-hash',
rememberedAt: 0,
} : undefined);
const bridge = fakeBridge({
apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-cached' },
}] as any, false);
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
expect(info).toMatchObject({
fileId: 'uuid-cached',
fileName: 'real-doc.pdf',
fileSize: 4096,
fileHash: 'srv-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('aabbccddeeff', 'hex'));
});
it('inline segment fields take precedence over the upload cache', async () => {
// If the caller threads the metadata inline (e.g. they tracked the
// upload response themselves), honour that over the cache so a
// refresh of an evicted file still works.
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const recallUploadedFile = vi.fn(() => ({
fileId: 'uuid-x',
scope: 'private' as const,
userId: 67890,
fileName: 'stale-cache-name.txt',
fileSize: 99,
fileMd5: new Uint8Array(16),
fileSha1: new Uint8Array(20),
fileHash: 'stale-hash',
rememberedAt: 0,
}));
const bridge = fakeBridge({
apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid: vi.fn(async () => 'u_peer'),
recallUploadedFile,
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [{
type: 'file', data: { file_id: 'uuid-x', name: 'inline.txt', size: 200, md5: '11223344', file_hash: 'inline-hash' },
}] as any, false);
const [, , info] = sendC2cFileMessage.mock.calls[0]!;
expect(info).toMatchObject({
fileName: 'inline.txt',
fileSize: 200,
fileHash: 'inline-hash',
});
expect(info.fileMd5).toEqual(Buffer.from('11223344', 'hex'));
});
it('mixed file + text splits across two sends (text first, file second)', async () => {
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn(async (_uin: number, _uid: string, _info: any) => goodReceipt);
const resolveUserUid = vi.fn(async () => 'u_peer');
const bridge = fakeBridge({
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid,
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'here is the file:' } },
{ type: 'file', data: { file_id: 'uuid-xyz', name: 'pkg.zip' } },
] as any, false);
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
expect(sendC2cFileMessage).toHaveBeenCalledOnce();
// Text goes via the elems[] pipeline.
const [textUin, textElements] = sendPrivateMessage_bridge.mock.calls[0]!;
expect(textUin).toBe(67890);
expect(textElements).toEqual([{ type: 'text', text: 'here is the file:' }]);
// File goes via the dedicated c2c-file API.
const [fileUin, fileUid, fileInfo] = sendC2cFileMessage.mock.calls[0]!;
expect(fileUin).toBe(67890);
expect(fileUid).toBe('u_peer');
expect(fileInfo).toMatchObject({ fileId: 'uuid-xyz', fileName: 'pkg.zip' });
});
it('file segment without file_id is skipped (with a warn-level log)', async () => {
// OneBot11 file segments are upload-by-reference — without a
// file_id there's nothing to send. Previously these slipped
// through to the elems[] path and shipped empty messages.
const sendPrivateMessage_bridge = vi.fn(async (_uin: number, _elements: any[]) => goodReceipt);
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendPrivate: sendPrivateMessage_bridge, sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid: vi.fn(),
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await sendPrivateMessage(ctx, 67890, [
{ type: 'text', data: { text: 'with bad file segment' } },
{ type: 'file', data: {} }, // no file_id
] as any, false);
// Text still went out, file dropped (no c2c file call).
expect(sendPrivateMessage_bridge).toHaveBeenCalledOnce();
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
it('throws when uid cannot be resolved for a file-only message', async () => {
// C2C file send requires the recipient's UID for the RichText.
// notOnlineFile routing. If lookup fails we can't proceed —
// surfacing the error is better than shipping a c2c send with
// an empty uid.
const sendC2cFileMessage = vi.fn();
const bridge = fakeBridge({
apis: { message: { sendPrivate: vi.fn(), sendC2cFile: sendC2cFileMessage } } as any,
resolveUserUid: vi.fn(async () => ''), // intentional empty
recallUploadedFile: vi.fn(() => undefined),
} as any);
const ctx = makeCtx(bridge);
await expect(sendPrivateMessage(ctx, 67890, [
{ type: 'file', data: { file_id: 'uuid-orphan', name: 'x.txt' } },
] as any, false)).rejects.toThrow(/could not resolve uid/);
expect(sendC2cFileMessage).not.toHaveBeenCalled();
});
});
+13
View File
@@ -0,0 +1,13 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"types": ["node"],
"noEmit": true
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules"
]
}
+33
View File
@@ -0,0 +1,33 @@
// Vitest config — runs the OneBot tests against the workspace TS
// source directly (no build step). The 20 tests here were previously
// inside `packages/core/tests/` and ran via `@snowluma/core`'s vitest
// invocation; they moved over wholesale in the Phase 3 split.
import protobufVitePlugin from '@snowluma/proton/vite';
import { defineConfig } from 'vitest/config';
export default defineConfig({
// `@snowluma/proton` provides the bare-specifier resolver that turns
// `import type { OidbBase } from '@snowluma/proto-defs/oidb'` into
// a zero-runtime encoder/decoder at the call site. The same plugin
// is loaded by `@snowluma/core`'s vite config — keep it here so the
// OneBot tests resolve identically.
plugins: [protobufVitePlugin()],
test: {
include: ['tests/**/*.test.ts'],
environment: 'node',
// Suppress the logger's file transport during tests so the suite
// doesn't litter cwd with logs/snowluma-*.log files. Tests that
// explicitly cover file output set their own SNOWLUMA_LOG_FILE='1'
// + SNOWLUMA_LOG_DIR=<tmp>.
//
// Run at debug level so tests asserting on debug-level log entries
// (e.g. action dispatch entry lines) actually see them via the
// ring buffer / subscribers, which sit behind the console-level
// gate. Mirrors the equivalent env setup in @snowluma/core's
// vitest.config.ts.
env: {
SNOWLUMA_LOG_FILE: '0',
SNOWLUMA_LOG_LEVEL: 'debug'
}
},
});