diff --git a/.github/logo.svg b/.github/logo.svg new file mode 100644 index 00000000..f9e8d0d4 --- /dev/null +++ b/.github/logo.svg @@ -0,0 +1,40 @@ + + + + + + + + SnowLuma + + + + SnowLuma + + + + + + diff --git a/README.md b/README.md index 84a5db6b..36250fdf 100644 --- a/README.md +++ b/README.md @@ -1,4 +1,6 @@ -

❄️ SnowLuma

+

+ SnowLuma +

Next Remote Protocol Framework. @@ -7,8 +9,7 @@

Release Build - @snowluma/sdk - @snowluma/ui + NPM Stars

@@ -21,111 +22,29 @@ --- -## 简介 - -SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。 - -项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。 +SnowLuma 是一个基于 TypeScript 的协议转换框架,旨在为 QQ 客户端提供 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准接口,支持 WebSocket/HTTP 适配、多账号并行及 WebUI 管理。 ## 特性 -- **OneBot v11 兼容** —— 涵盖文本、图片、视频、语音、合并转发、戳一戳、Markdown、JSON、XML 等常用消息段。 -- **多账号并行** —— 同一进程可同时托管多个 QQ 账号,会话彼此独立。 -- **多种适配器** —— WebSocket Server / WebSocket Client / HTTP Server / HTTP Post,HTTP 服务端同时支持 `application/json` 与 `application/x-www-form-urlencoded`。 -- **WebUI 管理面板** —— 浏览器登录、密码强度校验、登录限流、SSE 实时日志、配置热更新。 -- **TypeScript 全链路** —— Bridge / OneBot / SDK / UI 均使用 TypeScript,发布到 npm 的 `@snowluma/sdk` 与 `@snowluma/ui` 可直接供下游应用消费。 -- **数据持久化** —— 好友、群、群成员等关系数据落 SQLite,跨重启可用。 +- **OneBot v11 兼容**:支持文本、音视频、Markdown、JSON 等消息格式。 +- **高性能架构**:TypeScript 全栈,基于 pnpm monorepo 管理,核心逻辑分离。 +- **现代化管理**:内置 WebUI 面板,支持实时日志、密码热更、多账号管理。 +- **多适配器支持**:WebSocket (Server/Client)、HTTP (Server/Post)。 +- **数据持久化**:使用 SQLite 存储好友、群组等关系数据。 ## 快速开始 -下载预构建发布包: - -```bash -# 从 Releases 下载 zip,解压到任意目录 -./launcher.bat # Windows -``` - -或从源码开发: - -```bash -git clone https://github.com/SnowLuma/SnowLuma.git -cd SnowLuma -pnpm install -pnpm build -pnpm start -``` - -WebUI 默认监听 `5099` 端口。首次启动会在控制台打印 `initial credentials: user=admin password=<...>`,登录后请立即修改。 -若未完成首次改密就关闭进程,下次启动会自动重新生成一个新的随机密码。 - -## 工作区 - -本仓库使用 pnpm monorepo 管理,各包职责如下: - -| 包 | 说明 | -| --- | --- | -| [`@snowluma/core`](packages/core) | 核心:协议层 / Bridge / OneBot / WebUI 全部在此。 | -| [`@snowluma/sdk`](packages/sdk) | OneBot HTTP & WebSocket TypeScript SDK,发布到 npm。 | -| [`@snowluma/ui`](packages/ui) | Tailwind 4 共享组件库(shadcn 风格),发布到 npm。 | -| [`@snowluma/websocket`](packages/websocket) | OneBot WebSocket 适配器底层。 | -| [`@snowluma/proton`](packages/proton) | 编译期 protobuf 编/解码器生成器:TS interface 标注 `pb`,Vite 插件在构建时把 `protobuf_encode` / `protobuf_decode` 替换为内联 codec,零运行时反射。 | -| [`@snowluma/runtime`](packages/runtime) | 运行时清单与发布包资源。 | -| [`webui`](packages/webui) | Web 管理面板前端。 | - -## 架构 - -```mermaid -flowchart TD - A([QQ 客户端]) - B["协议层
packet pipeline · cmd 分派"] - C["Bridge 层
会话调度 · 花名册缓存 · 消息发送"] - D["OneBot 层
Event Converter · Action Handler"] - E([WS / HTTP / WebUI]) - - A --> B --> C --> D --> E -``` - -## 文档 - -- [路线图](RoadMap.md) -- [贡献指南](CONTRIBUTING.md) -- [行为准则](CODE_OF_CONDUCT.md) - -## 开发命令 - -```bash -pnpm dev # 启动 core dev server -pnpm dev:web # 启动 webui dev server -pnpm test # 运行 core 测试 -pnpm typecheck # 全仓库 type check -pnpm build:all # 构建 core + sdk + webui -``` +1. 从 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 下载最新发布包并解压。 +2. 运行 `./launcher.bat` (Windows) 或 `./launcher.sh` (Linux)。 +3. 访问 `http://localhost:5099` (初始账号 `admin`,密码见控制台输出)。 ## 鸣谢 -- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。 -- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。 +参考了 [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) 的协议定义与 [NapCatQQ](https://github.com/NapNeko/NapCatQQ) 的实现思路。 -## 贡献者 +--- -感谢每一位为 SnowLuma 提交过代码的伙伴。 +

+ +

- - Contributors - - -## Star 趋势 - - - - - - Star History Chart - - - -## 社区 - -- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe) -- Telegram:[SnowLuma-TG](https://t.me/napcatqq) -- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues) diff --git a/package.json b/package.json index 62c62bc7..27b14fe9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.9.2", + "version": "1.9.3", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/bridge/package.json b/packages/bridge/package.json index df0e8a04..4b832fd9 100644 --- a/packages/bridge/package.json +++ b/packages/bridge/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/bridge", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "description": "SnowLuma bridge — QQ NT desktop client lifecycle: hook injection (via native addon), per-PID HookSession orchestration, pipe-watcher for process discovery, and the BridgeManagerSink interface that lets the hook layer call back into a UIN-keyed session router without depending on @snowluma/core. Consumed by the top-level app entry (which constructs the BridgeManager from @snowluma/core and injects it as the sink) and by the WebUI server (read-only HookProcessInfo views).", diff --git a/packages/common/package.json b/packages/common/package.json index 0c8471dc..308f0d6a 100644 --- a/packages/common/package.json +++ b/packages/common/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/common", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "description": "SnowLuma shared infrastructure — leaf-package utilities with zero business dependencies. Logger / hex codec / log file transport / log line summariser / packet sender wire-protocol types / runtime config loader. Consumed by @snowluma/protocol, @snowluma/core, and @snowluma/onebot. Per-file subpath exports keep import sites unambiguous and let the bundler tree-shake aggressively (importing `@snowluma/common/hex` doesn't pull in `node:fs` from the logger transport).", diff --git a/packages/core/package.json b/packages/core/package.json index 4eaece12..21ffbaf2 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.9.2", + "version": "1.9.3", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", @@ -46,7 +46,6 @@ "@snowluma/protocol": "workspace:*", "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", - "@snowluma/sqlite": "workspace:*", "@snowluma/websocket": "workspace:*" }, "devDependencies": { diff --git a/packages/core/src/bridge/apis/misc.ts b/packages/core/src/bridge/apis/misc.ts index 0e78432e..bb549d61 100644 --- a/packages/core/src/bridge/apis/misc.ts +++ b/packages/core/src/bridge/apis/misc.ts @@ -9,6 +9,7 @@ import type { BridgeContext } from '../bridge-context'; import { ClickInlineKeyboardButton } from '@snowluma/protocol/oidb-services/misc/click-inline-keyboard-button'; import { SendGroupSign } from '@snowluma/protocol/oidb-services/misc/send-group-sign'; import { TranslateEnToZh } from '@snowluma/protocol/oidb-services/misc/translate-en-to-zh'; +import { RequestDbKey } from '@snowluma/protocol/oidb-services/misc/request-decrypt-key'; export class MiscApi { constructor(private readonly ctx: BridgeContext) { } @@ -75,4 +76,15 @@ export class MiscApi { sendGroupSign(groupId: number): Promise { return SendGroupSign.invoke(this.ctx, { groupId }); } + + async getDecryptKey(dbSalt: string): Promise { + const result = await RequestDbKey.invoke(this.ctx, { db_salt: dbSalt }); + if (!result.success) { + throw new Error(result.errorMsg || `Failed to get decrypt key (code: ${result.errorCode})`); + } + if (!result.dbKey) { + throw new Error('Decrypt key is empty'); + } + return result.dbKey; + } } diff --git a/packages/core/src/bridge/apis/web.ts b/packages/core/src/bridge/apis/web.ts index 6198f924..e59c144c 100644 --- a/packages/core/src/bridge/apis/web.ts +++ b/packages/core/src/bridge/apis/web.ts @@ -1,3 +1,4 @@ +import { loadBinarySource } from '@snowluma/protocol/highway/utils'; import { ForceFetchClientKey, type ClientKeyInfo as NamespaceClientKeyInfo } from '@snowluma/protocol/oidb-services/web/force-fetch-client-key'; import { GetPskey } from '@snowluma/protocol/oidb-services/web/get-pskey'; import { getGroupEssenceMsg, getGroupEssenceMsgAll, type GroupEssenceMsgRet } from '@snowluma/protocol/web/group-essence'; @@ -247,16 +248,11 @@ export class WebApi { let imgHeight = 300; if (options?.image) { - let imageBuffer: Buffer; - - if (options.image.startsWith('http://') || options.image.startsWith('https://')) { - const response = await fetch(options.image); - if (!response.ok) throw new Error(`Failed to download image: ${response.status}`); - imageBuffer = Buffer.from(await response.arrayBuffer()); - } else { - const { readFileSync } = await import('fs'); - imageBuffer = readFileSync(options.image); - } + // Route through loadBinarySource so the group-notice image download + // gets the same browser-UA + Referer-retry hardening as every other + // media fetch — and http/file/base64 source handling for free. + const loaded = await loadBinarySource(options.image, 'group-notice image'); + const imageBuffer = Buffer.from(loaded.bytes); const picInfo = await uploadGroupNoticeImage(cookieObject, imageBuffer); if (picInfo) { diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 0b7099e1..82b165a4 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -355,6 +355,12 @@ export async function initWebUI( return c.json({ list }); }); + // Live OneBot adapter health per account (listening / connected / client + // counts / last-delivery), powering the dashboard's connection card. + app.get('/api/connections', (c) => { + return c.json({ list: oneBotManager.getConnectionStatuses() }); + }); + app.get('/api/logs', (c) => { const limit = Number(c.req.query('limit') ?? 300); return c.json({ list: getRecentLogs(limit) }); diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index 87f5c6c0..a6fa17d6 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -99,3 +99,81 @@ describe('loadBinarySource maxBytes enforcement', () => { ).rejects.toThrow(/too large: 128 > 64/); }); }); + +describe('loadBinarySource HTTP header hardening', () => { + const originalFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it('sends a browser User-Agent on the first attempt, without a Referer', async () => { + const calls: Array> = []; + globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => { + calls.push((init?.headers ?? {}) as Record); + return new Response(new Uint8Array([1, 2, 3]), { status: 200 }); + }) as typeof fetch; + + await loadBinarySource('https://example.test/a.png', 'image'); + expect(calls).toHaveLength(1); + expect(calls[0]['User-Agent']).toMatch(/Mozilla\/5\.0/); + expect(calls[0]['Referer']).toBeUndefined(); + }); + + it('retries with a Referer when the first fetch fails at the network level', async () => { + // Reproduces the reported bug: an anti-bot front-end resets the + // header-less request → undici `TypeError: fetch failed`. The retry + // carries a Referer pointing at the resource itself and succeeds. + const calls: Array> = []; + globalThis.fetch = vi.fn(async (_url: unknown, init?: RequestInit) => { + calls.push((init?.headers ?? {}) as Record); + if (calls.length === 1) throw new TypeError('fetch failed'); + return new Response(new Uint8Array([9, 9]), { status: 200 }); + }) as typeof fetch; + + const loaded = await loadBinarySource('https://img.example.test/x.gif', 'image'); + expect(Array.from(loaded.bytes)).toEqual([9, 9]); + expect(calls).toHaveLength(2); + expect(calls[0]['Referer']).toBeUndefined(); + expect(calls[1]['Referer']).toBe('https://img.example.test/x.gif'); + }); + + it('retries with a Referer on a 403 (anti-hotlink)', async () => { + let n = 0; + globalThis.fetch = vi.fn(async () => { + n++; + if (n === 1) return new Response(new Uint8Array(0), { status: 403 }); + return new Response(new Uint8Array([7]), { status: 200 }); + }) as typeof fetch; + + const loaded = await loadBinarySource('https://cdn.example.test/y.jpg', 'image'); + expect(Array.from(loaded.bytes)).toEqual([7]); + expect(n).toBe(2); + }); + + it('does not retry a size-limit rejection (deterministic, no second download)', async () => { + const fetchMock = vi.fn(async () => new Response(new Uint8Array(0), { + status: 200, + headers: { 'content-length': String(10 * 1024 * 1024) }, + })); + globalThis.fetch = fetchMock as typeof fetch; + + await expect( + loadBinarySource('https://example.test/big.bin', 'image', 1024), + ).rejects.toThrow(/too large/); + expect(fetchMock).toHaveBeenCalledTimes(1); + }); + + it('surfaces the first error when the Referer retry also fails', async () => { + let n = 0; + globalThis.fetch = vi.fn(async () => { + n++; + throw new TypeError('fetch failed'); + }) as typeof fetch; + + await expect( + loadBinarySource('https://example.test/z.png', 'image'), + ).rejects.toThrow(/fetch failed/); + expect(n).toBe(2); + }); +}); diff --git a/packages/core/vite.config.ts b/packages/core/vite.config.ts index f7cd92a4..90eb7396 100644 --- a/packages/core/vite.config.ts +++ b/packages/core/vite.config.ts @@ -1,10 +1,10 @@ -import { defineConfig, PluginOption, UserConfig } from 'vite'; -import { fileURLToPath } from 'url'; -import fs from 'fs'; -import path from 'path'; -import { builtinModules } from 'module'; -import cp from 'vite-plugin-cp'; import protobufVitePlugin from '@snowluma/proton/vite'; +import fs from 'fs'; +import { builtinModules } from 'module'; +import path from 'path'; +import { fileURLToPath } from 'url'; +import { defineConfig, PluginOption, UserConfig } from 'vite'; +import cp from 'vite-plugin-cp'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); const repoRoot = path.resolve(__dirname, '..', '..'); @@ -20,12 +20,16 @@ const rootPkg = JSON.parse( // vite-plugin-cp consumes globs through globby; on Windows we must use POSIX-style separators. const toPosix = (p: string) => p.replace(/\\/g, '/'); -// `@snowluma/websocket` and `@snowluma/sqlite` are bundled — they're -// in-tree TS workspace wrappers that route their native `.node` -// addons through `dist/native/`. Only Node builtins stay external; -// the actual `better-sqlite3` JS wrapper is pulled in via the -// `@snowluma/sqlite` re-export and bundled into `index.mjs`. -const external: string[] = []; +// `@snowluma/websocket` is bundled — it's an +// in-tree TS workspace wrapper that routes its native `.node` +// addon through `dist/native/`. Only Node builtins stay external. +// +// `node:sqlite` is an experimental builtin that Node 22.x lines don't +// list in `builtinModules`, so the `nodeModules` sweep below misses it. +// Externalise it explicitly — otherwise Vite bundles it and swaps in a +// browser shell, crashing the hook with `DatabaseSync is not a +// constructor` (the bug PR #68 set out to fix). +const external: string[] = ['node:sqlite', 'sqlite']; const nodeModules = [...builtinModules, ...builtinModules.map((m) => `node:${m}`)].flat(); @@ -46,20 +50,8 @@ const runtimeDistFiles = ['package.json', // Native binaries shipped for the selected target: // * `snowluma-*.{dll,node,so}` – NTQQ hook (Windows + Linux). // * `websocket-*.node` – RFC 6455 framing/mask addon (all platforms). -// * `better-sqlite3-v-*.node` – SQLite native binding consumed -// by @snowluma/sqlite. Two ABIs -// vendored side-by-side -// (v127 = Node 22 LTS, v137 = -// Node 24) so the runtime can -// pick whichever matches the -// host's `process.versions.modules`. -// Vendored via -// `tools/fetch-sqlite-prebuilts.mjs` -// from WiseLibs's prebuild releases. -const SQLITE_ABIS = ['v127', 'v137']; const nativeFiles = [ `websocket-${targetTriple}.node`, - ...SQLITE_ABIS.map((abi) => `better-sqlite3-${abi}-${targetTriple}.node`), ...(targetPlatform === 'win32' ? [`snowluma-${targetTriple}.dll`, `snowluma-${targetTriple}.node`] : []), diff --git a/packages/onebot/package.json b/packages/onebot/package.json index 13120b2e..e0812abc 100644 --- a/packages/onebot/package.json +++ b/packages/onebot/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/onebot", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "description": "SnowLuma OneBot v11 adapter — the protocol translation layer that maps the public OneBot vocabulary (HTTP / WebSocket actions, message segments, post events) onto @snowluma/core's typed Api hub (`bridge.apis..method()`). Owns network adapters (HTTP server / HTTP client / WS server / WS client), the registered action handlers, the receive-side event→OneBot converter, message-id hashing, message store (SQLite-backed event history), media store, and the OneBot instance + manager that ties one OneBotConfig to one Bridge. Per-file subpath exports mirror the legacy `core/src/onebot/*` layout 1:1 so the previous `import { … } from '../onebot/'` collapses to `import { … } from '@snowluma/onebot/'`.", @@ -91,7 +91,6 @@ "@snowluma/proto-defs": "workspace:*", "@snowluma/proton": "workspace:*", "@snowluma/protocol": "workspace:*", - "@snowluma/sqlite": "workspace:*", "@snowluma/websocket": "workspace:*" }, "devDependencies": { diff --git a/packages/onebot/src/actions/extended.ts b/packages/onebot/src/actions/extended.ts index cb39ba49..2a7ad844 100644 --- a/packages/onebot/src/actions/extended.ts +++ b/packages/onebot/src/actions/extended.ts @@ -1,3 +1,4 @@ +import { readFile } from 'node:fs/promises'; import type { ApiActionContext, ApiHandler } from '../api-handler'; import { asBoolean, asMessage, asNumber, asString } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; @@ -1175,6 +1176,35 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); } }); + + h.registerAction('request_decrypt_key', async (params) => { + const dbPath = asString(params.db_path); + if (!dbPath) { + return failedResponse(RETCODE.BAD_REQUEST, 'db_path is required'); + } + + try { + const buffer = Buffer.alloc(128); + const fileHandle = await readFile(dbPath); + + if (fileHandle.length < 0xaf) { + return failedResponse(RETCODE.ACTION_FAILED, 'Database file too short'); + } + + fileHandle.copy(buffer, 0, 0x2f, 0xaf); + const dbSalt = buffer.toString('utf8'); + + if (!/^[0-9a-fA-F]{128}$/.test(dbSalt)) { + return failedResponse(RETCODE.ACTION_FAILED, 'Invalid db_salt: not a valid 128-character hex string'); + } + + const dbKey = await ctx.bridge.apis.misc.getDecryptKey(dbSalt.toLowerCase()); + + return okResponse({ db_key: dbKey }); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } + }); } function hexToBytes(hex: string): Uint8Array { diff --git a/packages/onebot/src/actions/message.ts b/packages/onebot/src/actions/message.ts index da45e939..b2fbe754 100644 --- a/packages/onebot/src/actions/message.ts +++ b/packages/onebot/src/actions/message.ts @@ -3,6 +3,35 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asNumber, asString, asBoolean, asMessage } from '../api-handler'; import { RETCODE, failedResponse, okResponse } from '../types'; +/** + * Re-sign image URLs in a stored message event at read time. `get_msg` + * returns a copy persisted when the message first arrived, and image rkeys + * expire — so walk the segment array and refresh each image URL through + * `ctx.getImageInfo`, which mints a current rkey. Best-effort and in-place; + * `findEvent` returns a fresh parse, so mutating the array is safe. + */ +async function refreshStoredImageUrls(event: JsonObject, ctx: ApiActionContext): Promise { + const segments = event.message; + if (!Array.isArray(segments)) return; + for (const seg of segments) { + if (!seg || typeof seg !== 'object') continue; + const segment = seg as { type?: unknown; data?: Record }; + if (segment.type !== 'image') continue; + const data = segment.data; + if (!data || typeof data !== 'object') continue; + const file = typeof data.file === 'string' ? data.file + : typeof data.file_id === 'string' ? data.file_id + : ''; + if (!file) continue; + try { + const info = await ctx.getImageInfo(file); + if (info && typeof info.url === 'string' && info.url) data.url = info.url; + } catch { + // Keep the stored URL when the refresh fails. + } + } +} + export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('send_msg', async (params) => { const messageType = asString(params.message_type); @@ -77,6 +106,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { delete result.post_type; delete result.self_id; result.real_id = (result.message_id ?? messageId) as JsonValue; + await refreshStoredImageUrls(result, ctx); return okResponse(result); }); diff --git a/packages/onebot/src/event-converter/index.ts b/packages/onebot/src/event-converter/index.ts index 16f13f34..0cd17552 100644 --- a/packages/onebot/src/event-converter/index.ts +++ b/packages/onebot/src/event-converter/index.ts @@ -25,7 +25,7 @@ import { } from './to-request'; import { elementsToJson } from './to-segment'; -export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string; +export type ImageUrlResolver = (element: MessageElement, isGroup: boolean) => string | Promise; export type MediaUrlResolver = (element: MessageElement, isGroup: boolean, sessionId: number) => Promise; export type MessageIdResolver = (isGroup: boolean, sessionId: number, sequence: number, eventName: string) => number; diff --git a/packages/onebot/src/event-converter/to-segment.ts b/packages/onebot/src/event-converter/to-segment.ts index f7a33d7c..c8d289c9 100644 --- a/packages/onebot/src/event-converter/to-segment.ts +++ b/packages/onebot/src/event-converter/to-segment.ts @@ -45,7 +45,7 @@ async function elementToSegment( } if (element.type === 'image') { - const url = imageUrlResolver ? imageUrlResolver(element, isGroup) : (element.imageUrl ?? ''); + const url = imageUrlResolver ? await imageUrlResolver(element, isGroup) : (element.imageUrl ?? ''); const data: JsonObject = { url, file: element.fileId ?? '', diff --git a/packages/onebot/src/instance-context.ts b/packages/onebot/src/instance-context.ts index e32fecfc..50ccb3d3 100644 --- a/packages/onebot/src/instance-context.ts +++ b/packages/onebot/src/instance-context.ts @@ -114,7 +114,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { complete: cachedCount >= serverCount, }; }, - getImageInfo: (file) => getCachedImageInfo(mediaStore, file), + getImageInfo: (file) => getCachedImageInfo(mediaStore, file, ref.converterCtx.imageUrlResolver), getRecordInfo: (file) => getCachedRecordInfo(bridge, mediaStore, file), }; } diff --git a/packages/onebot/src/instance-rkey.ts b/packages/onebot/src/instance-rkey.ts index b713537c..73684089 100644 --- a/packages/onebot/src/instance-rkey.ts +++ b/packages/onebot/src/instance-rkey.ts @@ -15,6 +15,10 @@ interface CachedRKey { const RKEY_REFRESH_SKEW = 60; const RKEY_REFRESH_COOLDOWN = 30; +// Upper bound on how long URL resolution may block on a refresh round-trip. +// A stuck packet send must never wedge message conversion — past this we +// fall back to whatever the cache holds (possibly nothing). +const RKEY_REFRESH_TIMEOUT_MS = 5000; const PRIVATE_IMAGE_RKEY_TYPE = 10; const GROUP_IMAGE_RKEY_TYPE = 20; const PRIVATE_VIDEO_RKEY_TYPE = 12; @@ -26,31 +30,28 @@ const FALLBACK_IMAGE_RKEY_TYPE = 2; export class RKeyCache { private cache = new Map(); private lastRefreshAttempt = 0; + private refreshInflight: Promise | null = null; 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)); - }, + this.ensureFresh(bridge).then( + () => log.info('rkeys loaded: UIN=%s count=%d', uin, this.cache.size), + (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 { + async resolveImageUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise { const url = element.imageUrl ?? ''; if (!urlNeedsRKey(url)) return url; - const rkey = this.findRKey(bridge, isGroup); + const rkey = await this.findRKey(bridge, isGroup); if (!rkey) return url; const cleanRKey = stripRKeyPrefix(rkey); const separator = url.includes('?') ? '&rkey=' : '?rkey='; return url + separator + encodeURIComponent(cleanRKey); } - resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): string { + + async resolveMediaUrl(bridge: BridgeInterface, element: MessageElement, isGroup: boolean): Promise { const url = element.url ?? ''; if (!url || !urlNeedsRKey(url)) return url; @@ -65,7 +66,7 @@ export class RKeyCache { primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; } - const rkey = this.findRKeyForType(bridge, primaryType); + const rkey = await this.findRKeyForType(bridge, primaryType); if (!rkey) return url; const cleanRKey = stripRKeyPrefix(rkey); @@ -89,32 +90,66 @@ export class RKeyCache { } } - private findRKey(bridge: BridgeInterface, isGroup: boolean): string | null { + private findRKey(bridge: BridgeInterface, isGroup: boolean): Promise { const primaryType = isGroup ? GROUP_IMAGE_RKEY_TYPE : PRIVATE_IMAGE_RKEY_TYPE; return this.findRKeyForType(bridge, primaryType); } - private findRKeyForType(bridge: BridgeInterface, primaryType: number): string | null { + /** Pull a still-valid rkey out of the cache, or null if missing/expiring. */ + private findInCache(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; }; + return tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); + } - let result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); - if (result) return result; - if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return null; - this.lastRefreshAttempt = now; - bridge.apis.contacts.fetchDownloadRKeys().then( - (rkeys) => this.updateCache(rkeys), - () => { /* ignore */ }, - ); + private async findRKeyForType(bridge: BridgeInterface, primaryType: number): Promise { + const cached = this.findInCache(primaryType); + if (cached) return cached; - result = tryFind(primaryType) ?? tryFind(FALLBACK_IMAGE_RKEY_TYPE); - return result; + // Cache miss or inside the expiry skew: block on a fresh fetch rather + // than hand back a URL with a stale/absent rkey — the CDN rejects those + // with `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Mirrors NapCat's + // getImageUrl path, which does `if (isExpired()) await refreshRkey()` + // before building the URL instead of refreshing in the background. + await this.ensureFresh(bridge); + return this.findInCache(primaryType); + } + + /** + * Refresh the rkey cache via OIDB 0x9067_202, coalescing concurrent + * callers onto one in-flight request and backing off for + * RKEY_REFRESH_COOLDOWN after a failed attempt so a persistently + * unreachable server isn't hammered once per inbound image. The await is + * bounded by RKEY_REFRESH_TIMEOUT_MS. + */ + private async ensureFresh(bridge: BridgeInterface): Promise { + if (!this.refreshInflight) { + const now = Math.floor(Date.now() / 1000); + if (now - this.lastRefreshAttempt < RKEY_REFRESH_COOLDOWN) return; + this.lastRefreshAttempt = now; + this.refreshInflight = bridge.apis.contacts.fetchDownloadRKeys() + .then((rkeys) => { this.updateCache(rkeys); }) + .catch((err) => { + log.warn('rkey refresh failed: %s', err instanceof Error ? err.message : String(err)); + }) + .finally(() => { this.refreshInflight = null; }); + } + + const inflight = this.refreshInflight; + if (!inflight) return; + + let timer: ReturnType | undefined; + const timeout = new Promise((resolve) => { timer = setTimeout(resolve, RKEY_REFRESH_TIMEOUT_MS); }); + try { + await Promise.race([inflight, timeout]); + } finally { + if (timer) clearTimeout(timer); + } } } diff --git a/packages/onebot/src/instance.ts b/packages/onebot/src/instance.ts index 81c5a286..2b6eedee 100644 --- a/packages/onebot/src/instance.ts +++ b/packages/onebot/src/instance.ts @@ -18,6 +18,7 @@ import { OneBotNetworkManager, WsClientAdapter, WsServerAdapter, + type AdapterStatus, type NetworkAdapterContext, } from './network'; import { ReactionStore } from './reaction-store'; @@ -46,6 +47,11 @@ export class OneBotInstance { get nickname(): string { return this.bridge.identity.nickname; } + /** Live status of this account's OneBot network adapters. */ + getConnectionStatuses(): AdapterStatus[] { + return this.networkManager.describeStatuses(); + } + constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) { this.uin = uin; this.bridge = bridge; diff --git a/packages/onebot/src/manager.ts b/packages/onebot/src/manager.ts index ed52586a..b4395d36 100644 --- a/packages/onebot/src/manager.ts +++ b/packages/onebot/src/manager.ts @@ -3,10 +3,18 @@ import type { BridgeInterface } from '@snowluma/core/bridge-interface'; import type { BridgeManager } from '@snowluma/core/manager'; import { loadOneBotConfig } from './config'; import { OneBotInstance } from './instance'; +import type { AdapterStatus } from './network'; const log = createLogger('OneBot'); const VERBOSE_WARMUP = process.env.SNOWLUMA_VERBOSE_WARMUP === '1'; +/** Per-account OneBot connection health, surfaced to the WebUI dashboard. */ +export interface AccountConnections { + uin: string; + nickname: string; + adapters: AdapterStatus[]; +} + export class OneBotManager { private readonly instances = new Map(); @@ -28,6 +36,15 @@ export class OneBotManager { return [...this.instances.values()]; } + /** Live OneBot adapter status for every account, for the WebUI dashboard. */ + getConnectionStatuses(): AccountConnections[] { + return this.getInstances().map((i) => ({ + uin: i.uin, + nickname: i.nickname, + adapters: i.getConnectionStatuses(), + })); + } + reloadConfig(uin: string): boolean { const instance = this.instances.get(uin); if (!instance) return false; diff --git a/packages/onebot/src/media-store.ts b/packages/onebot/src/media-store.ts index b9f3a0d8..fa475747 100644 --- a/packages/onebot/src/media-store.ts +++ b/packages/onebot/src/media-store.ts @@ -1,6 +1,6 @@ import type { MessageElement } from '@snowluma/protocol/events'; -import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import fs from 'fs'; +import { DatabaseSync, type StatementSync } from 'node:sqlite'; import path from 'path'; export interface CachedImage { @@ -62,17 +62,17 @@ const TYPE_VIDEO = 'video'; const DEFAULT_KEEP_ENTRIES = 4096; export class MediaStore { - private readonly db: DatabaseType; + private readonly db: DatabaseSync; private readonly maxEntriesPerType: number; // Prepared statements (pay the parsing cost once at startup). - private readonly upsertEntry: Statement; - private readonly upsertKey: Statement; - private readonly findEntryByKey: Statement; - private readonly findEntryByPrimary: Statement; - private readonly evictByType: Statement; - private readonly purgeOrphanKeys: Statement; - private readonly countByType: Statement; + 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); @@ -80,9 +80,9 @@ export class MediaStore { const dir = path.dirname(dbPath); fs.mkdirSync(dir, { recursive: true }); - this.db = new Database(dbPath); - this.db.pragma('journal_mode = WAL'); - this.db.pragma('synchronous = NORMAL'); + 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( diff --git a/packages/onebot/src/message-store.ts b/packages/onebot/src/message-store.ts index c30a3946..5b87f7f1 100644 --- a/packages/onebot/src/message-store.ts +++ b/packages/onebot/src/message-store.ts @@ -1,18 +1,18 @@ -import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import fs from 'fs'; +import { DatabaseSync, type StatementSync } from 'node:sqlite'; import path from 'path'; import type { JsonObject, MessageMeta } from './types'; export class MessageStore { - private readonly db: DatabaseType; - private readonly stmtStoreEvent: Statement; - private readonly stmtStoreMeta: Statement; - private readonly stmtFindEvent: Statement; - private readonly stmtFindMeta: Statement; - private readonly stmtResolveReplyGroup: Statement; - private readonly stmtResolveReplyPrivate: Statement; - private readonly stmtListEventsAnchored: Statement; - private readonly stmtListEventsLatest: Statement; + private readonly db: DatabaseSync; + private readonly stmtStoreEvent: StatementSync; + private readonly stmtStoreMeta: StatementSync; + private readonly stmtFindEvent: StatementSync; + private readonly stmtFindMeta: StatementSync; + private readonly stmtResolveReplyGroup: StatementSync; + private readonly stmtResolveReplyPrivate: StatementSync; + private readonly stmtListEventsAnchored: StatementSync; + private readonly stmtListEventsLatest: StatementSync; constructor(dbPath: string) { const dir = path.dirname(dbPath); @@ -20,9 +20,9 @@ export class MessageStore { // Replace .json extension with .db if present const finalPath = dbPath.replace(/\.json$/, '.db'); - this.db = new Database(finalPath); - this.db.pragma('journal_mode = WAL'); - this.db.pragma('synchronous = NORMAL'); + this.db = new DatabaseSync(finalPath); + this.db.exec('PRAGMA journal_mode = WAL'); + this.db.exec('PRAGMA synchronous = NORMAL'); this.initSchema(); // Prepare once. Statements survive for the lifetime of the diff --git a/packages/onebot/src/modules/media-actions.ts b/packages/onebot/src/modules/media-actions.ts index 08ee1fe5..156885b2 100644 --- a/packages/onebot/src/modules/media-actions.ts +++ b/packages/onebot/src/modules/media-actions.ts @@ -1,5 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import type { BridgeInterface } from '@snowluma/core/bridge-interface'; +import type { MessageElement } from '@snowluma/protocol/events'; +import type { ImageUrlResolver } from '../event-converter'; import type { MediaStore } from '../media-store'; import type { JsonObject } from '../types'; @@ -8,10 +10,29 @@ const log = createLogger('OneBot'); export async function getImageInfo( mediaStore: MediaStore, file: string, + imageUrlResolver?: ImageUrlResolver | null, ): Promise { const cached = mediaStore.findImage(file); if (!cached) return null; - const url = cached.url || cached.imageUrl || ''; + + let url = cached.url || cached.imageUrl || ''; + + // Re-sign with a current rkey at lookup time. The stored `url` was signed + // when the message first arrived and its rkey may have since expired — the + // CDN then rejects the download with + // `{"retcode":-5503010,"retmsg":"invalid rkey"}`. Resolving from the raw + // (unsigned) `imageUrl` mints a fresh rkey, mirroring NapCat which + // re-signs on every getImageUrl call instead of handing back a baked URL. + if (imageUrlResolver && cached.imageUrl) { + try { + const element: MessageElement = { type: 'image', imageUrl: cached.imageUrl, subType: cached.subType }; + const fresh = await imageUrlResolver(element, cached.isGroup); + if (fresh) url = fresh; + } catch { + // Best-effort: fall back to the stored URL on any resolver failure. + } + } + return { file: url || cached.file, url, diff --git a/packages/onebot/src/network/adapter.ts b/packages/onebot/src/network/adapter.ts index 8162707e..4df2cc32 100644 --- a/packages/onebot/src/network/adapter.ts +++ b/packages/onebot/src/network/adapter.ts @@ -16,6 +16,19 @@ export enum NetworkReloadType { Opened = 3, } +export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled'; + +/** Live runtime status of a single network adapter, surfaced to the WebUI + * dashboard (and the per-node config cards) so the gateway's own + * connection health is visible. `detail` is a short human string, e.g. + * "3 个客户端" / "重连中" / "上次推送失败 14:53:01". */ +export interface AdapterStatus { + name: string; + kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient'; + status: AdapterStatusLevel; + detail: string; +} + export abstract class IOneBotNetworkAdapter { readonly name: string; protected config: C; @@ -37,4 +50,7 @@ export abstract class IOneBotNetworkAdapter { abstract reload(config: C): NetworkReloadType | Promise; abstract onEvent(event: JsonObject, payload: DispatchPayload): void | Promise; + + /** Report live connection health for the WebUI dashboard. */ + abstract describeStatus(): AdapterStatus; } diff --git a/packages/onebot/src/network/http-post-adapter.ts b/packages/onebot/src/network/http-post-adapter.ts index 9f47844f..1f650de1 100644 --- a/packages/onebot/src/network/http-post-adapter.ts +++ b/packages/onebot/src/network/http-post-adapter.ts @@ -6,7 +6,7 @@ import { type EventReportOptions, } from '../event-filter'; import type { HttpClientNetwork, JsonObject } from '../types'; -import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; +import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter'; import { executeQuickOperation } from './quick-operation'; const moduleLog = createLogger('OneBot.POST'); @@ -15,6 +15,7 @@ const DEFAULT_TIMEOUT_MS = 5000; export class HttpPostAdapter extends IOneBotNetworkAdapter { private options: EventReportOptions; private signature_: string; + private lastDelivery: { at: number; ok: boolean } | null = null; private readonly log: Logger; constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) { @@ -39,6 +40,15 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { this.isEnabled = false; } + override describeStatus(): AdapterStatus { + if (!this.isEnabled) return { name: this.name, kind: 'httpClient', status: 'disabled', detail: '未启用' }; + if (!this.lastDelivery) return { name: this.name, kind: 'httpClient', status: 'ok', detail: '已启用' }; + const at = new Date(this.lastDelivery.at).toTimeString().slice(0, 8); + return this.lastDelivery.ok + ? { name: this.name, kind: 'httpClient', status: 'ok', detail: `上次推送成功 ${at}` } + : { name: this.name, kind: 'httpClient', status: 'warn', detail: `上次推送失败 ${at}` }; + } + async reload(next: HttpClientNetwork): Promise { const wasEnabled = this.isEnabled; const willEnable = next.enabled !== false && !!next.url; @@ -98,6 +108,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { signal: AbortSignal.timeout(timeoutMs), }); if (response.ok) { + this.lastDelivery = { at: Date.now(), ok: true }; const contentType = response.headers.get('content-type') ?? ''; if (contentType.includes('application/json')) { const body = await response.text(); @@ -106,9 +117,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { } } } else { + this.lastDelivery = { at: Date.now(), ok: false }; this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status); } } catch (error) { + this.lastDelivery = { at: Date.now(), ok: false }; if (this.isEnabled) { this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error)); } diff --git a/packages/onebot/src/network/http-server-adapter.ts b/packages/onebot/src/network/http-server-adapter.ts index 0ef8084b..0374234f 100644 --- a/packages/onebot/src/network/http-server-adapter.ts +++ b/packages/onebot/src/network/http-server-adapter.ts @@ -7,13 +7,14 @@ import { } from 'http'; import type { DispatchPayload } from '../event-filter'; import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; -import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; +import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter'; import { isAuthorized, normalizePath } from './utils'; const moduleLog = createLogger('OneBot.HTTP'); export class HttpServerAdapter extends IOneBotNetworkAdapter { private server: Server | null = null; + private listening = false; private readonly log: Logger; constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) { @@ -36,10 +37,17 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter close(): void { if (!this.isEnabled && !this.server) return; this.isEnabled = false; + this.listening = false; this.server?.close(); this.server = null; } + override describeStatus(): AdapterStatus { + if (!this.isEnabled) return { name: this.name, kind: 'httpServer', status: 'disabled', detail: '未启用' }; + if (!this.listening) return { name: this.name, kind: 'httpServer', status: 'down', detail: '未监听(端口被占用?)' }; + return { name: this.name, kind: 'httpServer', status: 'ok', detail: '监听中' }; + } + async reload(next: HttpServerNetwork): Promise { const prevSig = bindingSignature(this.config); const wasEnabled = this.isEnabled; @@ -76,6 +84,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter this.server = server; server.on('listening', () => { + this.listening = true; this.log.success( '[%s] listening %s:%d%s', this.name, @@ -85,6 +94,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter ); }); server.on('error', (err) => { + this.listening = false; this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); }); diff --git a/packages/onebot/src/network/index.ts b/packages/onebot/src/network/index.ts index 0e5aa631..541f7a41 100644 --- a/packages/onebot/src/network/index.ts +++ b/packages/onebot/src/network/index.ts @@ -1,4 +1,10 @@ -export { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; +export { + IOneBotNetworkAdapter, + NetworkReloadType, + type AdapterStatus, + type AdapterStatusLevel, + type NetworkAdapterContext, +} from './adapter'; export { HttpPostAdapter } from './http-post-adapter'; export { HttpServerAdapter } from './http-server-adapter'; export { OneBotNetworkManager } from './network-manager'; diff --git a/packages/onebot/src/network/network-manager.ts b/packages/onebot/src/network/network-manager.ts index 8edab3c5..7b3eb226 100644 --- a/packages/onebot/src/network/network-manager.ts +++ b/packages/onebot/src/network/network-manager.ts @@ -1,7 +1,7 @@ import { createLogger } from '@snowluma/common/logger'; import { buildDispatchPayload } from '../event-filter'; import type { JsonObject, NetworkBase } from '../types'; -import { IOneBotNetworkAdapter } from './adapter'; +import { IOneBotNetworkAdapter, type AdapterStatus } from './adapter'; const log = createLogger('OneBot.Network'); @@ -30,6 +30,11 @@ export class OneBotNetworkManager { list(): AnyAdapter[] { return [...this.adapters.values()]; } + /** Live status of every registered adapter, for the WebUI dashboard. */ + describeStatuses(): AdapterStatus[] { + return this.list().map((a) => a.describeStatus()); + } + hasActiveAdapters(): boolean { for (const a of this.adapters.values()) if (a.isActive) return true; return false; diff --git a/packages/onebot/src/network/ws-client-adapter.ts b/packages/onebot/src/network/ws-client-adapter.ts index 5b0b11ff..bc085bf8 100644 --- a/packages/onebot/src/network/ws-client-adapter.ts +++ b/packages/onebot/src/network/ws-client-adapter.ts @@ -8,7 +8,7 @@ import { type EventReportOptions, } from '../event-filter'; import type { JsonObject, WsClientNetwork, WsRole } from '../types'; -import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; +import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter'; import { rawDataToString, safeClose, safeSend } from './utils'; const moduleLog = createLogger('OneBot.WS-Client'); @@ -16,6 +16,7 @@ const DEFAULT_RECONNECT_INTERVAL_MS = 5000; export class WsClientAdapter extends IOneBotNetworkAdapter { private socket: WebSocket | null = null; + private connected = false; private reconnectTimer: NodeJS.Timeout | null = null; private options: EventReportOptions; private role: WsRole; @@ -46,6 +47,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { close(): void { this.explicitlyClosed = true; this.isEnabled = false; + this.connected = false; this.cancelReconnect(); if (this.socket) { safeClose(this.socket); @@ -53,6 +55,12 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { } } + override describeStatus(): AdapterStatus { + if (!this.isEnabled) return { name: this.name, kind: 'wsClient', status: 'disabled', detail: '未启用' }; + if (this.connected) return { name: this.name, kind: 'wsClient', status: 'ok', detail: '已连接' }; + return { name: this.name, kind: 'wsClient', status: 'warn', detail: this.reconnectTimer ? '重连中' : '连接中' }; + } + async reload(next: WsClientNetwork): Promise { const prevSig = bindingSignature(this.config); const wasEnabled = this.isEnabled; @@ -108,6 +116,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { this.socket = socket; socket.on('open', () => { + this.connected = true; this.log.info('[%s] connected %s', this.name, this.config.url); this.sendBootstrapMetaEvents(socket); }); @@ -120,6 +129,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { socket.on('close', () => { this.socket = null; + this.connected = false; if (this.explicitlyClosed || !this.isEnabled) return; this.scheduleReconnect(); }); diff --git a/packages/onebot/src/network/ws-server-adapter.ts b/packages/onebot/src/network/ws-server-adapter.ts index 6368fa99..1abb5c80 100644 --- a/packages/onebot/src/network/ws-server-adapter.ts +++ b/packages/onebot/src/network/ws-server-adapter.ts @@ -9,7 +9,7 @@ import { type EventReportOptions, } from '../event-filter'; import type { JsonObject, WsRole, WsServerNetwork } from '../types'; -import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; +import { IOneBotNetworkAdapter, NetworkReloadType, type AdapterStatus, type NetworkAdapterContext } from './adapter'; import { isAuthorized, normalizePath, parseRequestPath, rawDataToString, safeClose, safeSend } from './utils'; const moduleLog = createLogger('OneBot.WS-Server'); @@ -22,6 +22,7 @@ interface ForwardConn { export class WsServerAdapter extends IOneBotNetworkAdapter { private wss: WebSocketServer | null = null; + private listening = false; private connections = new Map(); private options: EventReportOptions; private readonly log: Logger; @@ -57,12 +58,19 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { } this.isEnabled = false; + this.listening = false; for (const ws of [...this.connections.keys()]) safeClose(ws); this.connections.clear(); this.wss?.close(); this.wss = null; } + override describeStatus(): AdapterStatus { + if (!this.isEnabled) return { name: this.name, kind: 'wsServer', status: 'disabled', detail: '未启用' }; + if (!this.listening) return { name: this.name, kind: 'wsServer', status: 'down', detail: '未监听(端口被占用?)' }; + return { name: this.name, kind: 'wsServer', status: 'ok', detail: `${this.connections.size} 个客户端` }; + } + async reload(next: WsServerNetwork): Promise { const prevSig = bindingSignature(this.config); const wasEnabled = this.isEnabled; @@ -111,6 +119,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.wss = wss; wss.on('listening', () => { + this.listening = true; this.log.success( '[%s] listening %s:%d%s', this.name, @@ -121,6 +130,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { }); wss.on('error', (err: Error) => { + this.listening = false; this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); }); diff --git a/packages/onebot/src/reaction-store.ts b/packages/onebot/src/reaction-store.ts index c1e05c59..388b6715 100644 --- a/packages/onebot/src/reaction-store.ts +++ b/packages/onebot/src/reaction-store.ts @@ -1,21 +1,21 @@ -import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; import fs from 'fs'; +import { DatabaseSync, type StatementSync } from 'node:sqlite'; import path from 'path'; export class ReactionStore { - private readonly db: DatabaseType; - private readonly stmtUpsert: Statement; - private readonly stmtRemove: Statement; - private readonly stmtList: Statement; - private readonly stmtCount: Statement; - private readonly stmtCountByEmoji: Statement; + private readonly db: DatabaseSync; + private readonly stmtUpsert: StatementSync; + private readonly stmtRemove: StatementSync; + private readonly stmtList: StatementSync; + private readonly stmtCount: StatementSync; + private readonly stmtCountByEmoji: StatementSync; constructor(dbPath: string) { const dir = path.dirname(dbPath); fs.mkdirSync(dir, { recursive: true }); - this.db = new Database(dbPath); - this.db.pragma('journal_mode = WAL'); - this.db.pragma('synchronous = NORMAL'); + this.db = new DatabaseSync(dbPath); + this.db.exec('PRAGMA journal_mode = WAL'); + this.db.exec('PRAGMA synchronous = NORMAL'); this.initSchema(); this.stmtUpsert = this.db.prepare( diff --git a/packages/onebot/tests/instance-rkey.test.ts b/packages/onebot/tests/instance-rkey.test.ts new file mode 100644 index 00000000..28513091 --- /dev/null +++ b/packages/onebot/tests/instance-rkey.test.ts @@ -0,0 +1,94 @@ +import { describe, it, expect, vi } from 'vitest'; +import { RKeyCache } from '../src/instance-rkey'; +import type { MessageElement } from '@snowluma/protocol/events'; + +// The screenshot URL: a raw QQ-NT multimedia download link with no rkey yet. +const NT_IMAGE_URL = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC'; +const GROUP_IMAGE_TYPE = 20; +const PRIVATE_IMAGE_TYPE = 10; + +function nowSec(): number { + return Math.floor(Date.now() / 1000); +} + +function makeBridge(fetchImpl: () => Promise) { + const fetchDownloadRKeys = vi.fn(fetchImpl); + return { bridge: { apis: { contacts: { fetchDownloadRKeys } } }, fetchDownloadRKeys }; +} + +function freshGroupRkey(value = 'GROUPKEY') { + return [{ rkey: value, type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }]; +} + +function imageEl(): MessageElement { + return { type: 'image', imageUrl: NT_IMAGE_URL }; +} + +describe('RKeyCache.resolveImageUrl', () => { + it('awaits a refresh on a cold cache and appends the rkey', async () => { + const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey()); + const cache = new RKeyCache(); + + const url = await cache.resolveImageUrl(bridge as never, imageEl(), true); + + expect(url).toBe(`${NT_IMAGE_URL}&rkey=GROUPKEY`); + expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1); + }); + + it('coalesces concurrent cold-cache lookups into a single fetch', async () => { + const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey()); + const cache = new RKeyCache(); + + const urls = await Promise.all([ + cache.resolveImageUrl(bridge as never, imageEl(), true), + cache.resolveImageUrl(bridge as never, imageEl(), true), + cache.resolveImageUrl(bridge as never, imageEl(), true), + ]); + + expect(urls).toEqual(Array(3).fill(`${NT_IMAGE_URL}&rkey=GROUPKEY`)); + expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1); + }); + + it('serves a still-valid rkey from cache without re-fetching', async () => { + const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey()); + const cache = new RKeyCache(); + + await cache.resolveImageUrl(bridge as never, imageEl(), true); + await cache.resolveImageUrl(bridge as never, imageEl(), true); + + expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1); + }); + + it('falls back to the unsigned URL (no throw) when the refresh fails', async () => { + const { bridge, fetchDownloadRKeys } = makeBridge(async () => { throw new Error('oidb down'); }); + const cache = new RKeyCache(); + + const url = await cache.resolveImageUrl(bridge as never, imageEl(), true); + + expect(url).toBe(NT_IMAGE_URL); + expect(fetchDownloadRKeys).toHaveBeenCalledTimes(1); + }); + + it('uses the private rkey type for c2c images', async () => { + const { bridge } = makeBridge(async () => [ + { rkey: 'PRIVATEKEY', type: PRIVATE_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }, + { rkey: 'GROUPKEY', type: GROUP_IMAGE_TYPE, ttlSeconds: 3600, createTime: nowSec(), storeId: 0 }, + ]); + const cache = new RKeyCache(); + + const url = await cache.resolveImageUrl(bridge as never, imageEl(), false); + + expect(url).toBe(`${NT_IMAGE_URL}&rkey=PRIVATEKEY`); + }); + + it('leaves non-NT URLs untouched and never fetches', async () => { + const { bridge, fetchDownloadRKeys } = makeBridge(async () => freshGroupRkey()); + const cache = new RKeyCache(); + const el: MessageElement = { type: 'image', imageUrl: 'https://gchat.qpic.cn/foo.jpg' }; + + const url = await cache.resolveImageUrl(bridge as never, el, true); + + expect(url).toBe('https://gchat.qpic.cn/foo.jpg'); + expect(fetchDownloadRKeys).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/onebot/tests/media-actions.test.ts b/packages/onebot/tests/media-actions.test.ts new file mode 100644 index 00000000..d3a4cfa1 --- /dev/null +++ b/packages/onebot/tests/media-actions.test.ts @@ -0,0 +1,63 @@ +import { describe, it, expect, vi } from 'vitest'; +import type { MessageElement } from '@snowluma/protocol/events'; +import { getImageInfo } from '../src/modules/media-actions'; +import type { CachedImage, MediaStore } from '../src/media-store'; + +const RAW = 'https://multimedia.nt.qq.com.cn/download?appid=1407&fileid=ABC'; + +function fakeStore(image: CachedImage | null): MediaStore { + return { findImage: () => image } as unknown as MediaStore; +} + +function cachedImage(overrides: Partial = {}): CachedImage { + return { + file: 'ABC.jpg', + url: `${RAW}&rkey=STALE`, // signed when the message arrived; now expired + fileSize: 100, + fileName: 'ABC.jpg', + subType: 0, + summary: '', + isGroup: true, + sessionId: 123, + imageUrl: RAW, // raw, unsigned — the basis for re-signing + ...overrides, + }; +} + +describe('getImageInfo — rkey re-signing at lookup time', () => { + it('re-signs from the raw imageUrl via the resolver', async () => { + const resolver = vi.fn(async (el: MessageElement) => `${el.imageUrl}&rkey=FRESH`); + + const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver); + + expect(info?.url).toBe(`${RAW}&rkey=FRESH`); + expect(info?.file).toBe(`${RAW}&rkey=FRESH`); + expect(resolver).toHaveBeenCalledWith( + expect.objectContaining({ type: 'image', imageUrl: RAW }), + true, // isGroup carried through + ); + }); + + it('returns the stored URL when no resolver is wired', async () => { + const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg'); + expect(info?.url).toBe(`${RAW}&rkey=STALE`); + }); + + it('falls back to the stored URL when the resolver throws', async () => { + const resolver = vi.fn(async () => { throw new Error('rkey fetch failed'); }); + const info = await getImageInfo(fakeStore(cachedImage()), 'ABC.jpg', resolver); + expect(info?.url).toBe(`${RAW}&rkey=STALE`); + }); + + it('skips re-signing when no raw imageUrl is stored', async () => { + const resolver = vi.fn(async () => 'should-not-be-used'); + const info = await getImageInfo(fakeStore(cachedImage({ imageUrl: '' })), 'ABC.jpg', resolver); + expect(resolver).not.toHaveBeenCalled(); + expect(info?.url).toBe(`${RAW}&rkey=STALE`); + }); + + it('returns null when the image is not cached', async () => { + const info = await getImageInfo(fakeStore(null), 'missing.jpg'); + expect(info).toBeNull(); + }); +}); diff --git a/packages/proto-defs/package.json b/packages/proto-defs/package.json index 31e4eca2..2bf29fea 100644 --- a/packages/proto-defs/package.json +++ b/packages/proto-defs/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proto-defs", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "description": "SnowLuma QQ/Lagrange wire-protobuf type definitions. Pure TypeScript interfaces with proton's `pb` marker types — `@snowluma/proton`'s vite plugin compiles them into zero-runtime encoder/decoder functions at the call sites in `@snowluma/core` (and any downstream consumer). Exposed as per-file subpaths (`@snowluma/proto-defs/oidb`, `@snowluma/proto-defs/message`, …) so the import-site shape mirrors the legacy `bridge/proto/proton/*` layout and avoids name collisions across files (notably `highway.ts` and `oidb-actions/media.ts` share NTV2-prefixed names).", diff --git a/packages/proto-defs/src/oidb-actions/base.ts b/packages/proto-defs/src/oidb-actions/base.ts index 560c3070..9c919be0 100644 --- a/packages/proto-defs/src/oidb-actions/base.ts +++ b/packages/proto-defs/src/oidb-actions/base.ts @@ -1,4 +1,4 @@ -import type { pb, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; +import type { pb, pb_optional, pb_repeated, int_32, uint_32, uint_64, bool, bytes } from '@snowluma/proton'; // Re-exported from the legacy oidb-action module while large protocol groups // are split into focused files. @@ -13,7 +13,11 @@ export interface OidbMuteMember { body?: pb<3, OidbMuteMemberBody>; } export interface OidbMuteAllState { - state?: pb<17, uint_32>; + // Explicit presence: the unmute request sends state=0, which proto3 would + // otherwise omit — leaving an empty `muteState` the server can't tell apart + // from the other commands sharing OIDB (0x89A, 0) (SetSearch / SetAddOption, + // disambiguated by body shape). pb_optional forces the 0 onto the wire. + state?: pb_optional<17, uint_32>; } export interface OidbMuteAll { groupUin?: pb<1, uint_32>; @@ -90,13 +94,19 @@ export interface OidbSetAdmin { uid?: pb<2, string>; isAdmin?: pb<3, bool>; } +// 0x8FC_3 (set member card) shares its wire shape with 0x8FC_2 (special +// title): the body wrapper sits at tag 3, and the card name at tag 8 — +// NOT tags 2/2. Sending body@2 / targetName@2 makes the server miss both +// and reject with `OIDB error 1007`. Cross-checked byte-for-byte against: +// dev/Lagrange.Core/…/Request/OidbSvcTrpcTcp0x8FC.cs (Body=3, TargetName=8) +// dev/napcatQQInside/…/proto/oidb/Oidb.0x8FC_2.ts (body=3, targetName=8) export interface OidbRenameMemberBody { targetUid?: pb<1, string>; - targetName?: pb<2, string>; + targetName?: pb<8, string>; } export interface OidbRenameMember { groupUin?: pb<1, uint_32>; - body?: pb<2, OidbRenameMemberBody>; + body?: pb<3, OidbRenameMemberBody>; } export interface OidbRenameGroupBody { targetName?: pb<1, string>; @@ -112,7 +122,8 @@ export interface OidbSpecialTitleBody { } export interface OidbSpecialTitle { groupUin?: pb<1, uint_32>; - body?: pb<2, OidbSpecialTitleBody>; + // Same family as 0x8FC_3 above — body wrapper is tag 3, not 2. + body?: pb<3, OidbSpecialTitleBody>; } // 0x7E5_104 (FriendLike) request body. Field numbers 11/12/13 (NOT // 1/2/3) — the server reads `targetUid` from tag 11 and rejects with @@ -657,4 +668,22 @@ export interface GroupAvatarExtra { field3?: pb<3, GroupAvatarExtraField3>; field5?: pb<5, uint_32>; field6?: pb<6, uint_32>; -} \ No newline at end of file +} + +export interface Oidb0xcdeReqBodyInfo { + db_salt?: pb<1, string>; +} + +export interface Oidb0xcdeReq { + info?: pb<2, Oidb0xcdeReqBodyInfo>; + sessionData?: pb<10, bytes>; +} + +export interface Oidb0xcdeRespBodyInfo { + dbKey?: pb<1, string>; +} + +export interface Oidb0xcdeResp { + info?: pb<2, Oidb0xcdeRespBodyInfo>; +} + diff --git a/packages/protocol/package.json b/packages/protocol/package.json index c33f0aa3..4e720525 100644 --- a/packages/protocol/package.json +++ b/packages/protocol/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/protocol", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "description": "SnowLuma protocol — the protocol-layer between QQ wire bytes and typed events. Owns: identity service (uid↔uin cache with SQLite persistence), event bus, packet pipeline (incoming SSO packet → QQEventVariant), msg-push decoders, element-builder (MessageElement → wire elems[]), highway upload protocol (file/image/video/ptt), OIDB envelope helper, and the event/notice/request type vocabulary. Consumers (@snowluma/core, @snowluma/onebot) talk to this package through `BridgeContext` for runtime calls and the standalone classes (IdentityService, BridgeEventBus, IncomingPacketPipeline) for composition. Per-file subpath exports mirror the legacy `core/src/bridge/*` layout 1:1 so the previous `import { …} from '../bridge/'` collapses to `import { … } from '@snowluma/protocol/'`.", @@ -107,6 +107,10 @@ "types": "./src/oidb-services/misc/send-group-sign.ts", "default": "./src/oidb-services/misc/send-group-sign.ts" }, + "./oidb-services/misc/request-decrypt-key": { + "types": "./src/oidb-services/misc/request-decrypt-key.ts", + "default": "./src/oidb-services/misc/request-decrypt-key.ts" + }, "./oidb-services/web/force-fetch-client-key": { "types": "./src/oidb-services/web/force-fetch-client-key.ts", "default": "./src/oidb-services/web/force-fetch-client-key.ts" @@ -368,8 +372,7 @@ "dependencies": { "@snowluma/common": "workspace:*", "@snowluma/proto-defs": "workspace:*", - "@snowluma/proton": "workspace:*", - "@snowluma/sqlite": "workspace:*" + "@snowluma/proton": "workspace:*" }, "devDependencies": { "@types/node": "^24.12.2", diff --git a/packages/protocol/src/highway/utils.ts b/packages/protocol/src/highway/utils.ts index c1c2c89f..d42c09a8 100644 --- a/packages/protocol/src/highway/utils.ts +++ b/packages/protocol/src/highway/utils.ts @@ -22,6 +22,19 @@ const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB const FETCH_TIMEOUT_MS = 60_000; +/** + * Browser-like User-Agent for remote media downloads. Many image / CDN + * hosts (and anti-hotlink front-ends) reject or RST a header-less, + * non-browser request — which surfaces as undici `TypeError: fetch + * failed` rather than a clean 403. Sending a normal browser UA on every + * request (and retrying with a Referer when the first try is refused) is + * what lets NapCat fetch sources our bare `fetch(source)` couldn't. + * Cross-checked against + * `dev/napcatQQInside/packages/napcat-common/src/file.ts:101-142,359-369`. + */ +const DOWNLOAD_USER_AGENT = + 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36'; + export interface ImageHashes { md5: Uint8Array; sha1: Uint8Array; @@ -65,6 +78,14 @@ export function resolveLocalFilePath(source: string): string | null { return filePath; } +/** + * Tag a size-limit error so the HTTP retry path leaves it alone — retrying + * a too-large response just re-downloads the same oversized body. + */ +function tooLarge(message: string): Error { + return Object.assign(new Error(message), { noRetry: true }); +} + export async function loadBinarySource( source: string, resourceName: string, @@ -81,49 +102,79 @@ export async function loadBinarySource( } if (/^https?:\/\//i.test(source)) { - const resp = await fetch(source, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) }); - if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); - const declared = Number(resp.headers.get('content-length') ?? '0'); - if (Number.isFinite(declared) && declared > maxBytes) { - throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`); - } const fileName = guessFileNameFromUrl(source); - // Stream the body incrementally so a server that omits or - // understates Content-Length can't make us buffer a chunked response - // past maxBytes — `await resp.arrayBuffer()` would happily allocate - // the entire payload before we get a chance to length-check it. - const reader = resp.body?.getReader(); - if (!reader) { - const bytes = new Uint8Array(await resp.arrayBuffer()); - if (bytes.length > maxBytes) { - throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + + // A single fetch attempt with the given headers. Streams the body + // incrementally so a server that omits or understates Content-Length + // can't make us buffer a chunked response past maxBytes — `await + // resp.arrayBuffer()` would happily allocate the entire payload before + // we get a chance to length-check it. Size-limit rejections are tagged + // `noRetry` so the outer retry doesn't re-download an oversized body. + const attempt = async (headers: Record): Promise => { + const resp = await fetch(source, { + headers, + redirect: 'follow', + signal: AbortSignal.timeout(FETCH_TIMEOUT_MS), + }); + if (!resp.ok) throw new Error(`HTTP download failed: ${resp.status}`); + const declared = Number(resp.headers.get('content-length') ?? '0'); + if (Number.isFinite(declared) && declared > maxBytes) { + throw tooLarge(`${resourceName} too large: ${declared} > ${maxBytes}`); + } + const reader = resp.body?.getReader(); + if (!reader) { + const bytes = new Uint8Array(await resp.arrayBuffer()); + if (bytes.length > maxBytes) { + throw tooLarge(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + } + return { bytes, fileName }; + } + const chunks: Uint8Array[] = []; + let total = 0; + try { + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (!value) continue; + total += value.byteLength; + if (total > maxBytes) { + await reader.cancel().catch(() => { /* ignore */ }); + throw tooLarge(`${resourceName} too large: > ${maxBytes}`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + const bytes = new Uint8Array(total); + let offset = 0; + for (const chunk of chunks) { + bytes.set(chunk, offset); + offset += chunk.byteLength; } return { bytes, fileName }; - } - const chunks: Uint8Array[] = []; - let total = 0; + }; + + // First try with a browser UA only. On any non-size failure — a + // network-level `fetch failed` (connection reset by an anti-bot + // front-end) or a 403/4xx from anti-hotlink — retry once with a + // Referer pointing at the resource itself, the common bypass for + // same-origin hotlink checks. Mirrors NapCat's with/without-Referer + // strategy. + const baseHeaders: Record = { + 'User-Agent': DOWNLOAD_USER_AGENT, + Accept: '*/*', + }; try { - while (true) { - const { done, value } = await reader.read(); - if (done) break; - if (!value) continue; - total += value.byteLength; - if (total > maxBytes) { - await reader.cancel().catch(() => { /* ignore */ }); - throw new Error(`${resourceName} too large: > ${maxBytes}`); - } - chunks.push(value); + return await attempt(baseHeaders); + } catch (err) { + if ((err as { noRetry?: boolean } | null)?.noRetry) throw err; + try { + return await attempt({ ...baseHeaders, Referer: source }); + } catch { + throw err; } - } finally { - reader.releaseLock(); } - const bytes = new Uint8Array(total); - let offset = 0; - for (const chunk of chunks) { - bytes.set(chunk, offset); - offset += chunk.byteLength; - } - return { bytes, fileName }; } const filePath = resolveLocalFilePath(source); diff --git a/packages/protocol/src/identity-service.ts b/packages/protocol/src/identity-service.ts index cf68358f..d2e566e2 100644 --- a/packages/protocol/src/identity-service.ts +++ b/packages/protocol/src/identity-service.ts @@ -1,12 +1,14 @@ import fs from 'fs'; +import { DatabaseSync, type StatementSync } from 'node:sqlite'; import path from 'path'; -import Database, { type Database as DatabaseType, type Statement } from '@snowluma/sqlite'; -import type { - FriendInfo, GroupMemberInfo, QQGroupInfo, - UserProfileInfo, GroupRequestInfo, -} from './qq-info'; import { createLogger, type Logger } from '@snowluma/common/logger'; +import type { + FriendInfo, GroupMemberInfo, + GroupRequestInfo, + QQGroupInfo, + UserProfileInfo, +} from './qq-info'; const moduleLogger = createLogger('Identity'); @@ -109,14 +111,14 @@ export class IdentityService { private readonly uidByUin = new Map(); // ─── Persistence + fetcher ─── - private readonly db: DatabaseType | null; + private readonly db: DatabaseSync | null; // Prepared-statement cache. Every `.prepare(sql)` call in this // service re-parses the SQL — that's the SQLite anti-pattern // RoadMap #5 is fixing. We memoize by the SQL string itself so the // call sites stay readable (no need to enumerate 20+ named fields // upfront); the Map lookup is O(1) hash + string-eq, which is // negligible next to the SQL parse it replaces. - private readonly stmtCache_ = new Map(); + private readonly stmtCache_ = new Map(); private inTransaction = false; private fetcher: IdentityFetcher | null = null; private readonly log: Logger; @@ -134,16 +136,16 @@ export class IdentityService { } fs.mkdirSync(path.dirname(dbPath), { recursive: true }); - this.db = new Database(dbPath); - this.db.pragma('journal_mode = WAL'); - this.db.pragma('synchronous = NORMAL'); + this.db = new DatabaseSync(dbPath); + this.db.exec('PRAGMA journal_mode = WAL'); + this.db.exec('PRAGMA synchronous = NORMAL'); this.initSchema(); this.loadSnapshot(); } /** Cached `prepare(sql)`. First call per unique SQL parses; later * calls reuse the same `Statement` object. See `stmtCache_`. */ - private pstmt(sql: string): Statement { + private pstmt(sql: string): StatementSync { let cached = this.stmtCache_.get(sql); if (cached !== undefined) return cached; cached = this.db!.prepare(sql); diff --git a/packages/protocol/src/oidb-service.ts b/packages/protocol/src/oidb-service.ts index af01498d..b5ec017b 100644 --- a/packages/protocol/src/oidb-service.ts +++ b/packages/protocol/src/oidb-service.ts @@ -117,9 +117,19 @@ export async function invokeOidb 0) { const meta = protobuf_decode(respBytes); diff --git a/packages/protocol/src/oidb-services/misc/request-decrypt-key.ts b/packages/protocol/src/oidb-services/misc/request-decrypt-key.ts new file mode 100644 index 00000000..18b44329 --- /dev/null +++ b/packages/protocol/src/oidb-services/misc/request-decrypt-key.ts @@ -0,0 +1,70 @@ +import { protobuf_decode, protobuf_encode } from '@snowluma/proton'; +import type { OidbBase } from '@snowluma/proto-defs/oidb'; +import type { Oidb0xcdeReq, Oidb0xcdeResp } from '@snowluma/proto-defs/oidb-actions/base'; +import { invokeOidb, type OidbSender } from '../../oidb-service'; + +export namespace RequestDbKey { + export const command = 0xcde; + export const subCommand = 2; + + export interface Params { + db_salt: string; + sessionData?: Uint8Array; + } + + export interface Result { + success: boolean; + dbKey?: string; + errorCode?: number; + errorMsg?: string; + } + + export type Deps = OidbSender; + + export const serialize = (_ctx: Deps, p: Params): Oidb0xcdeReq => { + const req: Oidb0xcdeReq = { + info: { + db_salt: p.db_salt, + } + }; + if (p.sessionData) { + req.sessionData = p.sessionData; + } + return req; + }; + + export const deserialize = (_ctx: Deps, body: Oidb0xcdeResp): string => { + const dbKey = body.info?.dbKey; + + if (!dbKey) { + throw new Error('Oidb 0xcde_2 payload empty (Missing dbKey)'); + } + return dbKey; + }; + + export const encode = (env: OidbBase): Uint8Array => + protobuf_encode>(env); + + export const decode = (bytes: Uint8Array): OidbBase => + protobuf_decode>(bytes); + + export const invoke = async (deps: Deps, params: Params): Promise => { + try { + const key = await invokeOidb(deps, RequestDbKey, params); + return { + success: true, + dbKey: key, + }; + } catch (error: any) { + const code = error?.code ?? -1; + + return { + success: false, + errorCode: code, + errorMsg: code === 1006 + ? "数据库不匹配!检查数据库是否属于当前帐号" + : (error?.serverMsg || error?.message || "网络或包结构解析失败"), + }; + } + }; +} diff --git a/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts b/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts index 18f9d2b0..33e06dc2 100644 --- a/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts +++ b/packages/protocol/tests/oidb-services/group-admin/mute-all.test.ts @@ -26,12 +26,18 @@ describe('MuteAll namespace', () => { expect(env.body).toMatchObject({ groupUin: 12345, muteState: { state: 0xFFFFFFFF } }); }); - it('enable=false emits state=0', async () => { + it('enable=false forces state=0 ONTO the wire (so the server can disambiguate)', async () => { const deps = makeDeps(); await MuteAll.invoke(deps, { groupId: 12345, enable: false }); const [, bytes] = deps.sendRawPacket.mock.calls[0]!; const env = protobuf_decode>(bytes); - // proto3 default 0 fields are omitted on the wire. - expect(env.body?.muteState?.state ?? 0).toBe(0); + expect(env.body?.muteState?.state).toBe(0); + // The fix (issue #70): state=0 is a `pb_optional<>` field, so it must be + // PRESENT on the wire — field 17 (varint tag 0x88 0x01) + value 0x00 — not + // omitted. An empty `muteState` is indistinguishable from the other + // commands sharing OIDB (0x89A, 0), so the server rejects unmute with 1007. + const arr = Array.from(bytes); + const hasStateField = arr.some((_, i) => arr[i] === 0x88 && arr[i + 1] === 0x01 && arr[i + 2] === 0x00); + expect(hasStateField).toBe(true); }); }); diff --git a/packages/proton/package.json b/packages/proton/package.json index 496e2727..f2374cd6 100644 --- a/packages/proton/package.json +++ b/packages/proton/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/proton", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "description": "Compile-time protobuf encoder/decoder generator for SnowLuma. TypeScript interfaces → fully-inlined, zero-runtime protobuf codec functions. Vendored from SnowLuma/protobuf-dsl (reference copy under dev/protobuf-dsl/) with edge-case fixes applied.", diff --git a/packages/proton/protobuf.d.ts b/packages/proton/protobuf.d.ts index cc2f8deb..b6f52593 100644 --- a/packages/proton/protobuf.d.ts +++ b/packages/proton/protobuf.d.ts @@ -3,6 +3,14 @@ export type pb<_ProtoNumber extends number, Type> = Type; /** Marks a repeated protobuf field: `ids: pb_repeated` → Type[] */ export type pb_repeated<_ProtoNumber extends number, Type> = Type[]; +/** + * Marks a singular field with **explicit presence** (proto3 `optional`): it + * serialises whenever the value is present, INCLUDING its zero/default value + * — unlike `pb<>`, which omits zeros. Use when the wire peer needs the field + * present to disambiguate, e.g. an OIDB sub-command keyed on body shape where + * a zero must still appear on the wire. `name: pb_optional`. + */ +export type pb_optional<_ProtoNumber extends number, Type> = Type; // ── Protobuf primitive types ────────────────────────────────────────── export type uint_32 = number; diff --git a/packages/proton/src/ast/collector.ts b/packages/proton/src/ast/collector.ts index 6955b308..03552eba 100644 --- a/packages/proton/src/ast/collector.ts +++ b/packages/proton/src/ast/collector.ts @@ -1,7 +1,7 @@ import ts from 'typescript'; import { WireType, - PB_MARKER, PB_REPEATED_MARKER, + PB_MARKER, PB_REPEATED_MARKER, PB_OPTIONAL_MARKER, type ProtobufField, type ProtobufMessage, type GenericProtobufTemplate, type GenericFieldTemplate, } from './types.js'; @@ -85,7 +85,7 @@ function parsePbTypeRef( // Resolve the marker name through aliased imports so `import { pb as P }` // / `import { pb_repeated as PR }` still match the marker constants. const marker = resolveImportedTypeName(t.typeName.text); - if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER) return null; + if (marker !== PB_MARKER && marker !== PB_REPEATED_MARKER && marker !== PB_OPTIONAL_MARKER) return null; const ta = t.typeArguments; if (!ta || ta.length !== 2) return null; const fnNode = ta[0]; @@ -129,6 +129,7 @@ function extractField( isMessage: false, // placeholder isOptional: member.questionToken != null, isRepeated: parsed.marker === PB_REPEATED_MARKER, + explicitPresence: parsed.marker === PB_OPTIONAL_MARKER, }; } @@ -149,6 +150,7 @@ function extractGenericField( isTypeParam: tpSet.has(raw), isOptional: member.questionToken != null, isRepeated: parsed.marker === PB_REPEATED_MARKER, + explicitPresence: parsed.marker === PB_OPTIONAL_MARKER, }; // If the field's type-arg is itself a generic instantiation (`Wrapper`, // where U is a type param of the enclosing template), capture the original diff --git a/packages/proton/src/ast/monomorphizer.ts b/packages/proton/src/ast/monomorphizer.ts index 29d9e47b..adf7c38e 100644 --- a/packages/proton/src/ast/monomorphizer.ts +++ b/packages/proton/src/ast/monomorphizer.ts @@ -89,6 +89,7 @@ export function monomorphizeTypeNode( isMessage: false, isOptional: f.isOptional, isRepeated: f.isRepeated, + explicitPresence: f.explicitPresence, }; } return { @@ -99,6 +100,7 @@ export function monomorphizeTypeNode( isMessage: false, isOptional: f.isOptional, isRepeated: f.isRepeated, + explicitPresence: f.explicitPresence, }; }); diff --git a/packages/proton/src/ast/types.ts b/packages/proton/src/ast/types.ts index 37f80ea2..a95dfa18 100644 --- a/packages/proton/src/ast/types.ts +++ b/packages/proton/src/ast/types.ts @@ -13,6 +13,14 @@ export interface ProtobufField { isMessage: boolean; isOptional: boolean; isRepeated: boolean; + /** + * Explicit presence (proto3 `optional`), set only by the `pb_optional<>` + * marker. When true, a scalar field serialises even at its zero/default + * value. Distinct from `isOptional` (which merely tracks the TS `?` and is + * true for almost every field) — the encoder keys off THIS flag, never + * `isOptional`, so existing `pb<>` fields are unaffected. + */ + explicitPresence: boolean; } export interface ProtobufMessage { @@ -34,6 +42,8 @@ export interface GenericFieldTemplate { isTypeParam: boolean; isOptional: boolean; isRepeated: boolean; + /** Explicit presence (proto3 `optional`); see ProtobufField.explicitPresence. */ + explicitPresence: boolean; /** * For fields whose type-arg is itself a generic instantiation * (e.g. `wrapped: pb<5, Wrapper>` where `U` is a template type @@ -70,3 +80,4 @@ export const PRIMITIVE_TYPE_MAP: Record` scalar → serialise even at the zero value (proto3 explicit + // presence). Message fields already emit on `!= null`, so they stay on the + // default path; only scalars need the dedicated guard. Every `pb<>` / + // `pb_repeated<>` field has `explicitPresence === false` and so takes the + // untouched branches below — their generated code is byte-for-byte unchanged. + if (field.explicitPresence && !isMessage) { + return buildExplicitPresenceScalarBlock(field, index); + } const valueVar = `_f${index}`; const cacheVar = `_c${index}`; const tagLength = computeTagBytes(fieldNumber, isMessage || typeName === 'string' || typeName === 'bytes' ? 2 : wireType).length; @@ -318,6 +326,221 @@ function buildSingularBlock(field: ProtobufField, index: number): EncoderBlock { return { declare: [], size: [], write: [] }; } +/** + * Encoder block for a singular scalar field marked `pb_optional<>` (proto3 + * explicit presence). Identical to the default scalar paths EXCEPT the guard + * is `!= null` instead of `!= null && !== `, so the field — and a + * `bool`'s real value — is written even when zero/false/empty. Reached only + * when `field.explicitPresence === true`, so default `pb<>` fields never run + * this code. + */ +function buildExplicitPresenceScalarBlock(field: ProtobufField, index: number): EncoderBlock { + const { name, fieldNumber, typeName, wireType } = field; + const valueVar = `_f${index}`; + const cacheVar = `_c${index}`; + const isLenDelim = typeName === 'string' || typeName === 'bytes'; + const tagLength = computeTagBytes(fieldNumber, isLenDelim ? 2 : wireType).length; + const declareVal = ` const ${valueVar} = obj.${name};`; + const present = `${valueVar} != null`; + + if (typeName === 'string') { + return { + declare: [declareVal, ` let ${cacheVar};`], + size: [ + ` if (${present}) {`, + ` ${cacheVar} = __utf8Len(${valueVar});`, + ` const _len = ${cacheVar};`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${cacheVar};`, + writeVarint('_len', ' '), + ` offset = __utf8Write(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (typeName === 'bytes') { + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _len = ${valueVar}.length;`, + ` size += ${tagLength};`, + varintSize('_len', ' '), + ` size += _len;`, + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 2, ' '), + ` const _len = ${valueVar}.length;`, + writeVarint('_len', ' '), + ` buf.set(${valueVar}, offset);`, + ` offset += _len;`, + ` }`, + ], + }; + } + + if (typeName === 'bool') { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 1};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 0, ' '), + ` buf[offset++] = ${valueVar} ? 1 : 0;`, + ` }`, + ], + }; + } + + if (isVarint64(typeName)) { + const bigintExpr = bigintVarintExpr(typeName, valueVar); + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _val = ${bigintExpr};`, + ` size += ${tagLength};`, + ` size += __varint64Size(_val);`, + ` }`, + ], + write: [ + ` if (${present}) {`, + ` const _val = ${bigintExpr};`, + writeTag(fieldNumber, 0, ' '), + ` offset = __writeVarint64(buf, offset, _val);`, + ` }`, + ], + }; + } + + if (typeName === 'sint_32') { + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _val = ((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`((${valueVar} << 1) ^ (${valueVar} >> 31)) >>> 0`, ' '), + ` }`, + ], + }; + } + + if (wireType === WireType.Varint) { + return { + declare: [declareVal], + size: [ + ` if (${present}) {`, + ` const _val = ${valueVar} >>> 0;`, + ` size += ${tagLength};`, + varintSize('_val', ' '), + ` }`, + ], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 0, ' '), + writeVarint(`${valueVar} >>> 0`, ' '), + ` }`, + ], + }; + } + + if (typeName === 'float') { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 4};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 5, ' '), + ` offset = __writeFloat32(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit32) { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 4};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 5, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` }`, + ], + }; + } + + if (typeName === 'double') { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 8};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFloat64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (isFixed64BigInt(typeName)) { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 8};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 1, ' '), + ` offset = __writeFixed64(buf, offset, ${valueVar});`, + ` }`, + ], + }; + } + + if (wireType === WireType.Bit64) { + return { + declare: [declareVal], + size: [` if (${present}) size += ${tagLength + 8};`], + write: [ + ` if (${present}) {`, + writeTag(fieldNumber, 1, ' '), + ` const _val = ${valueVar};`, + ` buf[offset++] = _val & 0xff;`, + ` buf[offset++] = (_val >> 8) & 0xff;`, + ` buf[offset++] = (_val >> 16) & 0xff;`, + ` buf[offset++] = (_val >> 24) & 0xff;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` buf[offset++] = 0;`, + ` }`, + ], + }; + } + + return { declare: [], size: [], write: [] }; +} + function buildRepeatedBlock(field: ProtobufField, index: number): EncoderBlock { const { name, fieldNumber, typeName, wireType, isMessage } = field; const arrayVar = `_f${index}`; diff --git a/packages/proton/src/runtime-map.ts b/packages/proton/src/runtime-map.ts index 8406d194..00f48cd0 100644 --- a/packages/proton/src/runtime-map.ts +++ b/packages/proton/src/runtime-map.ts @@ -25,6 +25,7 @@ function cloneField(field: ProtobufField): ProtobufField { isMessage: field.isMessage, isOptional: field.isOptional, isRepeated: field.isRepeated, + explicitPresence: field.explicitPresence ?? false, }; } diff --git a/packages/proton/test/__tests__/generator.test.ts b/packages/proton/test/__tests__/generator.test.ts index 31c543be..09fc54f8 100644 --- a/packages/proton/test/__tests__/generator.test.ts +++ b/packages/proton/test/__tests__/generator.test.ts @@ -139,3 +139,43 @@ interface DoubleMsg { expect(result.values[1]).toBeCloseTo(-0.5); }); }); + +describe('pb_optional explicit presence', () => { + it('serialises a zero scalar (where pb<> would omit it)', () => { + const { enc, dec } = makeRoundTripFromSchema( + `interface OptMsg { forced: pb_optional<1, uint_32>; }`, + 'OptMsg', + ); + // field 1, varint, value 0 → tag 0x08 then payload 0x00 (NOT empty). + expect(Array.from(enc({ forced: 0 }))).toEqual([0x08, 0x00]); + expect(dec(enc({ forced: 0 })).forced).toBe(0); + }); + + it('still omits the field when the value is absent (undefined)', () => { + const { enc } = makeRoundTripFromSchema( + `interface OptMsg2 { forced: pb_optional<1, uint_32>; }`, + 'OptMsg2', + ); + expect(enc({}).length).toBe(0); + }); + + it('does not change a sibling plain pb<> field (it still omits its zero)', () => { + const { enc, dec } = makeRoundTripFromSchema( + `interface MixMsg { plain: pb<1, uint_32>; forced: pb_optional<2, uint_32>; }`, + 'MixMsg', + ); + // plain=0 omitted (unchanged); only forced=0 is emitted (field 2 → tag 0x10). + expect(Array.from(enc({ plain: 0, forced: 0 }))).toEqual([0x10, 0x00]); + expect(dec(enc({ plain: 7, forced: 9 }))).toEqual({ plain: 7, forced: 9 }); + }); + + it('forces a false bool onto the wire', () => { + const { enc, dec } = makeRoundTripFromSchema( + `interface BoolOpt { flag: pb_optional<1, bool>; }`, + 'BoolOpt', + ); + expect(Array.from(enc({ flag: false }))).toEqual([0x08, 0x00]); + expect(dec(enc({ flag: false })).flag).toBe(false); + expect(Array.from(enc({ flag: true }))).toEqual([0x08, 0x01]); + }); +}); diff --git a/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node b/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node deleted file mode 100644 index f43da9ce..00000000 Binary files a/packages/runtime/native/better-sqlite3-v127-darwin-arm64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v127-darwin-x64.node b/packages/runtime/native/better-sqlite3-v127-darwin-x64.node deleted file mode 100644 index c4df275b..00000000 Binary files a/packages/runtime/native/better-sqlite3-v127-darwin-x64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v127-linux-arm64.node b/packages/runtime/native/better-sqlite3-v127-linux-arm64.node deleted file mode 100644 index b6e59662..00000000 Binary files a/packages/runtime/native/better-sqlite3-v127-linux-arm64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v127-linux-x64.node b/packages/runtime/native/better-sqlite3-v127-linux-x64.node deleted file mode 100644 index dfc2a4a8..00000000 Binary files a/packages/runtime/native/better-sqlite3-v127-linux-x64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v127-win32-x64.node b/packages/runtime/native/better-sqlite3-v127-win32-x64.node deleted file mode 100644 index b54d6060..00000000 Binary files a/packages/runtime/native/better-sqlite3-v127-win32-x64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node b/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node deleted file mode 100644 index b192e495..00000000 Binary files a/packages/runtime/native/better-sqlite3-v137-darwin-arm64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v137-darwin-x64.node b/packages/runtime/native/better-sqlite3-v137-darwin-x64.node deleted file mode 100644 index c189de35..00000000 Binary files a/packages/runtime/native/better-sqlite3-v137-darwin-x64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v137-linux-arm64.node b/packages/runtime/native/better-sqlite3-v137-linux-arm64.node deleted file mode 100644 index ecc84e9b..00000000 Binary files a/packages/runtime/native/better-sqlite3-v137-linux-arm64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v137-linux-x64.node b/packages/runtime/native/better-sqlite3-v137-linux-x64.node deleted file mode 100644 index d475c3f6..00000000 Binary files a/packages/runtime/native/better-sqlite3-v137-linux-x64.node and /dev/null differ diff --git a/packages/runtime/native/better-sqlite3-v137-win32-x64.node b/packages/runtime/native/better-sqlite3-v137-win32-x64.node deleted file mode 100644 index 2f872f81..00000000 Binary files a/packages/runtime/native/better-sqlite3-v137-win32-x64.node and /dev/null differ diff --git a/packages/runtime/package.json b/packages/runtime/package.json index c2fc31bf..020b7ae5 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index d9e45c0f..197ac01e 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.2", + "version": "1.9.3", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/sqlite/package.json b/packages/sqlite/package.json deleted file mode 100644 index f7e683c3..00000000 --- a/packages/sqlite/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "name": "@snowluma/sqlite", - "version": "1.9.2", - "private": true, - "type": "module", - "description": "SnowLuma SQLite wrapper. Exposes the `better-sqlite3` Database constructor + Statement type, but loads the native `.node` binding from `dist/native/sqlite/-/` at runtime instead of going through `bindings('better_sqlite3.node')` + `node_modules/.../build/Release/`. The vendored prebuilds under `packages/runtime/native/sqlite/` get copied into the dist tree by `vite-plugin-cp` during the @snowluma/core build, mirroring how `websocket-*.node` and `ffmpegAddon.*.node` are handled. The end result: production artifacts ship as a single self-contained dist/ directory with no `dist/node_modules/` and no install step at runtime.", - "main": "./src/index.ts", - "types": "./src/index.ts", - "exports": { - ".": { - "types": "./src/index.ts", - "default": "./src/index.ts" - } - }, - "scripts": { - "typecheck": "tsc --noEmit" - }, - "devDependencies": { - "@types/better-sqlite3": "^7.6.13", - "@types/node": "^24.12.2", - "better-sqlite3": "12.10.0", - "typescript": "catalog:" - } -} diff --git a/packages/sqlite/src/index.ts b/packages/sqlite/src/index.ts deleted file mode 100644 index 73f87eb6..00000000 --- a/packages/sqlite/src/index.ts +++ /dev/null @@ -1,84 +0,0 @@ -import BetterSqlite3 from 'better-sqlite3'; -import { existsSync } from 'node:fs'; -import { createRequire } from 'node:module'; -import { dirname, join, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; - -// Re-export the public types/classes consumers need. `Database` and -// `Statement` come straight from better-sqlite3 — we only intercept -// the constructor at call time, not the class shape. -export type { Database, Options, RunResult, Statement } from 'better-sqlite3'; - -function triplet(): string { - return `${process.platform}-${process.arch}`; -} - -function abi(): string { - // `process.versions.modules` is the NODE_MODULE_VERSION the running - // Node binary expects — e.g. "127" for Node 22, "137" for Node 24. - // Stays in sync with whatever the host actually does at load time. - return `v${process.versions.modules}`; -} - -function locateBinding(): string { - const tri = triplet(); - const fileName = `better-sqlite3-${abi()}-${tri}.node`; - // Two candidate locations, tried in order: - // 1. Production: dist/native/better-sqlite3-.node - // — `import.meta.url` resolves to dist/ at runtime (the wrapper - // is bundled into index.mjs alongside it). - // 2. Dev: /packages/runtime/native/better-sqlite3-.node - // — `import.meta.url` resolves to packages/sqlite/src/index.ts; - // walk up to repo root + into runtime/native. - const here = dirname(fileURLToPath(import.meta.url)); - const distCandidate = join(here, 'native', fileName); - if (existsSync(distCandidate)) return distCandidate; - - // From packages/sqlite/src ⇢ go up to packages/, then into - // runtime/native. (Two `..` segments, not three — `src` → `sqlite/` - // → `packages/`, then descend into `runtime/native`.) - const devCandidate = resolve(here, '..', '..', 'runtime', 'native', fileName); - if (existsSync(devCandidate)) return devCandidate; - - throw new Error( - `@snowluma/sqlite: could not locate ${fileName}. ` + - `Tried:\n ${distCandidate}\n ${devCandidate}\n` + - `Run \`node tools/fetch-sqlite-prebuilts.mjs\` to vendor the missing platform binary.`, - ); -} - -// Load the native addon once at module import — keeping it module- -// scoped so the require() cost is paid exactly once per process. -let addon: unknown | null = null; -function loadAddon(): unknown { - if (addon) return addon; - const bindingPath = locateBinding(); - // better-sqlite3 expects the addon to be loaded via the CJS - // require() mechanism (N-API init runs through it). createRequire - // is the ESM-safe way to do that with an absolute path. - const req = createRequire(import.meta.url); - addon = req(bindingPath); - return addon; -} - -// Drop-in `Database` factory. Matches the better-sqlite3 default- -// export signature exactly: `new Database(filename[, options])` → -// `Database` instance. -// -// We can't just `class extends BetterSqlite3` because better-sqlite3's -// default export is a function that returns the instance (the `new -// Database(...)` shape works through that function's `new.target` -// check). Wrapping at the function-call boundary keeps that contract -// intact. -type BetterSqlite3Type = typeof BetterSqlite3; -type DatabaseInstance = InstanceType; -type DatabaseOptions = ConstructorParameters[1]; -type BetterSqlite3Constructor = new (filename?: string | Buffer, options?: DatabaseOptions) => DatabaseInstance; - -const Database = function Database(filename?: string | Buffer, options?: DatabaseOptions): DatabaseInstance { - const opts = { ...(options ?? {}), nativeBinding: loadAddon() } as DatabaseOptions; - // better-sqlite3 的默认导出同时支持函数调用和 new 调用;这里只需要构造器形态。 - return new (BetterSqlite3 as unknown as BetterSqlite3Constructor)(filename, opts); -} as unknown as BetterSqlite3Type; - -export default Database; diff --git a/packages/sqlite/tsconfig.json b/packages/sqlite/tsconfig.json deleted file mode 100644 index 4cd329d7..00000000 --- a/packages/sqlite/tsconfig.json +++ /dev/null @@ -1,13 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "compilerOptions": { - "types": ["node"], - "noEmit": true - }, - "include": [ - "src/**/*" - ], - "exclude": [ - "node_modules" - ] -} diff --git a/packages/ui/package.json b/packages/ui/package.json index 9645e186..f3feb4f0 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.9.2", + "version": "1.9.3", "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", "keywords": [ "snowluma", diff --git a/packages/websocket/package.json b/packages/websocket/package.json index a4cb9513..fb14138f 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.9.2", + "version": "1.9.3", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 72128247..aa7a24a1 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.9.2", + "version": "1.9.3", "type": "module", "scripts": { "dev": "vite", diff --git a/packages/webui/src/App.tsx b/packages/webui/src/App.tsx index 2a759e7e..d6781eca 100644 --- a/packages/webui/src/App.tsx +++ b/packages/webui/src/App.tsx @@ -21,6 +21,11 @@ function AuthBoundary() { const [authed, setAuthed] = useState(false); const [mustChange, setMustChange] = useState(false); const [status, setStatus] = useState('未连接'); + // The password from *this* session's login, carried into the forced + // change-password gate so it doesn't have to render an old-password field + // (which browsers autofill, misleading users on upgrade). Stays undefined + // for a returning session that's already authed but still must change. + const [loginPassword, setLoginPassword] = useState(undefined); const client = useMemo( () => @@ -63,14 +68,21 @@ function AuthBoundary() { ) : !authed ? ( { + onAuthed={(needsChange, password) => { setAuthed(true); setStatus('已连接'); setMustChange(needsChange); + setLoginPassword(password); }} /> ) : mustChange ? ( - setMustChange(false)} /> + { + setMustChange(false); + setLoginPassword(undefined); + }} + /> ) : ( @@ -81,13 +93,13 @@ function AuthBoundary() { ); } -function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) { +function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean, password: string) => void }) { const api = useApi(); const handleLogin = useCallback( async (password: string) => { const result = await api.login(password); if (!result.ok) return { success: false, error: result.message }; - onAuthed(result.mustChangePassword); + onAuthed(result.mustChangePassword, password); return { success: true }; }, [api, onAuthed], @@ -95,11 +107,17 @@ function LoginGate({ onAuthed }: { onAuthed: (mustChange: boolean) => void }) { return ; } -function ForcedChangePasswordGate({ onSuccess }: { onSuccess: () => void }) { +function ForcedChangePasswordGate({ + knownOldPassword, + onSuccess, +}: { + knownOldPassword?: string; + onSuccess: () => void; +}) { const api = useApi(); return ( api.checkPasswordStrength(p)} submit={(o, n) => api.changePassword(o, n)} onSuccess={onSuccess} diff --git a/packages/webui/src/components/change-password-dialog.tsx b/packages/webui/src/components/change-password-dialog.tsx new file mode 100644 index 00000000..1ccb992c --- /dev/null +++ b/packages/webui/src/components/change-password-dialog.tsx @@ -0,0 +1,48 @@ +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { ChangePasswordForm } from '@/components/pages/change-password-form'; +import { useApi } from '@/lib/api'; + +interface ChangePasswordDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + /** Fired after the password is changed successfully (dialog closes itself). */ + onSuccess: () => void; +} + +/** + * In-app "修改访问密码" modal. The forced first-time flow uses the full-screen + * ChangePasswordPage; this is the voluntary change a logged-in admin triggers + * from 设置 → 账号安全. Both share ChangePasswordForm, so behaviour is identical. + */ +export function ChangePasswordDialog({ open, onOpenChange, onSuccess }: ChangePasswordDialogProps) { + const api = useApi(); + + return ( + + + + 修改访问密码 + + 设置一个全新的强密码后,其它会话将被立即下线,需要重新登录。 + + + api.checkPasswordStrength(p)} + submit={(o, n) => api.changePassword(o, n)} + onSuccess={() => { + onSuccess(); + onOpenChange(false); + }} + onCancel={() => onOpenChange(false)} + idPrefix="dialog-cpw" + /> + + + ); +} diff --git a/packages/webui/src/components/config/node-summary-card.tsx b/packages/webui/src/components/config/node-summary-card.tsx index 3ce3d235..85eba824 100644 --- a/packages/webui/src/components/config/node-summary-card.tsx +++ b/packages/webui/src/components/config/node-summary-card.tsx @@ -9,11 +9,27 @@ import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { cn } from '@/lib/utils'; import type { AdapterCommon } from './defaults'; +import type { AdapterStatus } from '@/types'; + +const LIVE_STYLE: Record = { + ok: 'bg-success/10 text-success', + warn: 'bg-warning/10 text-warning', + down: 'bg-destructive/10 text-destructive', + disabled: 'bg-muted text-muted-foreground', +}; +const LIVE_LABEL: Record = { + ok: '正常', + warn: '注意', + down: '异常', + disabled: '未启用', +}; interface NodeSummaryCardProps { item: T; summary: string; duplicateName: boolean; + /** Live runtime status from the OneBot manager, matched by adapter name. */ + liveStatus?: AdapterStatus; onToggleEnabled: (next: boolean) => void; onEdit: () => void; onDelete: () => void; @@ -23,6 +39,7 @@ export function NodeSummaryCard({ item, summary, duplicateName, + liveStatus, onToggleEnabled, onEdit, onDelete, @@ -51,6 +68,14 @@ export function NodeSummaryCard({ {!enabled && ( 已停用 )} + {liveStatus && ( + + {LIVE_LABEL[liveStatus.status]} · {liveStatus.detail} + + )}
{summary}
diff --git a/packages/webui/src/components/layout/main-layout.tsx b/packages/webui/src/components/layout/main-layout.tsx index 6a39f70a..22e71261 100644 --- a/packages/webui/src/components/layout/main-layout.tsx +++ b/packages/webui/src/components/layout/main-layout.tsx @@ -1,7 +1,7 @@ import { useEffect, useState, type ReactNode } from 'react'; import { motion, AnimatePresence } from 'motion/react'; import { useRouterState } from '@tanstack/react-router'; -import { Sheet, SheetContent } from '@/components/ui/sheet'; +import { Sheet, SheetContent, SheetDescription, SheetTitle } from '@/components/ui/sheet'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Sidebar } from '@/components/layout/sidebar'; import { TopBar } from '@/components/layout/top-bar'; @@ -44,6 +44,11 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) { {isMobile && ( + {/* Radix Dialog (the Sheet primitive) requires an accessible name + + description; the nav itself is the visible content, so these are + screen-reader-only. */} + 导航菜单 + 切换 SnowLuma 控制台的页面。 setMobileOpen(false)} /> @@ -62,7 +67,7 @@ export function MainLayout({ status, onLogout, children }: MainLayoutProps) {
-
+
Promise<{ rules: PasswordRule[]; valid: boolean }>; + /** Sends `{ oldPassword, newPassword }`. Returns success or error message. */ + submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>; + /** Called after a successful submit. */ + onSuccess: () => void; + /** When provided, a cancel button is shown (used by the settings dialog). */ + onCancel?: () => void; + /** Disambiguates input ids if two instances ever mount at once. */ + idPrefix?: string; + submitLabel?: string; +} + +export function ChangePasswordForm({ + knownOldPassword, + checkStrength, + submit, + onSuccess, + onCancel, + idPrefix = 'cpw', + submitLabel = '保存新密码', +}: ChangePasswordFormProps) { + const carriesOld = knownOldPassword !== undefined; + + const [oldPassword, setOldPassword] = useState(''); + const [newPassword, setNewPassword] = useState(''); + const [confirmPassword, setConfirmPassword] = useState(''); + const [showOld, setShowOld] = useState(false); + const [showNew, setShowNew] = useState(false); + const [rules, setRules] = useState([]); + const [valid, setValid] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(''); + + const effectiveOld = carriesOld ? (knownOldPassword as string) : oldPassword; + const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword; + const canSubmit = + !submitting && effectiveOld.length > 0 && valid && confirmMatches && effectiveOld !== newPassword; + + // Debounce the strength check so we don't slam the API on every keystroke. + useEffect(() => { + let cancelled = false; + const handle = window.setTimeout(async () => { + try { + const res = await checkStrength(newPassword); + if (cancelled) return; + setRules(res.rules); + setValid(res.valid); + } catch { + /* ignore – the form will just stay disabled */ + } + }, 180); + return () => { + cancelled = true; + window.clearTimeout(handle); + }; + }, [newPassword, checkStrength]); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + if (!canSubmit) return; + setSubmitting(true); + setError(''); + try { + const res = await submit(effectiveOld, newPassword); + if (res.success) { + onSuccess(); + } else { + setError(res.message || '修改失败'); + } + } catch (err) { + setError(err instanceof Error ? err.message : '网络错误'); + } finally { + setSubmitting(false); + } + }; + + return ( +
+ {!carriesOld && ( +
+ +
+ setOldPassword(e.target.value)} + placeholder="输入当前访问密码" + className="h-10 pr-10 text-sm" + /> + +
+
+ )} + +
+ +
+ setNewPassword(e.target.value)} + placeholder="设置新的强密码" + className="h-10 pr-10 text-sm" + /> + +
+
+ +
+ + setConfirmPassword(e.target.value)} + placeholder="再次输入新密码" + className="h-10 text-sm" + /> + {confirmPassword.length > 0 && !confirmMatches && ( + 两次输入的密码不一致 + )} +
+ + + + + {error && ( + + {error} + + )} + + +
+ {onCancel && ( + + )} + +
+ + ); +} + +function RuleList({ rules }: { rules: PasswordRule[] }) { + // Initial empty state: show a placeholder set so the user knows the rules + // exist even before any input. + const display = useMemo(() => { + if (rules.length > 0) return rules; + return [ + { id: 'length', label: '长度不少于 10 位', ok: false }, + { id: 'lower', label: '至少包含一个小写字母', ok: false }, + { id: 'upper', label: '至少包含一个大写字母', ok: false }, + { id: 'special', label: '至少包含一个特殊字符', ok: false }, + { id: 'no-space', label: '不得包含空格', ok: false }, + ]; + }, [rules]); + + return ( +
    + {display.map((rule) => ( +
  • + + + {rule.ok && ( + + + + )} + + + + {rule.label} + +
  • + ))} +
+ ); +} diff --git a/packages/webui/src/components/pages/change-password-page.tsx b/packages/webui/src/components/pages/change-password-page.tsx index 7972b966..09aae42f 100644 --- a/packages/webui/src/components/pages/change-password-page.tsx +++ b/packages/webui/src/components/pages/change-password-page.tsx @@ -1,104 +1,40 @@ -import { useEffect, useMemo, useState } from 'react'; -import { motion, AnimatePresence } from 'motion/react'; -import { Check, Eye, EyeOff, KeyRound, Loader2, ShieldAlert } from 'lucide-react'; -import { Button } from '@/components/ui/button'; +import { motion } from 'motion/react'; +import { ShieldAlert } from 'lucide-react'; import { Card, CardContent } from '@/components/ui/card'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; import { ThemeToggle } from '@/components/theme-toggle'; -import { cn } from '@/lib/utils'; +import { ChangePasswordForm, type PasswordRule } from '@/components/pages/change-password-form'; -export interface PasswordRule { - id: string; - label: string; - ok: boolean; -} +// Re-exported so existing importers (e.g. the API client) keep resolving +// `PasswordRule` from this module after the form was extracted. +export type { PasswordRule }; interface ChangePasswordPageProps { - /** When true, this is the forced first-time change flow. */ - forced?: boolean; - /** Heading shown above the form. */ + /** + * The password the user just logged in with. Passed straight through to the + * form as `knownOldPassword`, so the forced flow never renders an + * old-password field for a browser to autofill. See change-password-form. + */ + knownOldPassword?: string; title?: string; - /** Subheading. */ description?: string; - /** Sends `{ password }` and returns the rule list + valid flag. */ checkStrength: (password: string) => Promise<{ rules: PasswordRule[]; valid: boolean }>; - /** Sends `{ oldPassword, newPassword }`. Returns success or error message. */ submit: (oldPassword: string, newPassword: string) => Promise<{ success: boolean; message?: string }>; - /** Called after a successful submit. */ onSuccess: () => void; - /** Called when user cancels (only available when not forced). */ - onCancel?: () => void; } +/** + * Full-screen "you must set a new password before continuing" gate, shown + * once right after the first login with a generated temp password. The + * in-app "修改访问密码" action uses ChangePasswordDialog instead. + */ export function ChangePasswordPage({ - forced = false, - title, - description, + knownOldPassword, + title = '请先设置新的访问密码', + description = '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。', checkStrength, submit, onSuccess, - onCancel, }: ChangePasswordPageProps) { - const [oldPassword, setOldPassword] = useState(''); - const [newPassword, setNewPassword] = useState(''); - const [confirmPassword, setConfirmPassword] = useState(''); - const [showOld, setShowOld] = useState(false); - const [showNew, setShowNew] = useState(false); - const [rules, setRules] = useState([]); - const [valid, setValid] = useState(false); - const [submitting, setSubmitting] = useState(false); - const [error, setError] = useState(''); - - const confirmMatches = newPassword.length > 0 && newPassword === confirmPassword; - const canSubmit = - !submitting && oldPassword.length > 0 && valid && confirmMatches && oldPassword !== newPassword; - - // Debounce the strength check so we don't slam the API on every keystroke. - useEffect(() => { - let cancelled = false; - const handle = window.setTimeout(async () => { - try { - const res = await checkStrength(newPassword); - if (cancelled) return; - setRules(res.rules); - setValid(res.valid); - } catch { - /* ignore – the form will just stay disabled */ - } - }, 180); - return () => { - cancelled = true; - window.clearTimeout(handle); - }; - }, [newPassword, checkStrength]); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - if (!canSubmit) return; - setSubmitting(true); - setError(''); - try { - const res = await submit(oldPassword, newPassword); - if (res.success) { - onSuccess(); - } else { - setError(res.message || '修改失败'); - } - } catch (err) { - setError(err instanceof Error ? err.message : '网络错误'); - } finally { - setSubmitting(false); - } - }; - - const computedTitle = title ?? (forced ? '请先设置新的访问密码' : '修改访问密码'); - const computedDescription = - description ?? - (forced - ? '为了保护你的实例,必须将首次启动生成的临时密码替换为符合下列要求的强密码。' - : '设置一个全新的强密码后,其他会话将被立即下线,需要重新登录。'); - return (
- {forced ? ( - - ) : ( - - )} +
-

{computedTitle}

-

{computedDescription}

+

{title}

+

{description}

-
-
- -
- setOldPassword(e.target.value)} - placeholder="输入当前访问密码" - className="h-10 pr-10 text-sm" - /> - -
-
- -
- -
- setNewPassword(e.target.value)} - placeholder="设置新的强密码" - className="h-10 pr-10 text-sm" - /> - -
-
- -
- - setConfirmPassword(e.target.value)} - placeholder="再次输入新密码" - className="h-10 text-sm" - /> - {confirmPassword.length > 0 && !confirmMatches && ( - 两次输入的密码不一致 - )} -
- - - - - {error && ( - - {error} - - )} - - -
- {!forced && onCancel && ( - - )} - -
- +
+ +
); } - -function RuleList({ rules }: { rules: PasswordRule[] }) { - // Initial empty state: show a placeholder set so the user knows the rules - // exist even before any input. - const display = useMemo(() => { - if (rules.length > 0) return rules; - return [ - { id: 'length', label: '长度不少于 10 位', ok: false }, - { id: 'lower', label: '至少包含一个小写字母', ok: false }, - { id: 'upper', label: '至少包含一个大写字母', ok: false }, - { id: 'special', label: '至少包含一个特殊字符', ok: false }, - { id: 'no-space', label: '不得包含空格', ok: false }, - ]; - }, [rules]); - - return ( -
    - {display.map((rule) => ( -
  • - - - {rule.ok && ( - - - - )} - - - - {rule.label} - -
  • - ))} -
- ); -} diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index fa7594f4..1fd66961 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -16,6 +16,7 @@ import { Badge } from '@/components/ui/badge'; import { ConfirmDialog } from '@/components/confirm-dialog'; import { cn } from '@/lib/utils'; import type { + AdapterStatus, NetworkKind, OneBotConfig, OneBotNetworks, @@ -39,7 +40,7 @@ type DialogState = // index: null → create with `seed`, otherwise edit the item at that position. export function ConfigPage() { - const { qqList, selectedUin, setSelectedUin } = useAppState(); + const { qqList, connections, selectedUin, setSelectedUin } = useAppState(); const { config, setConfig, @@ -56,7 +57,11 @@ export function ConfigPage() { }); const [activeTab, setActiveTab] = useState('general'); - const [sidebarCollapsed, setSidebarCollapsed] = useState(false); + // Default the account strip to its 56px avatar-only form on narrow screens + // (≤lg) so the editor pane isn't squeezed; the user can still expand it. + const [sidebarCollapsed, setSidebarCollapsed] = useState( + () => typeof window !== 'undefined' && window.matchMedia('(max-width: 1024px)').matches, + ); const [confirmSave, setConfirmSave] = useState(false); // The edit dialog is modal and blocks every other click in the page, // so `selectedUin` cannot change while it's open — no defensive close @@ -68,40 +73,56 @@ export function ConfigPage() { [pendingSwitchUin, qqList], ); - // Per-kind helpers (typed at the call site so the dialog's onSubmit - // payload is exactly the kind's adapter shape). - function updateKind(kind: K, next: OneBotNetworks[K]): void { + // Live adapter status for the selected account, keyed by adapter name so + // each summary card can light up its real connection state. + const liveStatusByName = useMemo(() => { + const acc = connections.find((c) => c.uin === selectedUin); + const map = new Map(); + for (const a of acc?.adapters ?? []) map.set(a.name, a); + return map; + }, [connections, selectedUin]); + + // A discrete node mutation (create / edit / delete / enable-toggle) is + // persisted the moment it happens — clicking 保存 inside the editor dialog + // (or flipping the enable switch) IS the save. This removes the old + // two-step trap where editing a token in the dialog only marked the config + // "dirty" until you also pressed the top-right 保存, which silently cost + // many users their token edits. The general-settings tab keeps its explicit + // top-right save (it's a continuously-edited free-form surface). + function commitKind(kind: K, nextList: OneBotNetworks[K]): void { if (!config) return; - setConfig({ ...config, networks: { ...config.networks, [kind]: next } }); + const next = { ...config, networks: { ...config.networks, [kind]: nextList } }; + setConfig(next); + void save(next); } function handleCreate(kind: K, item: OneBotNetworks[K][number]): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - updateKind(kind, [...list, item] as OneBotNetworks[K]); + commitKind(kind, [...list, item] as OneBotNetworks[K]); } function handleEdit(kind: K, index: number, item: OneBotNetworks[K][number]): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - const next = list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]; - updateKind(kind, next); + commitKind(kind, list.map((it, i) => (i === index ? item : it)) as OneBotNetworks[K]); } function handleDelete(kind: K, index: number): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - const next = list.filter((_, i) => i !== index) as OneBotNetworks[K]; - updateKind(kind, next); + commitKind(kind, list.filter((_, i) => i !== index) as OneBotNetworks[K]); } function handleToggleEnabled(kind: K, index: number, enabled: boolean): void { if (!config) return; const list = config.networks[kind] as OneBotNetworks[K]; - const next = list.map((it, i) => - i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it, - ) as OneBotNetworks[K]; - updateKind(kind, next); + commitKind( + kind, + list.map((it, i) => + i === index ? ({ ...it, enabled: enabled ? undefined : false } as OneBotNetworks[K][number]) : it, + ) as OneBotNetworks[K], + ); } const openCreate = (kind: NetworkKind) => { @@ -159,6 +180,7 @@ export function ConfigPage() { openCreate(activeTab)} onEdit={(idx) => openEdit(activeTab, idx)} onDelete={(idx) => handleDelete(activeTab, idx)} @@ -237,7 +259,7 @@ function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate UIN {selectedUin}
-
+
{saveStatus && ( +
{ALL_TABS.map((key) => { const label = key === 'general' ? '通用设置' : NETWORK_TABS[key].title; const count = key === 'general' ? null : counts[key]; @@ -292,7 +314,7 @@ function TabStrip({ activeTab, onChange, counts }: TabStripProps) { type="button" onClick={() => onChange(key)} className={cn( - 'group relative inline-flex items-center gap-1.5 px-3 py-2 text-sm transition-colors cursor-pointer', + 'group relative inline-flex shrink-0 items-center gap-1.5 whitespace-nowrap px-3 py-2 text-sm transition-colors cursor-pointer', active ? 'text-foreground' : 'text-muted-foreground hover:text-foreground', )} > @@ -333,6 +355,7 @@ function countMap(networks: OneBotNetworks): Record { interface NetworkTabViewProps { kind: NetworkKind; config: OneBotConfig; + statusByName: Map; onCreateClick: () => void; onEdit: (index: number) => void; onDelete: (index: number) => void; @@ -342,6 +365,7 @@ interface NetworkTabViewProps { function NetworkTabView({ kind, config, + statusByName, onCreateClick, onEdit, onDelete, @@ -390,6 +414,7 @@ function NetworkTabView({ item={item} summary={summarize(item)} duplicateName={duplicate} + liveStatus={statusByName.get(item.name)} onToggleEnabled={(v) => onToggleEnabled(idx, v)} onEdit={() => onEdit(idx)} onDelete={() => onDelete(idx)} diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index 6201bc06..05dbe644 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -21,6 +21,13 @@ const levelClass: Record = { const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error']; +/** Show a locale time when the backend sends an ISO timestamp (it does); + * fall back to the raw string otherwise so we never render "Invalid Date". */ +function formatTime(t: string): string { + const d = new Date(t); + return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString(); +} + export function LogsPage() { const api = useApi(); const [logs, setLogs] = useState([]); @@ -205,16 +212,19 @@ export function LogsPage() { initial={{ opacity: 0 }} animate={{ opacity: 1 }} transition={{ duration: 0.12 }} - className="flex gap-2 whitespace-pre-wrap px-3 py-0.5 leading-5 hover:bg-accent/30" + className="flex flex-col gap-0.5 px-3 py-1 leading-5 hover:bg-accent/30 sm:flex-row sm:gap-2 sm:py-0.5" > - - {new Date(log.time).toLocaleTimeString()} - - - {log.level.toUpperCase()} - - [{log.scope}] - {log.message} + {/* Meta drops to its own line on phones so the message gets + the full width instead of a ~40px column that breaks + every few characters. On sm+ it's the dense single row. */} +
+ {formatTime(log.time)} + + {log.level.toUpperCase()} + + [{log.scope}] +
+ {log.message} )) )} diff --git a/packages/webui/src/components/pages/overview-page.tsx b/packages/webui/src/components/pages/overview-page.tsx index 096d1db2..e0da68bc 100644 --- a/packages/webui/src/components/pages/overview-page.tsx +++ b/packages/webui/src/components/pages/overview-page.tsx @@ -1,51 +1,32 @@ import { useEffect, useState } from 'react'; import { motion } from 'motion/react'; +import { Link } from '@tanstack/react-router'; import { Activity, - AlertCircle, - CheckCircle2, + ArrowRight, + Bell, + Cable, Cpu, - Eye, - Loader2, MemoryStick, MonitorCog, + PlugZap, RefreshCw, Server, - Unplug, Users, } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; -import { Badge } from '@/components/ui/badge'; import { Progress } from '@/components/ui/progress'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Skeleton } from '@/components/ui/skeleton'; -import { ConfirmDialog } from '@/components/confirm-dialog'; -import { ProcessProbeDialog } from '@/components/process-probe-dialog'; import { cn, formatBytes, formatUptime } from '@/lib/utils'; -import type { HookProcessInfo } from '@/types'; +import type { AppPath } from '@/router'; +import type { AccountConnections, AdapterStatus, AdapterStatusLevel, LogEntry } from '@/types'; +import { useApi } from '@/lib/api'; import { useAppState } from '@/contexts/AppStateContext'; import { useSession } from '@/contexts/SessionContext'; -const processStatusLabel: Record = { - available: '可加载', - loading: '加载中', - connecting: '等待连接', - loaded: '等待登录', - online: '已在线', - error: '错误', - disconnected: '已断开', -}; - -function processBadgeVariant(status: HookProcessInfo['status']) { - if (status === 'online') return 'success' as const; - if (status === 'error') return 'destructive' as const; - if (status === 'disconnected') return 'destructive' as const; - if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const; - return 'secondary' as const; -} - function qqAvatarUrl(uin: string) { return `/avatar/${encodeURIComponent(uin)}`; } @@ -56,44 +37,48 @@ function StatTile({ value, subtext, accent = false, + to, }: { icon: React.ReactNode; label: string; value: React.ReactNode; subtext?: React.ReactNode; accent?: boolean; + /** When set, the whole tile becomes a link to this route. */ + to?: AppPath; }) { - return ( - - -
- {icon} -
-
-

{label}

-
{value}
- {subtext &&

{subtext}

} -
-
-
+ const body = ( + +
+ {icon} +
+
+

{label}

+
{value}
+ {subtext &&

{subtext}

} +
+ {to && } +
); + + if (to) { + return ( + + {body} + + ); + } + return {body}; } export function OverviewPage() { - const { qqList, processList, systemInfo, processOps, refreshProcesses, refreshSystem } = - useAppState(); + const { qqList, processList, systemInfo, connections, refreshSystem } = useAppState(); const { status } = useSession(); - const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps; - const [confirm, setConfirm] = useState< - | { kind: 'load' | 'unload'; pid: number; name: string } - | null - >(null); - const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null); // Lightweight tick to refresh "uptime" pretty-print every 30s const [, force] = useState(0); @@ -103,11 +88,14 @@ export function OverviewPage() { }, []); const online = status === '已连接'; + // Read-only injection health for the dashboard. Control lives on /processes. + const onlineProcs = processList.filter((p) => p.status === 'online').length; + const loadableProcs = processList.filter((p) => !p.injected).length; return (
{/* Top stats */} -
+
} label="服务状态" @@ -121,6 +109,13 @@ export function OverviewPage() { value={qqList.length} subtext={`已接入 ${qqList.length} 个会话`} /> + } + label="进程注入" + value={`${onlineProcs} 在线`} + subtext={`${processList.length} 进程 · ${loadableProcs} 可注入`} + to="/processes" + /> } label="主机名" @@ -135,6 +130,35 @@ export function OverviewPage() { />
+ {/* First-run nudge: nothing online yet → point at the injection page. */} + {qqList.length === 0 && ( + + +
+ +
+
+

+ {loadableProcs > 0 ? `检测到 ${loadableProcs} 个可加载 QQ 进程` : '尚未接入任何账号'} +

+

+ 前往「进程注入」加载 QQ,登录后会自动接入 OneBot 流程。 +

+
+ + +
+ )} + + {/* Operational health — connection status + recent alerts (side by side on wide screens) */} +
+ + +
+ {/* System metrics */} @@ -240,147 +264,6 @@ export function OverviewPage() { - {/* QQ Processes */} - - -
- QQ 进程 - - 加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程 - -
- -
- - {processActionStatus && ( - - {processActionStatus} - - )} - {processList.length === 0 ? ( -
- -

未检测到可加载 QQ 主进程

-
- ) : ( -
- {processList.map((proc, idx) => { - const op = statusOf(proc.pid); - const loading = op === 'load' || proc.status === 'loading'; - const unloading = op === 'unload'; - const refreshing = op === 'refresh'; - const busy = op != null || proc.status === 'loading'; - const isOnline = proc.status === 'online'; - const canUnload = proc.injected; - // Refresh is meaningful whenever a hook may exist (so the user - // can re-check the pipe and trigger a reconnect on demand). - const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected'; - return ( - -
- {isOnline ? ( - - ) : proc.status === 'error' ? ( - - ) : ( - - )} -
-
-
- {proc.name || 'QQ.exe'} - {processStatusLabel[proc.status]} -
-
- PID {proc.pid} - {proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''} -
- {proc.path && ( -
- {proc.path} -
- )} - {proc.error && ( -
- {proc.error} -
- )} -
-
- - {showRefresh && ( - - )} - -
-
- ); - })} -
- )} -
-
- {/* Online accounts */} @@ -395,7 +278,7 @@ export function OverviewPage() {
) : ( -
+
{qqList.map((q, idx) => ( - - !o && setConfirm(null)} - title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'} - description={ - confirm - ? confirm.kind === 'unload' - ? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。` - : `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。` - : '' - } - confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'} - destructive={confirm?.kind === 'unload'} - onConfirm={async () => { - if (!confirm) return; - if (confirm.kind === 'unload') await unload(confirm.pid); - else await load(confirm.pid); - }} - /> - - {probeDialog && ( - !open && setProbeDialog(null)} - /> - )}
); } + +// ─────────────── connection health ─────────────── + +const CONN_STATUS_STYLE: Record = { + ok: 'bg-success/10 text-success', + warn: 'bg-warning/10 text-warning', + down: 'bg-destructive/10 text-destructive', + disabled: 'bg-muted text-muted-foreground', +}; +const CONN_STATUS_LABEL: Record = { + ok: '正常', + warn: '注意', + down: '异常', + disabled: '未启用', +}; +const ADAPTER_KIND_LABEL: Record = { + httpServer: 'HTTP 服务端', + httpClient: 'HTTP 上报', + wsServer: 'WS 服务端', + wsClient: 'WS 客户端', +}; + +function ConnectionsCard({ connections }: { connections: AccountConnections[] }) { + return ( + + + + OneBot 连接 + + 各账号协议端点的实时连接状态 + + + {connections.length === 0 ? ( +
+ +

暂无已接入的账号实例

+
+ ) : ( +
+ {connections.map((acc) => ( +
+
+ {acc.nickname || acc.uin} + {acc.uin} +
+ {acc.adapters.length === 0 ? ( +

+ 未配置任何协议端点 +

+ ) : ( +
+ {acc.adapters.map((a) => ( +
+ + {CONN_STATUS_LABEL[a.status]} + +
+
+ {a.name} + {ADAPTER_KIND_LABEL[a.kind]} +
+
{a.detail}
+
+
+ ))} +
+ )} +
+ ))} +
+ )} +
+
+ ); +} + +// ─────────────── recent alerts ─────────────── + +function alertClock(t: string): string { + const d = new Date(t); + return Number.isNaN(d.getTime()) ? t : d.toLocaleTimeString(); +} + +function RecentAlertsCard() { + const api = useApi(); + const [alerts, setAlerts] = useState([]); + + useEffect(() => { + let active = true; + api.logs + .list(200) + .then((list) => { + if (!active) return; + setAlerts(list.filter((l) => l.level === 'warn' || l.level === 'error').slice(-5)); + }) + .catch(() => { /* ignore */ }); + const stop = api.logs.stream({ + onLine: (entry) => { + if (entry.level !== 'warn' && entry.level !== 'error') return; + setAlerts((prev) => [...prev.filter((a) => a.id !== entry.id), entry].slice(-5)); + }, + }); + return () => { + active = false; + stop(); + }; + }, [api]); + + return ( + + +
+ + 最近告警 + + 最近的 warn / error 级别日志 +
+ + 查看日志 + +
+ + {alerts.length === 0 ? ( +
+ +

暂无告警

+
+ ) : ( +
+ {alerts.map((a) => ( +
+ {alertClock(a.time)} + + {a.level.toUpperCase()} + + + [{a.scope}] {a.message} + +
+ ))} +
+ )} +
+
+ ); +} diff --git a/packages/webui/src/components/pages/processes-page.tsx b/packages/webui/src/components/pages/processes-page.tsx new file mode 100644 index 00000000..d011d8a4 --- /dev/null +++ b/packages/webui/src/components/pages/processes-page.tsx @@ -0,0 +1,222 @@ +import { useState } from 'react'; +import { motion } from 'motion/react'; +import { AlertCircle, CheckCircle2, Cpu, Eye, Loader2, RefreshCw, Unplug } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { Badge } from '@/components/ui/badge'; +import { ConfirmDialog } from '@/components/confirm-dialog'; +import { ProcessProbeDialog } from '@/components/process-probe-dialog'; +import { cn } from '@/lib/utils'; +import type { HookProcessInfo } from '@/types'; +import { useAppState } from '@/contexts/AppStateContext'; + +const processStatusLabel: Record = { + available: '可加载', + loading: '加载中', + connecting: '等待连接', + loaded: '等待登录', + online: '已在线', + error: '错误', + disconnected: '已断开', +}; + +function processBadgeVariant(status: HookProcessInfo['status']) { + if (status === 'online') return 'success' as const; + if (status === 'error') return 'destructive' as const; + if (status === 'disconnected') return 'destructive' as const; + if (status === 'loading' || status === 'connecting' || status === 'loaded') return 'default' as const; + return 'secondary' as const; +} + +/** + * Process / injection control surface. Split out of the overview page so the + * homepage stays a read-only monitoring dashboard. State (processList, + * processOps) is owned by AppLayout and read from context, so this page needs + * no plumbing of its own; the layout keeps polling and the unload-failed alert + * regardless of which page is mounted. + */ +export function ProcessesPage() { + const { processList, processOps, refreshProcesses } = useAppState(); + const { statusOf, banner: processActionStatus, load, unload, refresh } = processOps; + const [confirm, setConfirm] = useState<{ kind: 'load' | 'unload'; pid: number; name: string } | null>(null); + const [probeDialog, setProbeDialog] = useState<{ pid: number; name: string } | null>(null); + + return ( +
+ + +
+ 进程注入 + 加载 SnowLuma 后会监听登录状态,登录后自动接入 OneBot 流程 +
+ +
+ + {processActionStatus && ( + + {processActionStatus} + + )} + {processList.length === 0 ? ( +
+ +

未检测到可加载 QQ 主进程

+

请确认 QQ 已启动后点击右上角刷新

+
+ ) : ( +
+ {processList.map((proc, idx) => { + const op = statusOf(proc.pid); + const loading = op === 'load' || proc.status === 'loading'; + const unloading = op === 'unload'; + const refreshing = op === 'refresh'; + const busy = op != null || proc.status === 'loading'; + const isOnline = proc.status === 'online'; + const canUnload = proc.injected; + // Refresh is meaningful whenever a hook may exist (so the user + // can re-check the pipe and trigger a reconnect on demand). + const showRefresh = proc.injected || proc.status === 'connecting' || proc.status === 'disconnected'; + return ( + + {/* icon + info stay horizontal; on phones the actions drop to + a second row so name / PID / path get the full width + instead of collapsing to "Q..". */} +
+
+ {isOnline ? ( + + ) : proc.status === 'error' ? ( + + ) : ( + + )} +
+
+
+ {proc.name || 'QQ.exe'} + + {processStatusLabel[proc.status]} + +
+
+ PID {proc.pid} + {proc.uin && proc.uin !== '0' ? ` · UIN ${proc.uin}` : ''} +
+ {proc.path && ( +
+ {proc.path} +
+ )} + {proc.error && ( +
+ {proc.error} +
+ )} +
+
+
+ + {showRefresh && ( + + )} + +
+
+ ); + })} +
+ )} +
+
+ + !o && setConfirm(null)} + title={confirm?.kind === 'unload' ? '确认卸载 SnowLuma?' : '确认加载 SnowLuma?'} + description={ + confirm + ? confirm.kind === 'unload' + ? `将从进程 ${confirm.name} 卸载 SnowLuma 注入,可能导致当前会话断开。` + : `将向进程 ${confirm.name} 注入 SnowLuma,并开始监听登录状态。` + : '' + } + confirmText={confirm?.kind === 'unload' ? '卸载' : '加载'} + destructive={confirm?.kind === 'unload'} + onConfirm={async () => { + if (!confirm) return; + if (confirm.kind === 'unload') await unload(confirm.pid); + else await load(confirm.pid); + }} + /> + + {probeDialog && ( + !open && setProbeDialog(null)} + /> + )} +
+ ); +} diff --git a/packages/webui/src/components/pages/settings-page.tsx b/packages/webui/src/components/pages/settings-page.tsx index a969f34c..b58daf5d 100644 --- a/packages/webui/src/components/pages/settings-page.tsx +++ b/packages/webui/src/components/pages/settings-page.tsx @@ -1,6 +1,6 @@ import { useState } from 'react'; import { motion } from 'motion/react'; -import { Check, KeyRound, Loader2, Monitor, Moon, Sun } from 'lucide-react'; +import { Check, KeyRound, Monitor, Moon, Palette, RefreshCw, ShieldCheck, Sun } from 'lucide-react'; import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@/components/ui/card'; import { Button } from '@/components/ui/button'; import { Label } from '@/components/ui/label'; @@ -14,8 +14,7 @@ import { type Density, type ThemeMode, } from '@/contexts/ThemeContext'; -import { ChangePasswordPage } from '@/components/pages/change-password-page'; -import { useApi } from '@/lib/api'; +import { ChangePasswordDialog } from '@/components/change-password-dialog'; import { useAppState } from '@/contexts/AppStateContext'; import { cn } from '@/lib/utils'; @@ -30,233 +29,279 @@ const DENSITY_OPTIONS: { value: Density; label: string; description: string }[] { value: 'compact', label: '紧凑', description: '更小的字号与行距,单屏放更多内容' }, ]; +type SettingsTab = 'appearance' | 'data' | 'account'; + +const TABS: { key: SettingsTab; label: string; icon: typeof Sun }[] = [ + { key: 'appearance', label: '外观', icon: Palette }, + { key: 'data', label: '数据刷新', icon: RefreshCw }, + { key: 'account', label: '账号安全', icon: ShieldCheck }, +]; + export function SettingsPage() { - const api = useApi(); - const { onLogout } = useAppState(); - const { - mode, setMode, - accent, setAccent, - radius, setRadius, - density, setDensity, - pollInterval, setPollInterval, - } = useTheme(); - - const [showChangePwd, setShowChangePwd] = useState(false); - const [pwdSavedAt, setPwdSavedAt] = useState(null); - - if (showChangePwd) { - return ( - api.checkPasswordStrength(p)} - submit={(o, n) => api.changePassword(o, n)} - onSuccess={() => { - setShowChangePwd(false); - setPwdSavedAt(Date.now()); - }} - onCancel={() => setShowChangePwd(false)} - /> - ); - } + const [tab, setTab] = useState('appearance'); return ( -
- {/* Appearance */} - - - 外观 - 调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。 - - - {/* Mode */} -
- -
- {MODE_OPTIONS.map((opt) => { - const Icon = opt.icon; - const active = mode === opt.value; - return ( - - ); - })} -
-
+
+ - - - {/* Accent color */} -
- -
- {ACCENTS.map((spec) => { - const active = accent === spec.id; - return ( - - ); - })} -
-

当前:{ACCENTS.find((a) => a.id === accent)?.label}

-
- - - - {/* Radius */} -
- -
- {RADIUS_OPTIONS.map((opt) => { - const active = Math.abs(radius - opt.value) < 1e-6; - return ( - - ); - })} -
-
- - - - {/* Density */} -
- -
- {DENSITY_OPTIONS.map((opt) => { - const active = density === opt.value; - return ( - - ); - })} -
-
- - - - {/* Behavior */} - - - 数据刷新 - 控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。 - - -
- -
- {POLL_INTERVAL_OPTIONS.map((opt) => { - const active = pollInterval === opt.value; - return ( - - ); - })} -
-

当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`}

-
-
-
- - {/* Account */} - - - 账号安全 - WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。 - - - - {pwdSavedAt && ( - - 密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。 - - )} - - - -
-

退出登录

-

立即清除当前浏览器的会话令牌。

- -
-
-
+ {tab === 'appearance' && } + {tab === 'data' && } + {tab === 'account' && }
); } + +// ─────────────── mini tab strip ─────────────── + +function MiniTabs({ tab, onChange }: { tab: SettingsTab; onChange: (t: SettingsTab) => void }) { + return ( +
+ {TABS.map((t) => { + const Icon = t.icon; + const active = tab === t.key; + return ( + + ); + })} +
+ ); +} + +// ─────────────── 外观 ─────────────── + +function AppearancePanel() { + const { mode, setMode, accent, setAccent, radius, setRadius, density, setDensity } = useTheme(); + return ( + + + 外观 + 调整界面的明暗模式、强调色、圆角与密度。所有改动会立即应用并保存到本地。 + + + {/* Mode */} +
+ +
+ {MODE_OPTIONS.map((opt) => { + const Icon = opt.icon; + const active = mode === opt.value; + return ( + + ); + })} +
+
+ + + + {/* Accent color */} +
+ +
+ {ACCENTS.map((spec) => { + const active = accent === spec.id; + return ( + + ); + })} +
+

当前:{ACCENTS.find((a) => a.id === accent)?.label}

+
+ + + + {/* Radius */} +
+ +
+ {RADIUS_OPTIONS.map((opt) => { + const active = Math.abs(radius - opt.value) < 1e-6; + return ( + + ); + })} +
+
+ + + + {/* Density */} +
+ +
+ {DENSITY_OPTIONS.map((opt) => { + const active = density === opt.value; + return ( + + ); + })} +
+
+
+
+ ); +} + +// ─────────────── 数据刷新 ─────────────── + +function DataPanel() { + const { pollInterval, setPollInterval } = useTheme(); + return ( + + + 数据刷新 + 控制总览页轮询刷新 QQ 列表、进程列表与系统状态的间隔。 + + +
+ +
+ {POLL_INTERVAL_OPTIONS.map((opt) => { + const active = pollInterval === opt.value; + return ( + + ); + })} +
+

+ 当前生效值:{pollInterval === 0 ? '已暂停轮询' : `${pollInterval} 毫秒`} +

+
+
+
+ ); +} + +// ─────────────── 账号安全 ─────────────── + +function AccountPanel() { + const { onLogout } = useAppState(); + const [showChangePwd, setShowChangePwd] = useState(false); + const [pwdSavedAt, setPwdSavedAt] = useState(null); + + return ( + + + 账号安全 + WebUI 仅有 admin 一个账号,密码会以 scrypt 哈希形式持久化到 config/webui.json。 + + + + {pwdSavedAt && ( + + 密码已更新({new Date(pwdSavedAt).toLocaleTimeString()})— 其他设备的会话已失效。 + + )} + + + +
+

退出登录

+

立即清除当前浏览器的会话令牌。

+ +
+
+ + setPwdSavedAt(Date.now())} + /> +
+ ); +} diff --git a/packages/webui/src/components/pages/status-screens.tsx b/packages/webui/src/components/pages/status-screens.tsx new file mode 100644 index 00000000..b2c290ee --- /dev/null +++ b/packages/webui/src/components/pages/status-screens.tsx @@ -0,0 +1,95 @@ +import type { ReactNode } from 'react'; +import { motion } from 'motion/react'; +import { AlertTriangle, Compass, Home, RotateCw } from 'lucide-react'; +import { Button } from '@/components/ui/button'; + +type Tone = 'primary' | 'destructive'; + +function StatusShell({ + tone, + icon, + code, + title, + description, + children, +}: { + tone: Tone; + icon: ReactNode; + code?: string; + title: string; + description: string; + children: ReactNode; +}) { + return ( +
+ +
+ {icon} +
+ {code && ( + + {code} + + )} +

{title}

+

{description}

+
{children}
+
+
+ ); +} + +/** Rendered by the router for any unmatched path. */ +export function NotFoundPage() { + return ( + } + code="404" + title="页面不存在" + description="你访问的地址没有对应的页面,可能链接已失效或输入有误。" + > + + + ); +} + +/** Rendered by the router when a route component throws while rendering. */ +export function ErrorPage({ error, reset }: { error?: Error; reset?: () => void }) { + const message = error?.message?.trim(); + return ( + } + title="页面出错了" + description="渲染该页面时发生了意外错误。可以重试,或返回首页继续操作。" + > + {reset && ( + + )} + + {message && ( +
+          {message}
+        
+ )} +
+ ); +} diff --git a/packages/webui/src/components/ui/dialog.tsx b/packages/webui/src/components/ui/dialog.tsx index 4352566a..91a115d8 100644 --- a/packages/webui/src/components/ui/dialog.tsx +++ b/packages/webui/src/components/ui/dialog.tsx @@ -32,7 +32,11 @@ const DialogContent = React.forwardRef< , + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetTitle.displayName = 'SheetTitle'; + +const SheetDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetDescription.displayName = 'SheetDescription'; + +export { + Sheet, + SheetTrigger, + SheetClose, + SheetContent, + SheetPortal, + SheetOverlay, + SheetTitle, + SheetDescription, +}; diff --git a/packages/webui/src/contexts/AppStateContext.tsx b/packages/webui/src/contexts/AppStateContext.tsx index 2b8e35ce..adb54042 100644 --- a/packages/webui/src/contexts/AppStateContext.tsx +++ b/packages/webui/src/contexts/AppStateContext.tsx @@ -1,5 +1,5 @@ import { createContext, useContext, type ReactNode } from 'react'; -import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types'; +import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types'; import type { HookProcessOps } from '@/hooks/use-hook-process-ops'; /** @@ -12,11 +12,13 @@ export interface AppStateValue { qqList: QQInfo[]; processList: HookProcessInfo[]; systemInfo: SystemInfo | null; + connections: AccountConnections[]; selectedUin: string | null; setSelectedUin: (uin: string | null) => void; processOps: HookProcessOps; refreshProcesses: () => void; refreshSystem: () => void; + refreshConnections: () => void; /** Triggered from the topbar logout button. */ onLogout: () => void; } diff --git a/packages/webui/src/hooks/use-onebot-instance-config.ts b/packages/webui/src/hooks/use-onebot-instance-config.ts index dc4b2cd0..b3d61031 100644 --- a/packages/webui/src/hooks/use-onebot-instance-config.ts +++ b/packages/webui/src/hooks/use-onebot-instance-config.ts @@ -25,7 +25,13 @@ export interface UseOneBotInstanceConfig { pendingSwitchUin: string | null; confirmSwitch: () => void; cancelSwitch: () => void; - save: () => Promise; + /** + * Persist to the backend. Pass an explicit config to save it directly — + * the node dialog / enable-toggle / delete persist their freshly-computed + * config in the same tick, before React has flushed `setConfig`, so they + * can't rely on the (still-stale) closed-over `config`. + */ + save: (override?: OneBotConfig) => Promise; saveStatus: string; } @@ -117,11 +123,12 @@ export function useOneBotInstanceConfig( }, CLEAR_SAVE_STATUS_MS); }, []); - const save = useCallback(async () => { - if (!selectedUin || !config) return; + const save = useCallback(async (override?: OneBotConfig) => { + const target = override ?? config; + if (!selectedUin || !target) return; setSaveStatus('保存中...'); try { - const serverView = await api.config.save(selectedUin, config); + const serverView = await api.config.save(selectedUin, target); setConfigState(serverView); setSavedSnapshot(JSON.stringify(serverView)); setSaveStatus('保存成功'); diff --git a/packages/webui/src/lib/api/client.ts b/packages/webui/src/lib/api/client.ts index 617de321..82718136 100644 --- a/packages/webui/src/lib/api/client.ts +++ b/packages/webui/src/lib/api/client.ts @@ -1,4 +1,4 @@ -import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types'; +import type { AccountConnections, HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types'; import type { PasswordRule } from '@/components/pages/change-password-page'; import { normalizeOneBotConfig } from '@/lib/onebot-config'; import { @@ -222,6 +222,10 @@ class HttpApiClient implements ApiClient { return this.getJson('/api/system'); } + connections(): Promise { + return this.getJson<{ list: AccountConnections[] }>('/api/connections').then((d) => d.list ?? []); + } + // ---------- SSE ---------- private openLogStream(options: LogsStreamOptions): () => void { diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 83beb3a0..4644fba5 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -1,4 +1,5 @@ import type { + AccountConnections, HookProcessInfo, LogEntry, LogLevel, @@ -50,6 +51,8 @@ export interface ApiClient { // ---- system ---- qqList(): Promise; system(): Promise; + /** Live OneBot adapter health per account. */ + connections(): Promise; // ---- hook processes ---- processes: { diff --git a/packages/webui/src/router/app-layout.tsx b/packages/webui/src/router/app-layout.tsx index 7fd5d9f6..c6b7b1c0 100644 --- a/packages/webui/src/router/app-layout.tsx +++ b/packages/webui/src/router/app-layout.tsx @@ -8,7 +8,7 @@ import { ConfirmDialog } from '@/components/confirm-dialog'; import { Skeleton } from '@/components/ui/skeleton'; import { AppStateProvider } from '@/contexts/AppStateContext'; import { useSession } from '@/contexts/SessionContext'; -import type { HookProcessInfo, QQInfo, SystemInfo } from '@/types'; +import type { AccountConnections, HookProcessInfo, QQInfo, SystemInfo } from '@/types'; /** * The layout route. Owns the live state shared across the four pages @@ -24,6 +24,7 @@ export function AppLayout() { const [qqList, setQqList] = useState([]); const [processList, setProcessList] = useState([]); const [systemInfo, setSystemInfo] = useState(null); + const [connections, setConnections] = useState([]); const [selectedUin, setSelectedUin] = useState(null); const refreshQqList = useCallback(async () => { @@ -50,6 +51,14 @@ export function AppLayout() { } }, [api]); + const refreshConnections = useCallback(async () => { + try { + setConnections(await api.connections()); + } catch (e) { + console.error('connections', e); + } + }, [api]); + const { ops: processOps, unloadFailedAlert, dismissUnloadFailedAlert } = useHookProcessOps({ onAfterOp: refreshProcesses, }); @@ -59,7 +68,7 @@ export function AppLayout() { let cancelled = false; const tick = async () => { if (cancelled) return; - await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem()]); + await Promise.all([refreshQqList(), refreshProcesses(), refreshSystem(), refreshConnections()]); }; tick(); const interval = setInterval(tick, pollInterval); @@ -67,13 +76,14 @@ export function AppLayout() { cancelled = true; clearInterval(interval); }; - }, [pollInterval, refreshQqList, refreshProcesses, refreshSystem]); + }, [pollInterval, refreshQqList, refreshProcesses, refreshSystem, refreshConnections]); const handleLogout = useCallback(async () => { await api.logout(); setQqList([]); setProcessList([]); setSystemInfo(null); + setConnections([]); setSelectedUin(null); session.onLogoutComplete(); }, [api, session]); @@ -84,11 +94,13 @@ export function AppLayout() { qqList, processList, systemInfo, + connections, selectedUin, setSelectedUin, processOps, refreshProcesses, refreshSystem, + refreshConnections, onLogout: handleLogout, }} > diff --git a/packages/webui/src/router/index.tsx b/packages/webui/src/router/index.tsx index 791dc490..238f1edc 100644 --- a/packages/webui/src/router/index.tsx +++ b/packages/webui/src/router/index.tsx @@ -6,6 +6,9 @@ import { Outlet, } from '@tanstack/react-router'; import { AppLayout } from './app-layout'; +// Imported eagerly (not lazy): the error / not-found fallbacks must render +// even when a route's own chunk failed to load. +import { ErrorPage, NotFoundPage } from '@/components/pages/status-screens'; // Page components are loaded on demand so the initial paint only ships // the auth surface + layout shell. With `defaultPreload: 'intent'` set @@ -34,6 +37,15 @@ const overviewRoute = createRoute({ ), }); +const processesRoute = createRoute({ + path: '/processes', + getParentRoute: () => appLayoutRoute, + component: lazyRouteComponent( + () => import('@/components/pages/processes-page'), + 'ProcessesPage', + ), +}); + const configRoute = createRoute({ path: '/config', getParentRoute: () => appLayoutRoute, @@ -62,12 +74,14 @@ const settingsRoute = createRoute({ }); const routeTree = rootRoute.addChildren([ - appLayoutRoute.addChildren([overviewRoute, configRoute, logsRoute, settingsRoute]), + appLayoutRoute.addChildren([overviewRoute, processesRoute, configRoute, logsRoute, settingsRoute]), ]); export const appRouter = createRouter({ routeTree, defaultPreload: 'intent', + defaultNotFoundComponent: () => , + defaultErrorComponent: ({ error, reset }) => , }); declare module '@tanstack/react-router' { @@ -77,4 +91,4 @@ declare module '@tanstack/react-router' { } /** Paths registered on the layout — single source of truth for nav metadata. */ -export type AppPath = '/' | '/config' | '/logs' | '/settings'; +export type AppPath = '/' | '/processes' | '/config' | '/logs' | '/settings'; diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index ef65d96a..ba814615 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -7,6 +7,21 @@ export interface QQInfo { nickname: string; } +export type AdapterStatusLevel = 'ok' | 'warn' | 'down' | 'disabled'; + +export interface AdapterStatus { + name: string; + kind: 'httpServer' | 'httpClient' | 'wsServer' | 'wsClient'; + status: AdapterStatusLevel; + detail: string; +} + +export interface AccountConnections { + uin: string; + nickname: string; + adapters: AdapterStatus[]; +} + export interface HookProcessInfo { pid: number; name: string; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index fb96ef9f..2715a2c4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -102,9 +102,6 @@ importers: '@snowluma/proton': specifier: workspace:* version: link:../proton - '@snowluma/sqlite': - specifier: workspace:* - version: link:../sqlite '@snowluma/websocket': specifier: workspace:* version: link:../websocket @@ -157,9 +154,6 @@ importers: '@snowluma/proton': specifier: workspace:* version: link:../proton - '@snowluma/sqlite': - specifier: workspace:* - version: link:../sqlite '@snowluma/websocket': specifier: workspace:* version: link:../websocket @@ -201,9 +195,6 @@ importers: '@snowluma/proton': specifier: workspace:* version: link:../proton - '@snowluma/sqlite': - specifier: workspace:* - version: link:../sqlite devDependencies: '@types/node': specifier: ^24.12.2 @@ -251,21 +242,6 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(@vitest/coverage-istanbul@4.1.4)(@vitest/coverage-v8@4.1.4)(vite@8.0.8(@types/node@24.12.2)(esbuild@0.27.7)(jiti@2.6.1)(sass@1.99.0)(tsx@4.21.0)) - packages/sqlite: - devDependencies: - '@types/better-sqlite3': - specifier: ^7.6.13 - version: 7.6.13 - '@types/node': - specifier: ^24.12.2 - version: 24.12.2 - better-sqlite3: - specifier: 12.10.0 - version: 12.10.0 - typescript: - specifier: 'catalog:' - version: 6.0.2 - packages/ui: dependencies: '@radix-ui/react-alert-dialog': @@ -1695,9 +1671,6 @@ packages: '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} - '@types/better-sqlite3@7.6.13': - resolution: {integrity: sha512-NMv9ASNARoKksWtsq/SHakpYAYnhBrQgGD8zkLYk/jaK8jUGn08CfEdTRgYhMypUQAfzSP8W6gNLe0q19/t4VA==} - '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -1891,24 +1864,11 @@ packages: base-log-factory@2.1.4: resolution: {integrity: sha512-FK1tHOB+rXvlBcGYYhSNR2QS2juEG4SZ1ekXQRQ2XscYNtDxllzqkzfgBFr12EVrKb2/07NLdbr0cSwVoc378A==} - base64-js@1.5.1: - resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} - baseline-browser-mapping@2.10.19: resolution: {integrity: sha512-qCkNLi2sfBOn8XhZQ0FXsT1Ki/Yo5P90hrkRamVFRS7/KV9hpfA4HkoWNU152+8w0zPjnxo5psx5NL3PSGgv5g==} engines: {node: '>=6.0.0'} hasBin: true - better-sqlite3@12.10.0: - resolution: {integrity: sha512-CyzaZRQKyHkB2ZInfTTl2nvT33EbDpjkLEbE8/Zck3Ll6O0qqvuGdrJ45HgtH+HykRg88ITY3AdreBGN70aBSQ==} - engines: {node: 20.x || 22.x || 23.x || 24.x || 25.x || 26.x} - - bindings@1.5.0: - resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} - - bl@4.1.0: - resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} - blf-colorful-appender@1.0.6: resolution: {integrity: sha512-MdwOI17J8iOC2XKi5b4VagAJg308R4QesRoCAPw/w7ihzwkTst91LvkTAF3GvPJCEaHXptiUS2UsFkCNiBIEGg==} @@ -1924,9 +1884,6 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true - buffer@5.7.1: - resolution: {integrity: sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==} - bundle-require@5.1.0: resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} @@ -1948,9 +1905,6 @@ packages: resolution: {integrity: sha512-Qgzu8kfBvo+cA4962jnP1KkS6Dop5NS6g7R5LFYJr4b8Ub94PPQXUksCw9PvXoeXPRRddRNC5C1JQUR2SMGtnA==} engines: {node: '>= 14.16.0'} - chownr@1.1.4: - resolution: {integrity: sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==} - class-variance-authority@0.7.1: resolution: {integrity: sha512-Ka+9Trutv7G8M6WT6SeiRWz792K5qEqIGEGzXKhAE6xOWAY6pPH8U+9IY3oCMv6kqTmLsv7Xh/2w2RigkePMsg==} @@ -2003,14 +1957,6 @@ packages: supports-color: optional: true - decompress-response@6.0.0: - resolution: {integrity: sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==} - engines: {node: '>=10'} - - deep-extend@0.6.0: - resolution: {integrity: sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA==} - engines: {node: '>=4.0.0'} - deep-is@0.1.4: resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==} @@ -2028,9 +1974,6 @@ packages: electron-to-chromium@1.5.339: resolution: {integrity: sha512-Is+0BBHJ4NrdpAYiperrmp53pLywG/yV/6lIMTAnhxvzj/Cmn5Q/ogSHC6AKe7X+8kPLxxFk0cs5oc/3j/fxIg==} - end-of-stream@1.4.5: - resolution: {integrity: sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==} - enhanced-resolve@5.20.1: resolution: {integrity: sha512-Qohcme7V1inbAfvjItgw0EaxVX5q2rdVEZHRBrEQdRZTssLDGsL8Lwrznl8oQ/6kuTJONLaDcGjkNP247XEhcA==} engines: {node: '>=10.13.0'} @@ -2114,10 +2057,6 @@ packages: resolution: {integrity: sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==} engines: {node: '>=0.10.0'} - expand-template@2.0.3: - resolution: {integrity: sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg==} - engines: {node: '>=6'} - expect-type@1.3.0: resolution: {integrity: sha512-knvyeauYhqjOYvQ66MznSMs83wmHrCycNEN6Ao+2AeYEfxUIkuiVxdEa1qlGEPK+We3n0THiDciYSsCcgW/DoA==} engines: {node: '>=12.0.0'} @@ -2149,9 +2088,6 @@ packages: resolution: {integrity: sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==} engines: {node: '>=16.0.0'} - file-uri-to-path@1.0.0: - resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} - find-up@5.0.0: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} @@ -2180,9 +2116,6 @@ packages: react-dom: optional: true - fs-constants@1.0.0: - resolution: {integrity: sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow==} - fs-extra@11.3.4: resolution: {integrity: sha512-CTXd6rk/M3/ULNQj8FBqBWHYBVYybQ3VPBw0xGKFe3tuH7ytT6ACnvzpIQ3UZtB8yvUKC2cXn1a+x+5EVQLovA==} engines: {node: '>=14.14'} @@ -2206,9 +2139,6 @@ packages: get-tsconfig@4.14.0: resolution: {integrity: sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA==} - github-from-package@0.0.0: - resolution: {integrity: sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw==} - glob-parent@6.0.2: resolution: {integrity: sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==} engines: {node: '>=10.13.0'} @@ -2241,9 +2171,6 @@ packages: html-escaper@2.0.2: resolution: {integrity: sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==} - ieee754@1.2.1: - resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} - ignore@5.3.2: resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==} engines: {node: '>= 4'} @@ -2259,12 +2186,6 @@ packages: resolution: {integrity: sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==} engines: {node: '>=0.8.19'} - inherits@2.0.4: - resolution: {integrity: sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==} - - ini@1.3.8: - resolution: {integrity: sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==} - is-core-module@2.16.1: resolution: {integrity: sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==} engines: {node: '>= 0.4'} @@ -2452,20 +2373,10 @@ packages: resolution: {integrity: sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==} engines: {node: '>=10'} - mimic-response@3.1.0: - resolution: {integrity: sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==} - engines: {node: '>=10'} - minimatch@10.2.5: resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} engines: {node: 18 || 20 || >=22} - minimist@1.2.8: - resolution: {integrity: sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==} - - mkdirp-classic@0.5.3: - resolution: {integrity: sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A==} - mlly@1.8.2: resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} @@ -2500,16 +2411,9 @@ packages: engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} hasBin: true - napi-build-utils@2.0.0: - resolution: {integrity: sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA==} - natural-compare@1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} - node-abi@3.92.0: - resolution: {integrity: sha512-KdHvFWZjEKDf0cakgFjebl371GPsISX2oZHcuyKqM7DtogIsHrqKeLTo8wBHxaXRAQlY2PsPlZmfo+9ZCxEREQ==} - engines: {node: '>=10'} - node-addon-api@7.1.1: resolution: {integrity: sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==} @@ -2523,9 +2427,6 @@ packages: obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} - once@1.4.0: - resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==} - optionator@0.9.4: resolution: {integrity: sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==} engines: {node: '>= 0.8.0'} @@ -2588,27 +2489,14 @@ packages: resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==} engines: {node: ^10 || ^12 || >=14} - prebuild-install@7.1.3: - resolution: {integrity: sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug==} - engines: {node: '>=10'} - deprecated: No longer maintained. Please contact the author of the relevant native addon; alternatives are available. - hasBin: true - prelude-ls@1.2.1: resolution: {integrity: sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==} engines: {node: '>= 0.8.0'} - pump@3.0.4: - resolution: {integrity: sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==} - punycode@2.3.1: resolution: {integrity: sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==} engines: {node: '>=6'} - rc@1.2.8: - resolution: {integrity: sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw==} - hasBin: true - react-dom@19.2.5: resolution: {integrity: sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag==} peerDependencies: @@ -2648,10 +2536,6 @@ packages: resolution: {integrity: sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA==} engines: {node: '>=0.10.0'} - readable-stream@3.6.2: - resolution: {integrity: sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==} - engines: {node: '>= 6'} - readdirp@4.1.2: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} @@ -2678,9 +2562,6 @@ packages: engines: {node: '>=18.0.0', npm: '>=8.0.0'} hasBin: true - safe-buffer@5.2.1: - resolution: {integrity: sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==} - sass@1.99.0: resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} engines: {node: '>=14.0.0'} @@ -2719,12 +2600,6 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} - simple-concat@1.0.1: - resolution: {integrity: sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==} - - simple-get@4.0.1: - resolution: {integrity: sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==} - sonner@2.0.7: resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==} peerDependencies: @@ -2745,13 +2620,6 @@ packages: std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} - string_decoder@1.3.0: - resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} - - strip-json-comments@2.0.1: - resolution: {integrity: sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==} - engines: {node: '>=0.10.0'} - sucrase@3.35.1: resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} engines: {node: '>=16 || 14 >=14.17'} @@ -2775,13 +2643,6 @@ packages: resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==} engines: {node: '>=6'} - tar-fs@2.1.4: - resolution: {integrity: sha512-mDAjwmZdh7LTT6pNleZ05Yt65HC3E+NiQzl672vQG38jIrehtJk/J3mNwIg+vShQPcLF/LV7CMnDW6vjj6sfYQ==} - - tar-stream@2.2.0: - resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} - engines: {node: '>=6'} - thenify-all@1.6.0: resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} engines: {node: '>=0.8'} @@ -2847,9 +2708,6 @@ packages: engines: {node: '>=18.0.0'} hasBin: true - tunnel-agent@0.6.0: - resolution: {integrity: sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w==} - tw-animate-css@1.4.0: resolution: {integrity: sha512-7bziOlRqH0hJx80h/3mbicLW7o8qLsH5+RaLR2t+OHM3D0JlWGODQKQ4cxbK7WlvmUxpcj6Kgu6EKqjrGFe3QQ==} @@ -2916,9 +2774,6 @@ packages: peerDependencies: react: ^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 - util-deprecate@1.0.2: - resolution: {integrity: sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==} - vite-plugin-cp@6.0.3: resolution: {integrity: sha512-qxKGH3v9wPwUDbDchJf4IH4mRE1zkLWgzZSxwrl8LapwUWm48IFS7SlbRmcF4NquC/fESA5cHFge9E2Ps+woxg==} engines: {node: '>=14.18.0', vite: '>=3.1.0'} @@ -3025,9 +2880,6 @@ packages: resolution: {integrity: sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==} engines: {node: '>=0.10.0'} - wrappy@1.0.2: - resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} - yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} @@ -4075,10 +3927,6 @@ snapshots: tslib: 2.8.1 optional: true - '@types/better-sqlite3@7.6.13': - dependencies: - '@types/node': 25.6.0 - '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -4326,25 +4174,8 @@ snapshots: date-manip: 2.0.6 is-what-type: 1.1.4 - base64-js@1.5.1: {} - baseline-browser-mapping@2.10.19: {} - better-sqlite3@12.10.0: - dependencies: - bindings: 1.5.0 - prebuild-install: 7.1.3 - - bindings@1.5.0: - dependencies: - file-uri-to-path: 1.0.0 - - bl@4.1.0: - dependencies: - buffer: 5.7.1 - inherits: 2.0.4 - readable-stream: 3.6.2 - blf-colorful-appender@1.0.6: dependencies: base-log-factory: 2.1.4 @@ -4372,11 +4203,6 @@ snapshots: node-releases: 2.0.37 update-browserslist-db: 1.2.3(browserslist@4.28.2) - buffer@5.7.1: - dependencies: - base64-js: 1.5.1 - ieee754: 1.2.1 - bundle-require@5.1.0(esbuild@0.27.7): dependencies: esbuild: 0.27.7 @@ -4392,8 +4218,6 @@ snapshots: dependencies: readdirp: 4.1.2 - chownr@1.1.4: {} - class-variance-authority@0.7.1: dependencies: clsx: 2.1.1 @@ -4431,12 +4255,6 @@ snapshots: dependencies: ms: 2.1.3 - decompress-response@6.0.0: - dependencies: - mimic-response: 3.1.0 - - deep-extend@0.6.0: {} - deep-is@0.1.4: {} deepmerge@4.3.1: {} @@ -4447,10 +4265,6 @@ snapshots: electron-to-chromium@1.5.339: {} - end-of-stream@1.4.5: - dependencies: - once: 1.4.0 - enhanced-resolve@5.20.1: dependencies: graceful-fs: 4.2.11 @@ -4580,8 +4394,6 @@ snapshots: esutils@2.0.3: {} - expand-template@2.0.3: {} - expect-type@1.3.0: {} fast-deep-equal@3.1.3: {} @@ -4602,8 +4414,6 @@ snapshots: dependencies: flat-cache: 4.0.1 - file-uri-to-path@1.0.0: {} - find-up@5.0.0: dependencies: locate-path: 6.0.0 @@ -4631,8 +4441,6 @@ snapshots: react: 19.2.5 react-dom: 19.2.5(react@19.2.5) - fs-constants@1.0.0: {} - fs-extra@11.3.4: dependencies: graceful-fs: 4.2.11 @@ -4652,8 +4460,6 @@ snapshots: dependencies: resolve-pkg-maps: 1.0.0 - github-from-package@0.0.0: {} - glob-parent@6.0.2: dependencies: is-glob: 4.0.3 @@ -4678,8 +4484,6 @@ snapshots: html-escaper@2.0.2: {} - ieee754@1.2.1: {} - ignore@5.3.2: {} ignore@7.0.5: {} @@ -4689,10 +4493,6 @@ snapshots: imurmurhash@0.1.4: {} - inherits@2.0.4: {} - - ini@1.3.8: {} - is-core-module@2.16.1: dependencies: hasown: 2.0.2 @@ -4838,16 +4638,10 @@ snapshots: dependencies: semver: 7.7.4 - mimic-response@3.1.0: {} - minimatch@10.2.5: dependencies: brace-expansion: 5.0.5 - minimist@1.2.8: {} - - mkdirp-classic@0.5.3: {} - mlly@1.8.2: dependencies: acorn: 8.16.0 @@ -4879,14 +4673,8 @@ snapshots: nanoid@3.3.11: {} - napi-build-utils@2.0.0: {} - natural-compare@1.4.0: {} - node-abi@3.92.0: - dependencies: - semver: 7.7.4 - node-addon-api@7.1.1: optional: true @@ -4896,10 +4684,6 @@ snapshots: obug@2.1.1: {} - once@1.4.0: - dependencies: - wrappy: 1.0.2 - optionator@0.9.4: dependencies: deep-is: 0.1.4 @@ -4951,37 +4735,10 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 - prebuild-install@7.1.3: - dependencies: - detect-libc: 2.1.2 - expand-template: 2.0.3 - github-from-package: 0.0.0 - minimist: 1.2.8 - mkdirp-classic: 0.5.3 - napi-build-utils: 2.0.0 - node-abi: 3.92.0 - pump: 3.0.4 - rc: 1.2.8 - simple-get: 4.0.1 - tar-fs: 2.1.4 - tunnel-agent: 0.6.0 - prelude-ls@1.2.1: {} - pump@3.0.4: - dependencies: - end-of-stream: 1.4.5 - once: 1.4.0 - punycode@2.3.1: {} - rc@1.2.8: - dependencies: - deep-extend: 0.6.0 - ini: 1.3.8 - minimist: 1.2.8 - strip-json-comments: 2.0.1 - react-dom@19.2.5(react@19.2.5): dependencies: react: 19.2.5 @@ -5016,12 +4773,6 @@ snapshots: react@19.2.5: {} - readable-stream@3.6.2: - dependencies: - inherits: 2.0.4 - string_decoder: 1.3.0 - util-deprecate: 1.0.2 - readdirp@4.1.2: {} resolve-from@5.0.0: {} @@ -5087,8 +4838,6 @@ snapshots: '@rollup/rollup-win32-x64-msvc': 4.60.4 fsevents: 2.3.3 - safe-buffer@5.2.1: {} - sass@1.99.0: dependencies: chokidar: 4.0.3 @@ -5118,14 +4867,6 @@ snapshots: siginfo@2.0.0: {} - simple-concat@1.0.1: {} - - simple-get@4.0.1: - dependencies: - decompress-response: 6.0.0 - once: 1.4.0 - simple-concat: 1.0.1 - sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5): dependencies: react: 19.2.5 @@ -5139,12 +4880,6 @@ snapshots: std-env@4.1.0: {} - string_decoder@1.3.0: - dependencies: - safe-buffer: 5.2.1 - - strip-json-comments@2.0.1: {} - sucrase@3.35.1: dependencies: '@jridgewell/gen-mapping': 0.3.13 @@ -5167,21 +4902,6 @@ snapshots: tapable@2.3.2: {} - tar-fs@2.1.4: - dependencies: - chownr: 1.1.4 - mkdirp-classic: 0.5.3 - pump: 3.0.4 - tar-stream: 2.2.0 - - tar-stream@2.2.0: - dependencies: - bl: 4.1.0 - end-of-stream: 1.4.5 - fs-constants: 1.0.0 - inherits: 2.0.4 - readable-stream: 3.6.2 - thenify-all@1.6.0: dependencies: thenify: 3.3.1 @@ -5248,10 +4968,6 @@ snapshots: optionalDependencies: fsevents: 2.3.3 - tunnel-agent@0.6.0: - dependencies: - safe-buffer: 5.2.1 - tw-animate-css@1.4.0: {} type-check@0.4.0: @@ -5308,8 +5024,6 @@ snapshots: dependencies: react: 19.2.5 - util-deprecate@1.0.2: {} - vite-plugin-cp@6.0.3: dependencies: fs-extra: 11.3.4 @@ -5400,8 +5114,6 @@ snapshots: word-wrap@1.2.5: {} - wrappy@1.0.2: {} - yallist@3.1.1: {} yocto-queue@0.1.0: {} diff --git a/tools/fetch-sqlite-prebuilts.mjs b/tools/fetch-sqlite-prebuilts.mjs deleted file mode 100644 index 0af48024..00000000 --- a/tools/fetch-sqlite-prebuilts.mjs +++ /dev/null @@ -1,121 +0,0 @@ -#!/usr/bin/env node -// Downloads better-sqlite3 prebuilt native bindings for all SnowLuma -// CI matrix targets (win32-x64, linux-x64, linux-arm64) plus the -// developer host (darwin-arm64 / darwin-x64) and vendors them into -// `packages/runtime/native/better-sqlite3--.node`. -// -// vite-plugin-cp picks the matching binary for `SNOWLUMA_TARGET` -// during `pnpm build` and copies it into `dist/native/`, where -// `@snowluma/sqlite/index.ts` finds it at runtime. Naming + layout -// mirror the existing `websocket--.node` convention -// (flat dir, dash-separated triplet) so SnowLuma's existing -// per-target packaging step doesn't need a new code path. -// -// Usage: -// node tools/fetch-sqlite-prebuilts.mjs # default version -// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 # explicit version -// -// Re-run when bumping the better-sqlite3 pin in -// `packages/sqlite/package.json`. The script is idempotent — -// existing binaries with the same SHA256 are left alone. - -import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join, dirname } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { spawnSync } from 'node:child_process'; - -const __dirname = dirname(fileURLToPath(import.meta.url)); -const repoRoot = join(__dirname, '..'); -const nativeRoot = join(repoRoot, 'packages', 'runtime', 'native'); - -// Default NODE_MODULE_VERSIONs to vendor. v127 = Node 22 LTS (matches -// the CI matrix + `engines.node: ">=22"`). v137 = Node 24 (covers dev -// boxes already on the newer release). Pass extra versions positionally -// after the better-sqlite3 version to add more: -// node tools/fetch-sqlite-prebuilts.mjs 11.10.0 v127 v137 v115 -const DEFAULT_NODE_ABIS = ['v127', 'v137']; - -// The targets vendored into the repo. linuxmusl-* variants are -// available too (for Alpine-based Docker images) but SnowLuma's -// existing native vendoring (websocket / ffmpeg) only ships glibc -// Linux, so we follow that lead. Add musl entries here if/when a -// downstream Alpine consumer asks. -const TARGETS = [ - { triplet: 'darwin-arm64', prebuildName: 'darwin-arm64' }, - { triplet: 'darwin-x64', prebuildName: 'darwin-x64' }, - { triplet: 'linux-arm64', prebuildName: 'linux-arm64' }, - { triplet: 'linux-x64', prebuildName: 'linux-x64' }, - { triplet: 'win32-x64', prebuildName: 'win32-x64' }, -]; - -async function main() { - const version = process.argv[2] ?? readVersionFromPin(); - const abis = process.argv.slice(3).filter(a => a.startsWith('v')); - const targetAbis = abis.length > 0 ? abis : DEFAULT_NODE_ABIS; - console.log(`fetching better-sqlite3 v${version} prebuilds (ABIs: ${targetAbis.join(', ')})`); - - mkdirSync(nativeRoot, { recursive: true }); - for (const abi of targetAbis) { - for (const target of TARGETS) { - const destBin = join(nativeRoot, `better-sqlite3-${abi}-${target.triplet}.node`); - if (existsSync(destBin)) { - console.log(` ✓ ${abi} ${target.triplet} (already vendored, skipping)`); - continue; - } - - const url = `https://github.com/WiseLibs/better-sqlite3/releases/download/v${version}/better-sqlite3-v${version}-node-${abi}-${target.prebuildName}.tar.gz`; - console.log(` ↓ ${abi} ${target.triplet}: ${url}`); - - const tarPath = join(tmpdir(), `better-sqlite3-${version}-${abi}-${target.triplet}.tar.gz`); - await downloadTo(url, tarPath); - extractBinding(tarPath, destBin); - console.log(` → ${destBin}`); - } - } - - console.log('done.'); -} - -function readVersionFromPin() { - const pkg = JSON.parse(readFileSync(join(repoRoot, 'packages', 'sqlite', 'package.json'), 'utf8')); - const raw = pkg.devDependencies?.['better-sqlite3']; - if (!raw) { - throw new Error('cannot find better-sqlite3 pin in packages/sqlite/package.json'); - } - // strip the `^` / `~` / `>=` etc prefix. - return raw.replace(/^[\^~>=<]+/, ''); -} - -async function downloadTo(url, dest) { - // curl is in every CI image SnowLuma cares about (and on every - // dev mac/linux), so we just shell out — keeps this script free - // of npm dependencies, which matters because pnpm install hasn't - // necessarily run yet when someone clones the repo fresh. - const result = spawnSync('curl', ['-fsSL', '--retry', '3', '-o', dest, url], { stdio: 'inherit' }); - if (result.status !== 0) { - throw new Error(`curl failed for ${url} (exit ${result.status})`); - } -} - -function extractBinding(tarPath, destBin) { - // The prebuild archive is `build/Release/better_sqlite3.node` - // wrapped in the standard better-sqlite3 layout. We capture tar's - // stdout as a buffer (spawnSync's `stdio: 'pipe'` + `encoding: null`) - // and write that buffer to the destination — simpler than wiring - // a Node WriteStream which spawnSync's stdio doesn't accept. - const result = spawnSync( - 'tar', - ['-xzOf', tarPath, '--strip-components=2', 'build/Release/better_sqlite3.node'], - { stdio: ['ignore', 'pipe', 'inherit'], encoding: null, maxBuffer: 64 * 1024 * 1024 }, - ); - if (result.status !== 0) { - throw new Error(`tar failed for ${tarPath} (exit ${result.status})`); - } - writeFileSync(destBin, result.stdout); -} - -main().catch((err) => { - console.error(err); - process.exit(1); -});