From ad65aa5b1b89de684d24baa597a02091a91b1e3e Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 16 May 2026 11:55:36 +0800 Subject: [PATCH 01/51] fix(send): resolve at-mention display name from the group roster OneBot clients commonly send [CQ:at,qq=12345] without a name field; we were piping `@12345` into the text element so QQ rendered the bare uin instead of the member's card/nickname (napcat resolves via getGroupMember before encoding). Move the fallback into the element builder so it consults the IdentityService roster and only falls back to the uin when the roster has nothing. --- packages/core/src/bridge/actions/forward.ts | 8 ++++-- packages/core/src/bridge/element-builder.ts | 32 ++++++++++++++++++--- packages/core/src/onebot/message-parser.ts | 13 +++++---- 3 files changed, 41 insertions(+), 12 deletions(-) diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 0181a5fc..6558c4b7 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -28,12 +28,16 @@ const forwardResCache = new Map(); async function buildForwardPushBody( bridge: Bridge, node: ForwardNodePayload, + groupId?: number, ): Promise> { const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); if (fromUin <= 0) throw new Error('forward node user uin is invalid'); const nickname = node.nickname.trim() || String(fromUin); - const elems = await buildSendElems(node.elements); + const sendCtx = groupId !== undefined + ? { bridge, groupId } + : { bridge }; + const elems = await buildSendElems(node.elements, sendCtx); const now = Math.floor(Date.now() / 1000); const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; const seq = Math.floor(Math.random() * 9000000) + 1000000; @@ -67,7 +71,7 @@ export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePaylo throw new Error('forward nodes are required'); } - const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node))); + const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId))); const longMsgResult = protoEncode({ action: [ { diff --git a/packages/core/src/bridge/element-builder.ts b/packages/core/src/bridge/element-builder.ts index b07f7980..74217fd4 100644 --- a/packages/core/src/bridge/element-builder.ts +++ b/packages/core/src/bridge/element-builder.ts @@ -37,19 +37,43 @@ function makeFaceElem(faceId: number): ProtoElem { }; } -function makeMentionElem(element: MessageElement): ProtoElem { +function resolveMentionDisplay(ctx: SendContext | undefined, targetUin: number): string { + if (!ctx || !targetUin) return ''; + if (ctx.groupId !== undefined) { + const member = ctx.bridge.identity.findGroupMember(ctx.groupId, targetUin); + return member?.card?.trim() || member?.nickname?.trim() || ''; + } + const friend = ctx.bridge.identity.findFriend(targetUin); + return friend?.remark?.trim() || friend?.nickname?.trim() || ''; +} + +function makeMentionElem(element: MessageElement, ctx?: SendContext): ProtoElem { const mentionAll = element.uid === 'all' || element.targetUin === 0; + const targetUin = element.targetUin ?? 0; const extra = protoEncode({ type: mentionAll ? 1 : 2, - uin: mentionAll ? 0 : (element.targetUin ?? 0), + uin: mentionAll ? 0 : targetUin, field5: 0, uid: mentionAll ? 'all' : (element.uid ?? ''), }, MentionExtraSendSchema); + // Prefer an explicit display string from the caller; otherwise look the + // target up in the roster so QQ renders `@昵称` instead of `@QQ号`. + // Falls back to the bare uin when the roster doesn't know them yet. + let str = element.text; + if (!str) { + if (mentionAll) { + str = '@全体成员 '; + } else { + const name = resolveMentionDisplay(ctx, targetUin); + str = name ? `@${name} ` : `@${targetUin} `; + } + } + return { text: { - str: element.text || (mentionAll ? '@全体成员 ' : `@${element.targetUin} `), + str, pbReserve: extra, } as any, }; @@ -260,7 +284,7 @@ export async function buildSendElems(elements: MessageElement[], ctx?: SendConte break; case 'at': - result.push(makeMentionElem(elem)); + result.push(makeMentionElem(elem, ctx)); break; case 'reply': diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index 89339ef1..4e085b82 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -105,12 +105,13 @@ async function segmentToElement(type: string, data: Record, opt uid = (await options.resolveMentionUid(uin))?.trim() ?? ''; } - return { - type: 'at', - targetUin: uin, - uid: uid || undefined, - text: name ? `@${name} ` : `@${uin} `, - }; + // Leave `text` undefined when the caller didn't supply a display + // name. The element-builder then resolves it from the group roster + // (so QQ renders `@昵称` instead of `@QQ号`). + const element: MessageElement = { type: 'at', targetUin: uin }; + if (uid) element.uid = uid; + if (name) element.text = `@${name} `; + return element; } case 'reply': { const id = parseInt(String(data.id ?? '0'), 10); From 655af833dc102c57df27bf64b11327e7a3222d5c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= Date: Sat, 16 May 2026 14:22:49 +0800 Subject: [PATCH 02/51] fix(send): keep c2c video compatQMsgSceneType at 2 (#38) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Commit 29f28d6 changed c2c video `compatQmsgSceneType` from 2 to 1 as a "symmetric asymmetry" cleanup, matching the image/ptt convention where the field tracks the upload's sceneType (c2c=1, group=2). For video this is wrong. Image and ptt have *different* legacy compat elements per scene (notOnlineImage vs customFace; ptt c2c vs group), so the server needs to know which scene shape to emit. The legacy `videoFile` element (packet element type 19) has no scene split — fromChatType / toChatType live inside the element itself — so the QQ NT server emits a single group-shaped compat payload regardless. NapCat hardcodes `compatQMsgSceneType: 2` for *both* UploadGroupVideo and UploadPrivateVideo for exactly this reason. Setting it to 1 on c2c made the server emit a c2c-scene shaped compat blob that older QQ clients failed to resolve, showing the message as "视频已过期" on those receivers. Newer clients only read the commonElem(48, 11) and displayed fine — which is why only "some devices" saw the breakage. Keep `commonElem.businessType = isGroup ? 21 : 11` untouched — that piece of 29f28d6 is still correct and is what fixed PbSendMsg result=79. --- packages/core/src/bridge/highway/video-upload.ts | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index b8990ce3..5ed36be3 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -487,11 +487,17 @@ export async function uploadVideoMsgInfo( subFileType: 100, }, ], - // Scene tag the NTV2 upload registers under. image-upload and - // ptt-upload both differentiate (group=2, c2c=1); video was - // hardcoded to the group value, which contributed to the c2c - // send-back rejection (PbSendMsg result=79). - compatQmsgSceneType: isGroup ? 2 : 1, + // Hardcoded 2 even on c2c (matches NapCat). Image/PTT use + // `isGroup ? 2 : 1` because their legacy compat elements differ + // per scene (notOnlineImage vs customFace; ptt c2c vs group), + // but the legacy `videoFile` element has no scene split — its + // fromChatType/toChatType live inside the element itself — so + // the server generates a single group-shaped compat payload + // regardless. Setting 1 here makes the server emit a c2c-scene + // shaped compat blob that old QQ clients fail to resolve, + // showing the message as "视频已过期" on those receivers while + // new clients (which only read the commonElem) display fine. + compatQmsgSceneType: 2, extBizInfo: { pic: { bizType: 0, textSummary: 'Nya~' }, video: { bytesPbReserve: new Uint8Array([0x80, 0x01, 0x00]) }, From 2c80e1a267bb27ac43e771daaa271119f816d3ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:06:37 +0800 Subject: [PATCH 03/51] refactor(onebot): make loadOneBotConfig read-only by default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit GET on a load helper used to mint a fresh access_token and write it to disk whenever the per-UIN file was missing or in legacy format. Reading should not have side effects, and the WebUI's read-only GET handler in particular was racing on concurrent requests and surprising operators with materialized config files. Introduce a `{ persistDefaults?: boolean }` option (default false). The two boot-time call sites in `OneBotManager` (onSessionStarted, reloadConfig) opt in explicitly; WebUI's GET path will rely on the new default once that side of the patch lands. Also stop reviving default 0.0.0.0 listeners when the operator has explicitly emptied every adapter — only seed defaults on a true fresh install (no per-uin and no global config on disk). Drop the unused deepClone / deepMerge helpers; tryLoadJson now logs a warning instead of silently swallowing JSON parse errors. --- packages/core/src/onebot/config.ts | 49 +++++++++++++++-------------- packages/core/src/onebot/manager.ts | 4 +-- packages/core/tests/config.test.ts | 32 +++++++++++++++++-- 3 files changed, 58 insertions(+), 27 deletions(-) diff --git a/packages/core/src/onebot/config.ts b/packages/core/src/onebot/config.ts index c4cb902e..5e1605df 100644 --- a/packages/core/src/onebot/config.ts +++ b/packages/core/src/onebot/config.ts @@ -1,6 +1,7 @@ import fs from 'fs'; import path from 'path'; import { randomBytes } from 'crypto'; +import { createLogger } from '../utils/logger'; import type { HttpClientNetwork, HttpServerNetwork, @@ -13,6 +14,8 @@ import type { WsServerNetwork, } from './types'; +const log = createLogger('OneBot.Config'); + const CONFIG_DIR = 'config'; const DEFAULT_CONFIG_PATH = path.join(CONFIG_DIR, 'onebot.json'); const DEFAULT_ACCESS_TOKEN_BYTES = 32; @@ -50,7 +53,18 @@ function generateAccessToken(): string { return randomBytes(DEFAULT_ACCESS_TOKEN_BYTES).toString('base64url'); } -export function loadOneBotConfig(uin: string): OneBotConfig { +export interface LoadOneBotConfigOptions { + /** + * Persist the normalized config to disk when the file is missing or was + * in legacy format. Default `false` so accidental call sites (read-only + * GETs in particular) don't generate fresh access tokens, race on + * concurrent writes, or surprise the operator with materialized files. + * Pass `true` from boot / explicit POST handlers. + */ + persistDefaults?: boolean; +} + +export function loadOneBotConfig(uin: string, options: LoadOneBotConfigOptions = {}): OneBotConfig { ensureConfigDir(); const perUinPath = path.join(CONFIG_DIR, `onebot_${uin}.json`); @@ -65,12 +79,11 @@ export function loadOneBotConfig(uin: string): OneBotConfig { if (globalRaw) sources.push(globalRaw); if (perUinRaw) sources.push(perUinRaw); - const config = fromJson(sources); + const config = fromJson(sources, !perUinRaw && !globalRaw); - // Persist normalized form whenever the file is missing OR was in legacy - // format, so downstream code can rely on the unified shape on disk. - const shouldSave = !perUinRaw || legacy; - if (shouldSave) saveOneBotConfig(uin, config); + if (options.persistDefaults && (!perUinRaw || legacy)) { + saveOneBotConfig(uin, config); + } return config; } @@ -148,7 +161,7 @@ function wsClientToJson(n: WsClientNetwork): JsonObject { return out; } -function fromJson(sources: JsonObject[]): OneBotConfig { +function fromJson(sources: JsonObject[], freshInstall: boolean): OneBotConfig { // Legacy top-level scalars are pulled DOWN into each adapter on the first // load: the on-disk schema has no globals anymore, every adapter is // self-describing. We compute the legacy fallbacks here so that adapters @@ -175,8 +188,11 @@ function fromJson(sources: JsonObject[]): OneBotConfig { const wsServers = collectByName(sources, 'wsServers', (raw) => parseWsServer(raw, adapterDefaults)); const wsClients = collectByName(sources, 'wsClients', (raw) => parseWsClient(raw, adapterDefaults)); - // Seed defaults if all four arrays are empty (brand-new install). + // Seed defaults ONLY for a brand-new install (no source files at all). + // If the operator deliberately emptied every adapter, respect that and + // do NOT silently revive default 0.0.0.0 listeners. if ( + freshInstall && httpServers.length === 0 && httpClients.length === 0 && wsServers.length === 0 && @@ -354,7 +370,8 @@ function tryLoadJson(filePath: string): JsonObject | null { const raw = fs.readFileSync(filePath, 'utf8'); const parsed = JSON.parse(raw) as unknown; return isObject(parsed) ? parsed : null; - } catch { + } catch (err) { + log.warn('config file %s is corrupt and will be ignored: %s', filePath, err instanceof Error ? err.message : String(err)); return null; } } @@ -364,20 +381,6 @@ function saveJson(filePath: string, json: JsonObject): void { fs.writeFileSync(filePath, JSON.stringify(json, null, 2), 'utf8'); } -function deepClone(obj: JsonObject): JsonObject { - return JSON.parse(JSON.stringify(obj)) as JsonObject; -} - -function deepMerge(base: JsonObject, override: JsonObject): void { - for (const [key, value] of Object.entries(override)) { - if (isObject(base[key]) && isObject(value)) { - deepMerge(base[key] as JsonObject, value); - } else { - base[key] = value as never; - } - } -} - function isObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } diff --git a/packages/core/src/onebot/manager.ts b/packages/core/src/onebot/manager.ts index ec4dfca4..a2a4b8d0 100644 --- a/packages/core/src/onebot/manager.ts +++ b/packages/core/src/onebot/manager.ts @@ -35,7 +35,7 @@ export class OneBotManager { const instance = this.instances.get(uin); if (!instance) return false; - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); instance.reloadConfig(config); log.info('configuration reloaded: UIN=%s', uin); return true; @@ -51,7 +51,7 @@ export class OneBotManager { private onSessionStarted(uin: string, bridge: BridgeInterface): void { if (this.instances.has(uin)) return; - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); const instance = new OneBotInstance(uin, bridge, config); const activePid = bridge.activePid; diff --git a/packages/core/tests/config.test.ts b/packages/core/tests/config.test.ts index dc670636..6a667f50 100644 --- a/packages/core/tests/config.test.ts +++ b/packages/core/tests/config.test.ts @@ -45,7 +45,7 @@ describe('loadOneBotConfig', () => { it('creates and persists default config when none exists', () => { const uin = '10001'; - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); expect(config.networks.httpServers).toHaveLength(1); const onDisk = JSON.parse(fs.readFileSync(path.join(tempDir, 'config', `onebot_${uin}.json`), 'utf8')); @@ -74,7 +74,7 @@ describe('loadOneBotConfig', () => { }; fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify(legacy), 'utf8'); - const config = loadOneBotConfig(uin); + const config = loadOneBotConfig(uin, { persistDefaults: true }); expect(config.networks.httpServers).toHaveLength(1); expect(config.networks.httpServers[0].port).toBe(3100); expect(config.networks.httpServers[0].accessToken).toBe('tok'); @@ -128,6 +128,34 @@ describe('loadOneBotConfig', () => { expect(reloaded.networks.httpClients[0].reportSelfMessage).toBe(true); }); + it('does not write to disk by default (read-only contract)', () => { + const uin = '10006'; + const cfgPath = path.join(tempDir, 'config', `onebot_${uin}.json`); + + // Default call must not materialize the file or mint a fresh access token. + const config = loadOneBotConfig(uin); + expect(config.networks.httpServers).toHaveLength(1); + expect(fs.existsSync(cfgPath)).toBe(false); + + // Explicit opt-in still writes. + loadOneBotConfig(uin, { persistDefaults: true }); + expect(fs.existsSync(cfgPath)).toBe(true); + }); + + it('respects an operator-emptied adapter list instead of seeding defaults back', () => { + const uin = '10007'; + const dir = path.join(tempDir, 'config'); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, `onebot_${uin}.json`), JSON.stringify({ + networks: { httpServers: [], httpClients: [], wsServers: [], wsClients: [] }, + musicSignUrl: '', + }), 'utf8'); + + const config = loadOneBotConfig(uin, { persistDefaults: true }); + expect(config.networks.httpServers).toEqual([]); + expect(config.networks.wsServers).toEqual([]); + }); + it('migrates legacy lowercase WsRole values into canonical uppercase form', () => { const uin = '10005'; const dir = path.join(tempDir, 'config'); From 917f08ce4dfe6a723b096f6859cdf885097f727d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:07:02 +0800 Subject: [PATCH 04/51] fix(webui): tighten auth handling and remove read-side write effects MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Stack of WebUI fixes prompted by an internal security/correctness pass: * getClientIp now resolves the real socket peer via @hono/node-server's getConnInfo helper instead of trusting `X-Forwarded-For`. The previous behaviour let any client rotate that header to bypass the 5-attempts/ 15-minute login lockout. * `?token=` is restricted to /api/logs/stream (the only endpoint that can't use the Authorization header, because EventSource lacks custom headers). Other routes used to leak tokens via access logs / Referer / browser history. * change-password now invalidates every session (including the current one) and signals requireRelogin. Keeping the current token alive made the rotation pointless if the old credentials were already in an attacker's hands. * GET /api/config/:uin no longer writes defaults to disk and no longer doubles up the payload (`{config}` only, dropping the {…config, config} legacy shape). Frontend's `data?.config ?? data` fallback still works. * webui.json is moved to .bak. instead of being silently overwritten when it fails to parse — losing the prior hash silently was rotating operator credentials with no warning. * Process load/unload/refresh routes are deduped into a single helper; internal error messages are logged but no longer surfaced verbatim to the client. * SSE log stream tolerates a closed controller (try/catch around enqueue + central teardown) and runs an unref'd janitor to GC expired session tokens + login attempt counters every minute. --- packages/core/src/webui/auth.ts | 23 +++- packages/core/src/webui/server.ts | 179 ++++++++++++++++-------------- 2 files changed, 118 insertions(+), 84 deletions(-) diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 725d9981..b5688f50 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -1,6 +1,9 @@ import fs from 'fs'; import path from 'path'; import { randomBytes, scryptSync, timingSafeEqual } from 'crypto'; +import { createLogger } from '../utils/logger'; + +const log = createLogger('WebUI.Auth'); const CONFIG_DIR = 'config'; const WEBUI_CONFIG_PATH = path.join(CONFIG_DIR, 'webui.json'); @@ -84,6 +87,16 @@ function generateInitialState(initialPassword: string): WebuiAuthState { }; } +function backupCorruptConfig(): void { + try { + const dest = `${WEBUI_CONFIG_PATH}.bak.${Date.now()}`; + fs.renameSync(WEBUI_CONFIG_PATH, dest); + log.warn('previous webui.json moved to %s', dest); + } catch (err) { + log.warn('failed to back up corrupt webui.json: %s', err instanceof Error ? err.message : String(err)); + } +} + function atomicWrite(state: WebuiAuthState): void { ensureConfigDir(); const tmp = WEBUI_CONFIG_PATH + '.tmp'; @@ -130,8 +143,14 @@ export class WebuiAuth { if (isValidState(parsed)) { return new WebuiAuth(parsed, null, false); } - } catch { - /* fallthrough — regenerate */ + log.error('webui.json schema invalid; backing up and regenerating credentials'); + backupCorruptConfig(); + } catch (err) { + log.error( + 'webui.json is corrupt and will be regenerated; the previous file is backed up: %s', + err instanceof Error ? err.message : String(err), + ); + backupCorruptConfig(); } } const initialPassword = randomBytes(8).toString('hex'); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 4bec10db..bf792788 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1,12 +1,13 @@ import { serve } from '@hono/node-server'; +import { getConnInfo } from '@hono/node-server/conninfo'; import { serveStatic } from '@hono/node-server/serve-static'; -import { Hono } from 'hono'; +import { Hono, type Context } from 'hono'; import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger'; import { randomBytes } from 'crypto'; import type { OneBotManager } from '../onebot/manager'; import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config'; import type { OneBotConfig } from '../onebot/types'; -import type { HookManager } from '../hook/hook-manager'; +import type { HookManager, HookProcessInfo } from '../hook/hook-manager'; import path from 'path'; import { existsSync, readFileSync } from 'fs'; import { fileURLToPath } from 'url'; @@ -40,6 +41,14 @@ const MUST_CHANGE_ALLOWLIST = new Set([ '/api/logout', ]); +// Endpoints that may authenticate via `?token=` query parameter. Only the +// SSE log stream is here because EventSource cannot set custom headers; all +// other endpoints MUST use the Authorization header so tokens never leak +// into access logs / Referer / browser history. +const TOKEN_QUERY_ALLOWLIST = new Set([ + '/api/logs/stream', +]); + // uin = QQ number; 5–12 digits. Used to construct config file paths, // so we MUST refuse anything else (path traversal, NUL bytes, etc.). const UIN_REGEX = /^\d{5,12}$/; @@ -51,10 +60,24 @@ function purgeExpiredTokens() { for (const [token, info] of sessionTokens) { if (now > info.expiresAt) sessionTokens.delete(token); } + for (const [ip, attempt] of loginAttempts) { + if (now > attempt.resetAt) loginAttempts.delete(ip); + } } -function getClientIp(req: Request): string { - return req.headers.get('x-forwarded-for')?.split(',')[0].trim() ?? '127.0.0.1'; +/** + * Resolve the client IP from the underlying TCP socket via the official + * @hono/node-server conninfo helper. We deliberately do NOT trust + * `X-Forwarded-For` — the WebUI listens on a local port with no required + * reverse proxy, so accepting that header would let any client rotate it + * to bypass the per-IP login lockout. + */ +function getClientIp(c: Context): string { + try { + return getConnInfo(c).remote.address ?? '127.0.0.1'; + } catch { + return '127.0.0.1'; + } } async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> { @@ -96,11 +119,10 @@ export async function initWebUI( const authHeader = c.req.header('Authorization'); const bearerToken = authHeader?.startsWith('Bearer ') ? authHeader.slice(7) : ''; - const queryToken = c.req.query('token') ?? ''; + const queryToken = TOKEN_QUERY_ALLOWLIST.has(reqPath) ? (c.req.query('token') ?? '') : ''; const token = bearerToken || queryToken; if (!token) return c.json({ status: 'failed', message: 'Unauthorized' }, 401); - purgeExpiredTokens(); const info = sessionTokens.get(token); if (!info || Date.now() > info.expiresAt) { return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401); @@ -114,9 +136,14 @@ export async function initWebUI( await next(); }); + // Periodic janitor — keeps sessionTokens / loginAttempts from growing + // unbounded and replaces the per-request O(n) sweep we used to do. + const tokenJanitor = setInterval(purgeExpiredTokens, 60_000); + tokenJanitor.unref?.(); + // ─── Login ─────────────────────────────────────────────────────────────── app.post('/api/login', async (c) => { - const ip = getClientIp(c.req.raw); + const ip = getClientIp(c); const now = Date.now(); const attempt = loginAttempts.get(ip); if (attempt && attempt.count >= LOGIN_MAX_ATTEMPTS && now < attempt.resetAt) { @@ -140,7 +167,6 @@ export async function initWebUI( } loginAttempts.delete(ip); - purgeExpiredTokens(); const token = randomBytes(32).toString('hex'); const mustChange = auth.mustChangePassword(); sessionTokens.set(token, { expiresAt: now + TOKEN_TTL_MS, mustChangePassword: mustChange }); @@ -196,20 +222,15 @@ export async function initWebUI( try { auth.setPassword(newPassword); } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 400); + log.warn('change password failed: %s', err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '密码修改失败' }, 400); } - // Invalidate all other sessions; current keeps but loses must-change flag. - const currentToken = c.get('sessionToken' as never) as string | undefined; - for (const [tok, info] of sessionTokens) { - if (tok === currentToken) { - info.mustChangePassword = false; - sessionTokens.set(tok, info); - } else { - sessionTokens.delete(tok); - } - } - log.info('password updated'); - return c.json({ success: true }); + // Invalidate every session, including the current one. If the old + // password was compromised, the attacker may already hold the current + // token; rotating credentials must rotate sessions too. + sessionTokens.clear(); + log.info('password updated; all sessions invalidated'); + return c.json({ success: true, requireRelogin: true }); }); // ─── Avatar proxy (uin validated) ──────────────────────────────────────── @@ -319,23 +340,35 @@ export async function initWebUI( const stream = new ReadableStream({ start(controller) { const encoder = new TextEncoder(); + let closed = false; + let unsubscribe: (() => void) | undefined; + let heartbeat: NodeJS.Timeout | undefined; + const teardown = () => { + if (closed) return; + closed = true; + if (heartbeat) clearInterval(heartbeat); + unsubscribe?.(); + try { controller.close(); } catch { /* ignore */ } + }; + const safeEnqueue = (chunk: Uint8Array) => { + if (closed) return; + try { + controller.enqueue(chunk); + } catch { + // The peer dropped between abort and the next enqueue — + // treat as end-of-stream so we don't leak listeners. + teardown(); + } + }; const send = (event: unknown) => { - controller.enqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); + safeEnqueue(encoder.encode(`data: ${JSON.stringify(event)}\n\n`)); }; send({ type: 'ready' }); - const unsubscribe = subscribeLogs((entry) => send(entry)); - const heartbeat = setInterval(() => { - controller.enqueue(encoder.encode(': heartbeat\n\n')); + unsubscribe = subscribeLogs((entry) => send(entry)); + heartbeat = setInterval(() => { + safeEnqueue(encoder.encode(': heartbeat\n\n')); }, 15000); - c.req.raw.signal.addEventListener('abort', () => { - clearInterval(heartbeat); - unsubscribe(); - try { - controller.close(); - } catch { - /* ignore */ - } - }); + c.req.raw.signal.addEventListener('abort', teardown); }, }); return new Response(stream, { @@ -356,62 +389,43 @@ export async function initWebUI( } }); - app.post('/api/processes/:pid/load', async (c) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await hookManager.loadProcess(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); - } - }); - - app.post('/api/processes/:pid/unload', async (c) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await hookManager.unloadProcess(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); - } - }); - - app.post('/api/processes/:pid/refresh', async (c) => { - if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); - const pid = Number(c.req.param('pid')); - if (!Number.isInteger(pid) || pid <= 0 || pid > 4_194_304) { - return c.json({ success: false, message: 'invalid pid' }, 400); - } - try { - const processInfo = await hookManager.refreshProcess(pid); - return c.json({ success: processInfo.status !== 'error', process: processInfo }); - } catch (err) { - return c.json({ success: false, message: err instanceof Error ? err.message : String(err) }, 500); - } - }); + // Per-process action handler. The three routes below differ only in + // which HookManager method they call. + const MAX_PID = 4_194_304; + function processAction(label: string, action: (pid: number) => Promise) { + return async (c: Context) => { + if (!hookManager) return c.json({ success: false, message: 'hook manager is not available' }, 503); + const pid = Number(c.req.param('pid')); + if (!Number.isInteger(pid) || pid <= 0 || pid > MAX_PID) { + return c.json({ success: false, message: 'invalid pid' }, 400); + } + try { + const processInfo = await action(pid); + return c.json({ success: processInfo.status !== 'error', process: processInfo }); + } catch (err) { + log.warn('%s pid=%d failed: %s', label, pid, err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '操作失败,请检查服务器日志' }, 500); + } + }; + } + app.post('/api/processes/:pid/load', processAction('load', (pid) => hookManager!.loadProcess(pid))); + app.post('/api/processes/:pid/unload', processAction('unload', (pid) => hookManager!.unloadProcess(pid))); + app.post('/api/processes/:pid/refresh', processAction('refresh', (pid) => hookManager!.refreshProcess(pid))); app.get('/api/config/:uin', (c) => { const uin = c.req.param('uin'); if (!UIN_REGEX.test(uin)) return c.json({ message: 'invalid uin' }, 400); + // Read-only: never write defaults to disk on a GET. The persisted + // file is created when manager.onSessionStarted boots an instance + // or when the operator POSTs from this very endpoint. const config = loadOneBotConfig(uin); - return c.json({ - ...config, - config, - }); + return c.json({ config }); }); app.post('/api/config/:uin', async (c) => { + const uin = c.req.param('uin'); + if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); try { - const uin = c.req.param('uin'); - if (!UIN_REGEX.test(uin)) return c.json({ success: false, message: 'invalid uin' }, 400); const body = (await c.req.json()) as OneBotConfig; saveOneBotConfig(uin, body); const reloaded = oneBotManager.reloadConfig(uin); @@ -422,7 +436,8 @@ export async function initWebUI( message: reloaded ? '配置保存成功,已热重载当前会话。' : '配置保存成功,当前会话未在线,将在下次连接时生效。', }); } catch (err) { - return c.json({ success: false, message: String(err) }, 400); + log.warn('save config for uin=%s failed: %s', uin, err instanceof Error ? err.message : String(err)); + return c.json({ success: false, message: '配置保存失败,请检查服务器日志' }, 400); } }); From b2c53b56f79e1e6c41353d3bdfbab8da88bdc6a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:07:32 +0800 Subject: [PATCH 05/51] fix(onebot): correctness pass on actions and message parser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Action-layer fixes, all cross-checked against NapCat's reference implementation in packages/napcat-onebot: * download_file (extended.ts:539) now sanitizes `name` via path.basename + resolve/relative containment check. Previously an authenticated client could write `../../config/onebot_.json` and replace access tokens / webhook URLs. * mark_group_msg_as_read / mark_private_msg_as_read / mark_msg_as_read fall back to meta.targetId when the optional group_id/user_id arg is missing. The old code passed 0 to the Bridge. NapCat resolves the peer from message_id alone in MarkMsgAsRead.ts; we now match that. * set_friend_remark / set_group_remark refuse a missing `remark` field. The previous `asString(...) ?? ''` silently CLEARED the remark for any client that forgot the parameter. NapCat's typebox schema makes `remark` required; we now do the same. * upload_forward_msg threads `group_id` down to uploadForwardNodes so the resulting resId lives in the correct namespace (type:3 + groupUin vs type:1 + selfUid — see bridge/actions/forward.ts). NapCat passes `peer.chatType === GROUP ? +peerUid : 0` for the same reason. ApiActionContext.sendForwardMsg + uploadForwardMessage signatures pick up an optional groupId. * Private-message reply meta now resolves senderUin from the cached event (real sender), with a self-id fallback when only meta exists (bot's own outbound message — `cacheMessageMeta` does not populate the event row). The old code used meta.targetId, which is the conversation peer — wrong when the bot replies to its own message. * message-parser: - intOr(value, fallback) helper replaces parseInt(String(...)) at face/at/reply/image/xml/poke/node sites so non-numeric input no longer produces NaN downstream. Invalid face ids skip the element rather than emit NaN. - cqUnescape decodes `,` (escaped comma) — the OneBot 11 spec requires it and clients in the wild emit it. * Drop the dead Array.isArray(rawAuth) branch in onebot/network/utils (Node's headers.authorization is `string | undefined`, never an array) and the unused WebHonorType import in api-handler. --- packages/core/src/onebot/actions/extended.ts | 81 +++++++++++++------ packages/core/src/onebot/api-handler.ts | 5 +- packages/core/src/onebot/instance-context.ts | 2 +- packages/core/src/onebot/message-parser.ts | 34 +++++--- .../src/onebot/modules/message-actions.ts | 29 ++++++- packages/core/src/onebot/network/utils.ts | 3 +- 6 files changed, 113 insertions(+), 41 deletions(-) diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 82fd4f99..5c3df155 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -2,6 +2,19 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asMessage, asNumber, asString, asBoolean } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { RETCODE, failedResponse, okResponse } from '../types'; +import { createLogger } from '../../utils/logger'; + +const log = createLogger('OneBot.Action'); + +/** + * Standard error wrapper. Logs the full error (so operators can debug) but + * surfaces only `Error.message` (or the supplied fallback) to the caller. + */ +function actionFailed(action: string, err: unknown, fallback = 'action failed') { + const detail = err instanceof Error ? err.message : String(err); + log.warn('%s failed: %s', action, detail); + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : fallback); +} /** * Pull NapCat-compatible forward preview overrides off a send_*_forward_msg @@ -157,8 +170,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); } const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (!meta || !meta.isGroup) { return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a group message'); } @@ -167,8 +178,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'group_id does not match message session'); } - - await ctx.bridge.markGroupMsgAsRead(groupId, meta.sequence); + await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence); return okResponse(); }); @@ -180,8 +190,6 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'message_id is required'); } const meta = ctx.getMessageMeta(messageId); - if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (!meta || meta.isGroup) { return failedResponse(RETCODE.ACTION_FAILED, 'message not found or not a private message'); } @@ -190,8 +198,7 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return failedResponse(RETCODE.BAD_REQUEST, 'user_id does not match message session'); } - - await ctx.bridge.markPrivateMsgAsRead(userId, meta.sequence); + await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence); return okResponse(); }); @@ -205,15 +212,14 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const meta = ctx.getMessageMeta(messageId); if (!meta) return failedResponse(RETCODE.ACTION_FAILED, 'message not found'); - if (targetId && targetId !== meta.targetId) { return failedResponse(RETCODE.BAD_REQUEST, 'target_id does not match message session'); } if (meta.isGroup) { - await ctx.bridge.markGroupMsgAsRead(targetId, meta.sequence); + await ctx.bridge.markGroupMsgAsRead(meta.targetId, meta.sequence); } else { - await ctx.bridge.markPrivateMsgAsRead(targetId, meta.sequence); + await ctx.bridge.markPrivateMsgAsRead(meta.targetId, meta.sequence); } return okResponse(); }); @@ -310,7 +316,11 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const groupId = asNumber(params.group_id); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendForwardMsg(messages); + // Group and private forwards live in different resId namespaces + // (see bridge/actions/forward.ts: type=3+groupUin vs type=1+selfUid). + // Passing groupId through is what makes the resulting resId usable + // when the caller later sends it into the same group. + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); const data: Record = { res_id: result.forwardId, forward_id: result.forwardId, @@ -320,10 +330,13 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return okResponse(data as any); }); + // Kept for backward compat with clients that follow the historical + // gocqhttp/NapCat docs misspelling; same semantics as upload_forward_msg. h.registerAction('upload_foward_msg', async (params) => { const messages = asMessage(params.messages ?? params.message); + const groupId = asNumber(params.group_id); if (messages === undefined) return failedResponse(RETCODE.BAD_REQUEST, 'message/messages is required'); - const result = await ctx.sendForwardMsg(messages); + const result = await ctx.sendForwardMsg(messages, groupId > 0 ? groupId : undefined); return okResponse({ res_id: result.forwardId, forward_id: result.forwardId, message_id: 0 }); }); @@ -482,17 +495,23 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { h.registerAction('set_friend_remark', async (params) => { const userId = asNumber(params.user_id); - const remark = asString(params.remark) ?? ''; if (!userId) return failedResponse(RETCODE.BAD_REQUEST, 'user_id is required'); - await ctx.bridge.setFriendRemark(userId, remark); + // remark must be explicitly provided. Falling back to '' on a missing + // field would silently CLEAR the operator's existing remark. + if (params.remark === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); + } + await ctx.bridge.setFriendRemark(userId, asString(params.remark)); return okResponse(); }); h.registerAction('set_group_remark', async (params) => { const groupId = asNumber(params.group_id); - const remark = asString(params.remark) ?? ''; if (!groupId) return failedResponse(RETCODE.BAD_REQUEST, 'group_id is required'); - await ctx.bridge.setGroupRemark(groupId, remark); + if (params.remark === undefined) { + return failedResponse(RETCODE.BAD_REQUEST, 'remark is required (pass an empty string to clear)'); + } + await ctx.bridge.setGroupRemark(groupId, asString(params.remark)); return okResponse(); }); @@ -545,14 +564,29 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { const fs = await import('fs'); const pathMod = await import('path'); const cryptoMod = await import('crypto'); - const tempDir = pathMod.join('data', 'downloads'); + const tempDir = pathMod.resolve('data', 'downloads'); if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); + // Sanitize file name: strip any path components, reject anything that + // resolves outside `tempDir`. Without this guard, `name = "../../config/onebot_x.json"` + // would let an authenticated OneBot client overwrite arbitrary files + // (config / dist / node_modules) under the working directory. + const resolveSafePath = (preferredName: string, fallbackBuf: Buffer): string | null => { + const raw = preferredName || cryptoMod.createHash('md5').update(fallbackBuf).digest('hex'); + const safeName = pathMod.basename(raw); + if (!safeName || safeName === '.' || safeName === '..' || /[\\/]/.test(safeName)) return null; + const resolved = pathMod.resolve(tempDir, safeName); + const rel = pathMod.relative(tempDir, resolved); + if (rel.startsWith('..') || pathMod.isAbsolute(rel)) return null; + return resolved; + }; + let filePath: string; if (base64) { const buf = Buffer.from(base64, 'base64'); - const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex'); - filePath = pathMod.join(tempDir, fileName); + const safe = resolveSafePath(name, buf); + if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); + filePath = safe; fs.writeFileSync(filePath, buf); } else { const response = await fetch(url!, { @@ -560,11 +594,12 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { }); if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`); const buf = Buffer.from(await response.arrayBuffer()); - const fileName = name || cryptoMod.createHash('md5').update(buf).digest('hex'); - filePath = pathMod.join(tempDir, fileName); + const safe = resolveSafePath(name, buf); + if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); + filePath = safe; fs.writeFileSync(filePath, buf); } - return okResponse({ file: pathMod.resolve(filePath) }); + return okResponse({ file: filePath }); }); h.registerAction('set_qq_profile', async (params) => { diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index 57f1dabf..2be74ec7 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -12,9 +12,6 @@ import { register as registerGroupFile } from './actions/group-file'; import { register as registerRequest } from './actions/request'; import { register as registerExtended } from './actions/extended'; -import { WebHonorType } from '@/bridge/web/group-honor'; -// import {ClientKeyInfo} from "@/bridge/bridge"; - export interface MessageSendResult { messageId: number; meta?: MessageMeta; @@ -91,7 +88,7 @@ export interface ApiActionContext { getDownloadRKeys: () => Promise; sendGroupForwardMsg: (groupId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>; sendPrivateForwardMsg: (userId: number, messages: JsonValue, meta?: ForwardPreviewMeta) => Promise<{ messageId: number; forwardId: string }>; - sendForwardMsg: (messages: JsonValue) => Promise<{ forwardId: string }>; + sendForwardMsg: (messages: JsonValue, groupId?: number) => Promise<{ forwardId: string }>; getForwardMsg: (resId: string) => Promise; forwardSingleMsg: (messageId: number, target: { groupId?: number; userId?: number }) => Promise<{ messageId: number }>; setMsgEmojiLike: (messageId: number, emojiId: string, set: boolean) => Promise; diff --git a/packages/core/src/onebot/instance-context.ts b/packages/core/src/onebot/instance-context.ts index e9eba0e5..6c295d18 100644 --- a/packages/core/src/onebot/instance-context.ts +++ b/packages/core/src/onebot/instance-context.ts @@ -158,7 +158,7 @@ export function buildApiContext(ref: OneBotInstanceContext): ApiActionContext { getDownloadRKeys: () => getDownloadRKeys(bridge), sendGroupForwardMsg: (groupId, messages, meta) => sendGroupForwardMessage(ref, groupId, messages, meta), sendPrivateForwardMsg: (userId, messages, meta) => sendPrivateForwardMessage(ref, userId, messages, meta), - sendForwardMsg: (messages) => uploadForwardMessage(ref, messages), + sendForwardMsg: (messages, groupId) => uploadForwardMessage(ref, messages, groupId), getForwardMsg: (resId) => getForwardMessage(ref, resId), forwardSingleMsg: (messageId, target) => forwardSingleMessage(ref, messageId, target), handleDeleteFriend: (userId, block) => bridge.deleteFriend(userId, !!block), diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index 4e085b82..2d9f7950 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -16,6 +16,19 @@ export interface ParseMessageOptions { const CQ_REGEX = /\[CQ:([A-Za-z]+)(?:,([^\]]*))?\]/g; +/** + * Best-effort base-10 integer coercion. Falls back to `fallback` (default 0) + * when the input can't be parsed as a finite integer — `parseInt('abc')` + * is `NaN`, which silently turns into `0`/`null` further down the wire + * pipeline and produces undebuggable protocol-level failures. + */ +function intOr(value: unknown, fallback = 0): number { + if (value === undefined || value === null) return fallback; + if (typeof value === 'number') return Number.isFinite(value) ? Math.trunc(value) : fallback; + const n = parseInt(String(value), 10); + return Number.isFinite(n) ? n : fallback; +} + function parseCQParams(raw: string): Record { const params: Record = {}; if (!raw) return params; @@ -33,9 +46,12 @@ function parseCQParams(raw: string): Record { } function cqUnescape(text: string): string { + // Order matters: `&` MUST be last so that, e.g., `&#91;` keeps + // the literal `[` instead of decoding twice into `[`. return text .replace(/[/g, '[') .replace(/]/g, ']') + .replace(/,/g, ',') .replace(/&/g, '&'); } @@ -88,7 +104,8 @@ async function segmentToElement(type: string, data: Record, opt return text ? { type: 'text', text } : null; } case 'face': { - const id = parseInt(String(data.id ?? '0'), 10); + const id = intOr(data.id, -1); + if (id < 0) return null; return { type: 'face', faceId: id }; } case 'at': { @@ -96,7 +113,7 @@ async function segmentToElement(type: string, data: Record, opt if (qq === 'all') { return { type: 'at', targetUin: 0, uid: 'all', text: '@全体成员 ' }; } - const uin = parseInt(qq, 10); + const uin = intOr(qq, 0); if (uin <= 0) return null; const name = String(data.name ?? data.nickname ?? data.card ?? '').trim(); @@ -114,8 +131,8 @@ async function segmentToElement(type: string, data: Record, opt return element; } case 'reply': { - const id = parseInt(String(data.id ?? '0'), 10); - if (!Number.isInteger(id) || id === 0) return null; + const id = intOr(data.id, 0); + if (id === 0) return null; if (options?.resolveReplySequence) { const resolved = options.resolveReplySequence(id); @@ -148,7 +165,7 @@ async function segmentToElement(type: string, data: Record, opt type: 'image', url: String(data.file ?? data.url ?? data.path ?? data.media ?? ''), flash: data.type === 'flash', - subType: parseInt(String(data.subType ?? '0'), 10), + subType: intOr(data.subType, 0), summary: data.summary ? String(data.summary) : undefined, }; } @@ -179,13 +196,13 @@ async function segmentToElement(type: string, data: Record, opt return { type: 'xml', text: String(data.data ?? ''), - subType: parseInt(String(data.id ?? '0'), 10), + subType: intOr(data.id, 0), }; } case 'poke': { return { type: 'poke', - faceId: parseInt(String(data.type ?? data.id ?? '0'), 10), + faceId: intOr(data.type ?? data.id, 0), }; } case 'forward': { @@ -197,11 +214,10 @@ async function segmentToElement(type: string, data: Record, opt case 'node': { // Fake forward node segment — store the raw data for later processing // The content field may be a segment array, a single segment, or a CQ string - const uin = String(data.user_id ?? data.uin ?? '0'); const name = String(data.nickname ?? data.name ?? ''); return { type: 'node', - targetUin: parseInt(uin, 10) || 0, + targetUin: intOr(data.user_id ?? data.uin, 0), text: name, // Raw content is stored as JSON string in resId for later processing resId: JSON.stringify(data.content ?? ''), diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index a2b2a0a5..5a847f9c 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -99,10 +99,32 @@ export async function sendPrivateMessage( return ref.messageStore.resolveReplySequence(false, userId, replyMessageId); }, resolveReplyMeta: (replyMessageId) => { + // Prefer the cached event (it carries the REAL sender). When only + // meta exists — typically because the message we're replying to was + // sent by the bot itself and never round-tripped through dispatch + // (reportSelfMessage off / no message_sent event) — fall back to + // selfId. The previous code used `meta.targetId` here, which is the + // conversation PEER and shows the wrong "回复 @某人" in QQ for any + // self-reply. + const event = ref.messageStore.findEvent(replyMessageId); + if (event) { + const senderUin = typeof event.user_id === 'number' + ? event.user_id + : parseInt(String(event.user_id || '0'), 10); + const time = typeof event.time === 'number' + ? event.time + : parseInt(String(event.time || '0'), 10); + const meta = ref.messageStore.findMeta(replyMessageId); + return { + senderUin, + time, + random: meta?.random ?? 0, + }; + } const meta = ref.messageStore.findMeta(replyMessageId); if (meta) { return { - senderUin: meta.targetId, + senderUin: ref.selfId, time: meta.timestamp, random: meta.random, }; @@ -240,9 +262,12 @@ export async function sendPrivateForwardMessage( export async function uploadForwardMessage( ref: OneBotInstanceContext, messages: JsonValue, + groupId?: number, ): Promise<{ forwardId: string }> { const nodes = await parseForwardNodes(ref, messages); - const forwardId = await ref.bridge.uploadForwardNodes(nodes); + // groupId controls the resId namespace (group vs private). Without it, + // a resId minted here is unusable when later sent into a group. + const forwardId = await ref.bridge.uploadForwardNodes(nodes, groupId); return { forwardId }; } diff --git a/packages/core/src/onebot/network/utils.ts b/packages/core/src/onebot/network/utils.ts index 2e445bb3..5e229ec3 100644 --- a/packages/core/src/onebot/network/utils.ts +++ b/packages/core/src/onebot/network/utils.ts @@ -6,8 +6,7 @@ import type { WebSocket } from '@snowluma/websocket'; /** Validate a request's bearer token / `?access_token=` query against the configured token. */ export function isAuthorized(request: IncomingMessage, token: string): boolean { if (!token) return true; - const rawAuth = request.headers.authorization; - const auth = Array.isArray(rawAuth) ? rawAuth[0] : rawAuth ?? ''; + const auth = request.headers.authorization ?? ''; if (auth === `Bearer ${token}`) return true; try { const url = new URL(request.url ?? '/', 'http://127.0.0.1'); From b3df633c877a1fda090a4eabfc6e93e829434ff2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:07:54 +0800 Subject: [PATCH 06/51] fix(bridge): correctness pass on highway, hook, and identity service * highway/utils detectImageFormat: JPEG SOF marker check now excludes 0xC4 (DHT), 0xC8 (JPG), and 0xCC (DAC). The old `(marker & 0xFC) === 0xC0` matched DHT et al. and then read Huffman table bytes as image dimensions, producing junk width/height for many real JPEGs. * loadBinarySource takes an optional maxBytes; defaults to 1 GiB to defend against an authenticated client triggering a multi-GB load into memory. Group/private file uploads pass FILE_UPLOAD_MAX_BYTES (4 GiB) because QQ's file protocol legitimately supports that size. HTTP fetches also pick up a 60s timeout and a Content-Length precheck. * highway-client.tcpConnect detaches its error/timeout listeners after a successful connect so subsequent upload IO errors don't reject an already-resolved promise. readHttpResponseBody uses local listener refs + a central detach(), eliminating MaxListenersExceededWarning during multi-chunk uploads. * hook/qq-hook-client.nextRequestId now wraps inside uint32 explicitly and skips id 0 / in-flight ids. The previous `nextRequestId++ >>> 0` loses precision past Number.MAX_SAFE_INTEGER (postfix increment evaluates before the shift) and could collide live request ids on very long-running processes. * identity-service.rememberUidUin removes stale partner entries before inserting a new (uid, uin) pair. The old code left orphan uidByUin / uinByUid entries after a uid/uin re-bind, so the two maps could disagree. --- .../core/src/bridge/actions/group-file.ts | 10 +++- .../core/src/bridge/highway/highway-client.ts | 56 +++++++++++++++---- packages/core/src/bridge/highway/utils.ts | 43 ++++++++++++-- packages/core/src/bridge/identity-service.ts | 7 +++ packages/core/src/hook/qq-hook-client.ts | 13 ++++- .../core/tests/actions/group-file.test.ts | 1 + 6 files changed, 111 insertions(+), 19 deletions(-) diff --git a/packages/core/src/bridge/actions/group-file.ts b/packages/core/src/bridge/actions/group-file.ts index 969b13ff..06f8c123 100644 --- a/packages/core/src/bridge/actions/group-file.ts +++ b/packages/core/src/bridge/actions/group-file.ts @@ -9,7 +9,7 @@ import type { Bridge } from '../bridge'; import { protoEncode } from '../../protobuf/decode'; import { runOidb } from '../bridge-oidb'; import { fetchHighwaySession, uploadHighwayHttp } from '../highway/highway-client'; -import { computeHashes, computeMd5, loadBinarySource } from '../highway/utils'; +import { computeHashes, computeMd5, FILE_UPLOAD_MAX_BYTES, loadBinarySource } from '../highway/utils'; import { OidbGroupFileCountViewReqSchema, OidbGroupFileCountViewRespSchema, @@ -288,7 +288,9 @@ export async function uploadGroupFile( folderId = '/', uploadFile = true, ): Promise { - const loaded = await loadBinarySource(source, 'file'); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); if (!loaded.bytes.length) throw new Error('group file is empty'); const fileName = normalizeUploadFileName(name, loaded.fileName); @@ -366,7 +368,9 @@ export async function uploadPrivateFile( name = '', uploadFile = true, ): Promise { - const loaded = await loadBinarySource(source, 'file'); + // Group/private files may legitimately be up to 4 GiB on QQ's wire, + // so override the default 1 GiB cap with the protocol ceiling. + const loaded = await loadBinarySource(source, 'file', FILE_UPLOAD_MAX_BYTES); if (!loaded.bytes.length) throw new Error('private file is empty'); const targetUid = await bridge.resolveUserUid(userId); diff --git a/packages/core/src/bridge/highway/highway-client.ts b/packages/core/src/bridge/highway/highway-client.ts index dcffbd74..99d3c385 100644 --- a/packages/core/src/bridge/highway/highway-client.ts +++ b/packages/core/src/bridge/highway/highway-client.ts @@ -129,10 +129,31 @@ export function buildHighwayExtend( function tcpConnect(host: string, port: number, timeoutMs = 10000): Promise { return new Promise((resolve, reject) => { - const socket = net.createConnection({ host, port }, () => resolve(socket)); + let settled = false; + const onTimeout = () => { + if (settled) return; + settled = true; + socket.destroy(); + reject(new Error('TCP connect timeout')); + }; + const onError = (err: Error) => { + if (settled) return; + settled = true; + reject(err); + }; + const socket = net.createConnection({ host, port }, () => { + if (settled) return; + settled = true; + // Drop the connect-only listeners so subsequent IO errors / idle + // timeouts don't try to reject this already-resolved promise. + socket.setTimeout(0); + socket.removeListener('timeout', onTimeout); + socket.removeListener('error', onError); + resolve(socket); + }); socket.setTimeout(timeoutMs); - socket.on('timeout', () => { socket.destroy(); reject(new Error('TCP connect timeout')); }); - socket.on('error', reject); + socket.once('timeout', onTimeout); + socket.once('error', onError); }); } @@ -148,8 +169,21 @@ function readHttpResponseBody(socket: net.Socket): Promise { let headerEnd = -1; let contentLength = 0; let totalNeeded = 0; + let settled = false; - const checkComplete = () => { + const detach = () => { + socket.off('data', onData); + socket.off('error', onError); + socket.off('close', onClose); + }; + const finish = (fn: () => void) => { + if (settled) return; + settled = true; + detach(); + fn(); + }; + const onData = (chunk: Buffer) => { + chunks.push(chunk); const buf = Buffer.concat(chunks); if (headerEnd < 0) { const idx = buf.indexOf('\r\n\r\n'); @@ -162,19 +196,19 @@ function readHttpResponseBody(socket: net.Socket): Promise { } } if (headerEnd >= 0 && buf.length >= totalNeeded) { - socket.removeAllListeners('data'); - socket.removeAllListeners('error'); - resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded))); + finish(() => resolve(new Uint8Array(buf.subarray(headerEnd, totalNeeded)))); } }; - - socket.on('data', (chunk) => { chunks.push(chunk); checkComplete(); }); - socket.on('error', reject); - socket.on('close', () => { + const onError = (err: Error) => finish(() => reject(err)); + const onClose = () => finish(() => { const buf = Buffer.concat(chunks); if (headerEnd >= 0) resolve(new Uint8Array(buf.subarray(headerEnd))); else reject(new Error('connection closed before response')); }); + + socket.on('data', onData); + socket.on('error', onError); + socket.on('close', onClose); }); } diff --git a/packages/core/src/bridge/highway/utils.ts b/packages/core/src/bridge/highway/utils.ts index a39ceabf..1ea3e950 100644 --- a/packages/core/src/bridge/highway/utils.ts +++ b/packages/core/src/bridge/highway/utils.ts @@ -11,6 +11,17 @@ export interface LoadedBinary { fileName: string; } +/** + * Default cap on a single binary load. Image/voice/video paths use this + * to defend against an authenticated OneBot client triggering a multi-GB + * read into memory. Group/private file uploads override this cap because + * QQ's file protocol legitimately supports up to 4 GiB. + */ +const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB +/** Hard ceiling QQ's file protocol supports — used by group/private files. */ +export const FILE_UPLOAD_MAX_BYTES = 4 * 1024 * 1024 * 1024; // 4 GiB +const FETCH_TIMEOUT_MS = 60_000; + export interface ImageHashes { md5: Uint8Array; sha1: Uint8Array; @@ -54,17 +65,32 @@ export function resolveLocalFilePath(source: string): string | null { return filePath; } -export async function loadBinarySource(source: string, resourceName: string): Promise { +export async function loadBinarySource( + source: string, + resourceName: string, + maxBytes: number = DEFAULT_MAX_BINARY_SIZE, +): Promise { if (!source) throw new Error(`${resourceName} source is empty`); if (/^base64:\/\//i.test(source)) { - return { bytes: Buffer.from(source.slice(9), 'base64'), fileName: '' }; + const bytes = Buffer.from(source.slice(9), 'base64'); + if (bytes.length > maxBytes) { + throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + } + return { bytes, fileName: '' }; } if (/^https?:\/\//i.test(source)) { - const resp = await fetch(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 bytes = new Uint8Array(await resp.arrayBuffer()); + if (bytes.length > maxBytes) { + throw new Error(`${resourceName} too large: ${bytes.length} > ${maxBytes}`); + } const fileName = guessFileNameFromUrl(source); return { bytes, fileName }; } @@ -72,6 +98,10 @@ export async function loadBinarySource(source: string, resourceName: string): Pr const filePath = resolveLocalFilePath(source); if (!filePath) throw new Error(`${resourceName} source is not a local file`); + const stat = fs.statSync(filePath); + if (stat.size > maxBytes) { + throw new Error(`${resourceName} too large: ${stat.size} > ${maxBytes}`); + } const bytes = fs.readFileSync(filePath); const fileName = path.basename(filePath); return { bytes, fileName }; @@ -183,7 +213,12 @@ export function detectImageFormat(bytes: Uint8Array): ImageFormat { if (offset + 4 > bytes.length) break; const segLen = readBE16(bytes, offset + 2); if (segLen < 2 || offset + 2 + segLen > bytes.length) break; - if ((marker & 0xFC) === 0xC0 && offset + 9 <= bytes.length) { + // Real SOF markers: 0xC0..0xCF EXCEPT 0xC4 (DHT), 0xC8 (JPG), 0xCC + // (DAC). The previous `(marker & 0xFC) === 0xC0` check accepted DHT + // and friends, then misread Huffman table bytes as image dimensions. + const isSof = marker >= 0xC0 && marker <= 0xCF + && marker !== 0xC4 && marker !== 0xC8 && marker !== 0xCC; + if (isSof && segLen >= 7 && offset + 9 <= bytes.length) { height = readBE16(bytes, offset + 5); width = readBE16(bytes, offset + 7); return { format: 1000, width, height }; diff --git a/packages/core/src/bridge/identity-service.ts b/packages/core/src/bridge/identity-service.ts index 3b3dfbe2..c6918284 100644 --- a/packages/core/src/bridge/identity-service.ts +++ b/packages/core/src/bridge/identity-service.ts @@ -440,6 +440,13 @@ export class IdentityService { const normalizedUid = normalizeUid(uid); const normalizedUin = normalizeUin(uin); if (!normalizedUid || normalizedUin === null) return; + // Drop any stale mapping for the old partner first; otherwise the two + // maps disagree (`findUinByUid(oldUid) -> uin` while + // `findUidByUin(uin) -> newUid`) after a uid/uin re-binding. + const oldUid = this.uidByUin.get(normalizedUin); + if (oldUid && oldUid !== normalizedUid) this.uinByUid.delete(oldUid); + const oldUin = this.uinByUid.get(normalizedUid); + if (oldUin !== undefined && oldUin !== normalizedUin) this.uidByUin.delete(oldUin); this.uinByUid.set(normalizedUid, normalizedUin); this.uidByUin.set(normalizedUin, normalizedUid); } diff --git a/packages/core/src/hook/qq-hook-client.ts b/packages/core/src/hook/qq-hook-client.ts index 9844a750..4b195f39 100644 --- a/packages/core/src/hook/qq-hook-client.ts +++ b/packages/core/src/hook/qq-hook-client.ts @@ -444,7 +444,18 @@ export class QqHookClient extends EventEmitter { }: QqHookSendOptions = {}): Promise { await this.connect(); - const requestId = this.nextRequestId++ >>> 0; + // Wrap inside uint32 explicitly. `nextRequestId++ >>> 0` would + // misbehave once the integer exceeds Number.MAX_SAFE_INTEGER (the + // postfix increment loses precision before the shift), letting two + // distinct requests collide on the same id. Skip 0 because zero is + // used as a sentinel by the wire protocol. + let requestId = this.nextRequestId; + while (this.pendingAcks.has(requestId) || this.pendingReplies.has(requestId)) { + requestId = (requestId + 1) >>> 0; + if (requestId === 0) requestId = 1; + } + this.nextRequestId = (requestId + 1) >>> 0; + if (this.nextRequestId === 0) this.nextRequestId = 1; const payload = encodeFrame({ op: PipeOp.sendRequest, requestId, diff --git a/packages/core/tests/actions/group-file.test.ts b/packages/core/tests/actions/group-file.test.ts index a6ce62cf..2f71bc76 100644 --- a/packages/core/tests/actions/group-file.test.ts +++ b/packages/core/tests/actions/group-file.test.ts @@ -16,6 +16,7 @@ vi.mock('../../src/bridge/highway/utils', () => ({ })), computeHashes: vi.fn(() => ({ md5: new Uint8Array(16), sha1: new Uint8Array(20) })), computeMd5: vi.fn(() => new Uint8Array(16)), + FILE_UPLOAD_MAX_BYTES: 4 * 1024 * 1024 * 1024, })); import * as oidb from '../../src/bridge/bridge-oidb'; From b40cee18cc41a109076ea83cca639dc26b7516e5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:26:49 +0800 Subject: [PATCH 07/51] fix(bridge): close two binary-size cap gaps flagged by review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up on the previous highway commit, addressing two real holes the Copilot review caught: * loadBinarySource HTTP path was buffering the entire response via `await resp.arrayBuffer()` BEFORE length-checking. A server that omits or understates `Content-Length` (chunked transfer, malicious upstream, proxy stripping headers) bypassed the cap entirely. Switch to a streaming reader: accumulate chunks, abort + reject as soon as the running total exceeds `maxBytes`. The Content-Length precheck still short-circuits the obvious case before we read a byte. * video-upload `stageVideoSource` has its own local-path fast-path that never went through `loadBinarySource`, so the 100 MB MAX_VIDEO_SIZE guard ran AFTER `fs.readFileSync` had already allocated the entire file. A 10 GiB local-file pointer would OOM the bot before the check fired. Add an `fs.statSync` precheck on the local branch, and pass `MAX_VIDEO_SIZE` explicitly when the source falls through to `loadBinarySource` so the HTTP / base64 cap matches the on-disk one. Update the DEFAULT_MAX_BINARY_SIZE comment to stop claiming video paths are bounded by it — they're bounded by the smaller MAX_VIDEO_SIZE, enforced inside video-upload. Adds five regression tests: - chunked streamed download (no Content-Length) over cap → throws - Content-Length over cap → throws before reading body - streamed download inside cap → returns full bytes - local file over cap (statSync precheck) → throws - base64 over cap → throws --- packages/core/src/bridge/highway/utils.ts | 50 +++++++++++-- .../core/src/bridge/highway/video-upload.ts | 10 ++- packages/core/tests/highway-utils.test.ts | 75 ++++++++++++++++++- 3 files changed, 125 insertions(+), 10 deletions(-) diff --git a/packages/core/src/bridge/highway/utils.ts b/packages/core/src/bridge/highway/utils.ts index 1ea3e950..963c7323 100644 --- a/packages/core/src/bridge/highway/utils.ts +++ b/packages/core/src/bridge/highway/utils.ts @@ -12,10 +12,13 @@ export interface LoadedBinary { } /** - * Default cap on a single binary load. Image/voice/video paths use this - * to defend against an authenticated OneBot client triggering a multi-GB - * read into memory. Group/private file uploads override this cap because - * QQ's file protocol legitimately supports up to 4 GiB. + * Default cap on a single binary load issued through this helper. Callers + * that route here (image / voice via base64+HTTP, group/private file + * uploads, avatar) get bounded reads. Not all callers route through here + * — in particular `video-upload.stageVideoSource` reads local-video files + * directly and enforces its own cap via `MAX_VIDEO_SIZE`. Group/private + * file uploads override this via `FILE_UPLOAD_MAX_BYTES` because QQ's + * file protocol legitimately supports up to 4 GiB. */ const DEFAULT_MAX_BINARY_SIZE = 1024 * 1024 * 1024; // 1 GiB /** Hard ceiling QQ's file protocol supports — used by group/private files. */ @@ -87,11 +90,42 @@ export async function loadBinarySource( if (Number.isFinite(declared) && declared > maxBytes) { throw new Error(`${resourceName} too large: ${declared} > ${maxBytes}`); } - const bytes = new Uint8Array(await resp.arrayBuffer()); - if (bytes.length > maxBytes) { - throw new Error(`${resourceName} too large: ${bytes.length} > ${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}`); + } + 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 new Error(`${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 }; } diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index 5ed36be3..79ddf949 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -280,6 +280,14 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu const local = resolveLocalFilePath(source); if (local && fs.existsSync(local)) { + // Pre-check on disk size BEFORE reading bytes into memory. The later + // `staged.bytes.length > MAX_VIDEO_SIZE` guard would otherwise only + // run after we'd already allocated the entire file (so a 10 GiB + // local path still OOMs us before the check fires). + const stat = fs.statSync(local); + if (stat.size > MAX_VIDEO_SIZE) { + throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB`); + } return { bytes: new Uint8Array(fs.readFileSync(local)), filePath: local, @@ -287,7 +295,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu }; } - const loaded = await loadBinarySource(source, 'video'); + const loaded = await loadBinarySource(source, 'video', MAX_VIDEO_SIZE); const fileName = element.fileName || loaded.fileName || ''; const stagedPath = path.join(tempDir, `snowluma-video-in-${crypto.randomUUID()}${sourceExtension(fileName, source)}`); fs.writeFileSync(stagedPath, Buffer.from(loaded.bytes)); diff --git a/packages/core/tests/highway-utils.test.ts b/packages/core/tests/highway-utils.test.ts index 087f22cd..130f8e68 100644 --- a/packages/core/tests/highway-utils.test.ts +++ b/packages/core/tests/highway-utils.test.ts @@ -2,7 +2,7 @@ import fs from 'fs'; import os from 'os'; import path from 'path'; import { pathToFileURL } from 'url'; -import { describe, expect, it } from 'vitest'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { loadBinarySource, resolveLocalFilePath } from '../src/bridge/highway/utils'; describe('highway source paths', () => { @@ -26,3 +26,76 @@ describe('highway source paths', () => { } }); }); + +describe('loadBinarySource maxBytes enforcement', () => { + const originalFetch = globalThis.fetch; + afterEach(() => { + globalThis.fetch = originalFetch; + vi.restoreAllMocks(); + }); + + it('rejects HTTP downloads larger than maxBytes via streaming, even without Content-Length', async () => { + // Streamed chunk-encoded response: no Content-Length, totals > cap. + const chunkSize = 4 * 1024; + const totalChunks = 16; + const stream = new ReadableStream({ + start(controller) { + for (let i = 0; i < totalChunks; i++) controller.enqueue(new Uint8Array(chunkSize)); + controller.close(); + }, + }); + globalThis.fetch = vi.fn(async () => new Response(stream, { + status: 200, + headers: { /* no content-length */ }, + })) as typeof fetch; + + // Cap below total: 16*4096 = 65536, cap 32 KiB → should throw mid-stream. + await expect( + loadBinarySource('https://example.test/big.bin', 'test', 32 * 1024), + ).rejects.toThrow(/too large/); + }); + + it('rejects HTTP downloads when Content-Length already exceeds maxBytes', async () => { + globalThis.fetch = vi.fn(async () => new Response(new Uint8Array(0), { + status: 200, + headers: { 'content-length': String(10 * 1024 * 1024) }, + })) as typeof fetch; + + await expect( + loadBinarySource('https://example.test/big.bin', 'test', 1024), + ).rejects.toThrow(/too large: 10485760/); + }); + + it('accepts a streamed download that fits inside maxBytes', async () => { + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(new Uint8Array([1, 2, 3])); + controller.enqueue(new Uint8Array([4, 5])); + controller.close(); + }, + }); + globalThis.fetch = vi.fn(async () => new Response(stream, { status: 200 })) as typeof fetch; + + const loaded = await loadBinarySource('https://example.test/small.bin', 'test', 1024); + expect(Array.from(loaded.bytes)).toEqual([1, 2, 3, 4, 5]); + }); + + it('rejects oversized local files via fs.stat before reading them', async () => { + const filePath = path.join(os.tmpdir(), `snowluma-binary-cap-${process.pid}-${Date.now()}.bin`); + fs.writeFileSync(filePath, Buffer.alloc(128)); + try { + await expect( + loadBinarySource(filePath, 'test', 64), + ).rejects.toThrow(/too large: 128 > 64/); + } finally { + try { fs.unlinkSync(filePath); } catch { /* ignore */ } + } + }); + + it('rejects oversized base64 payloads', async () => { + const big = Buffer.alloc(128).toString('base64'); + await expect( + loadBinarySource(`base64://${big}`, 'test', 64), + ).rejects.toThrow(/too large: 128 > 64/); + }); +}); From d66f0b2c6bc6c1baecf78d027b73937d76f6bd56 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:32:26 +0800 Subject: [PATCH 08/51] fix(bridge): point at file-upload actions in video-too-large error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QQ's short-video element protocol hard-limits a single video at 100 MB (NapCat enforces the same cap in highwayContext.uploadVideo with the same threshold and tells operators to switch to file upload). Mirror that hint so OneBot bot authors who hit the cap immediately see the correct alternative — `upload_group_file` / `upload_private_file`, which ride the FtnUpload path and go up to 4 GiB — instead of having to read the docs to figure out why a send_msg with a 200 MB video silently 'won't work'. --- packages/core/src/bridge/highway/video-upload.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index 79ddf949..a0778c6e 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -286,7 +286,7 @@ async function stageVideoSource(element: MessageElement, tempDir: string, cleanu // local path still OOMs us before the check fires). const stat = fs.statSync(local); if (stat.size > MAX_VIDEO_SIZE) { - throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB`); + throw new Error(`video file too large: ${(stat.size / (1024 * 1024)).toFixed(2)} MB > ${MAX_VIDEO_SIZE / (1024 * 1024)} MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`); } return { bytes: new Uint8Array(fs.readFileSync(local)), @@ -383,7 +383,7 @@ async function loadVideo(element: MessageElement): Promise { const staged = await stageVideoSource(element, tempDir, cleanups); if (staged.bytes.length === 0) throw new Error('video file is empty'); if (staged.bytes.length > MAX_VIDEO_SIZE) { - throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB`); + throw new Error(`video file too large: ${(staged.bytes.length / (1024 * 1024)).toFixed(2)} MB > 100 MB. Use upload_group_file / upload_private_file for files larger than 100 MB.`); } const hashes = computeHashes(staged.bytes); From ffe0c57abfdbe703a0adb3f5ee37781d47051d90 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=97=B6=E7=91=BE?= <74231782+sj817@users.noreply.github.com> Date: Sat, 16 May 2026 15:38:31 +0800 Subject: [PATCH 09/51] feat(webui): add SNOWLUMA_WEBUI_TRUST_PROXY for reverse-proxy deploys MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The previous commit tightened login rate-limiting to key off the real TCP socket peer, which fixed the X-Forwarded-For bypass but had the known caveat of collapsing every client into a single global bucket when the WebUI runs behind nginx / Caddy / a SaaS CDN. Give operators an explicit, audited way to opt back into per-client keying without re-introducing the spoof: * `SNOWLUMA_WEBUI_TRUST_PROXY` env var. Modes: - unset / empty → keep socket peer (safe default, unchanged) - "loopback" → trust X-Real-IP / X-Forwarded-For when the immediate socket peer is 127.0.0.1 / ::1 (nginx + WebUI on the same host) - "1" / "true" / → trust headers from any peer (only safe behind "all" a SaaS proxy that strips client-set headers) - comma-separated → trust headers only when the socket peer IP list matches one of these (proxy on another box) * When trusting headers we prefer X-Real-IP (single value the proxy overwrites unconditionally) and fall back to the first hop of XFF. We deliberately do NOT walk the full XFF chain — without a fully trusted proxy chain the leftmost value is still spoofable; a single-tier proxy is the only setup this app realistically sees. * Boot log prints "login rate-limit keyed by: …" so operators can verify the mode took effect, plus an extra WARN for "all" reminding them it's only safe with header-stripping in front. Logic lives in webui/client-ip.ts as a pure pickClientIp() that takes a socket-IP resolver, so the trust-proxy matrix can be exercised without standing up a server — see webui-client-ip.test.ts for the 11 new unit tests covering parse + dispatch + loopback / list / all / none modes. Smoke-tested with SNOWLUMA_WEBUI_TRUST_PROXY=loopback: - 5× failed login w/ X-Forwarded-For: 1.1.1.1 → 401 - 6th attempt same XFF → 429 (locked, per-XFF) - 6th attempt X-Forwarded-For: 2.2.2.2 → 401 (fresh bucket) - X-Real-IP overrides XFF when both present --- packages/core/src/webui/client-ip.ts | 106 ++++++++++++++++++++ packages/core/src/webui/server.ts | 24 ++--- packages/core/tests/webui-client-ip.test.ts | 92 +++++++++++++++++ 3 files changed, 209 insertions(+), 13 deletions(-) create mode 100644 packages/core/src/webui/client-ip.ts create mode 100644 packages/core/tests/webui-client-ip.test.ts diff --git a/packages/core/src/webui/client-ip.ts b/packages/core/src/webui/client-ip.ts new file mode 100644 index 00000000..a8765bc1 --- /dev/null +++ b/packages/core/src/webui/client-ip.ts @@ -0,0 +1,106 @@ +// Resolve the request's "real" client IP for per-IP rate limiting. +// +// Threat model: +// - By default we ONLY trust the TCP socket peer. `X-Forwarded-For` and +// `X-Real-IP` are client-controllable, so honoring them lets any +// client rotate the header to escape the 5-attempts/15-min login +// lockout. +// - Operators who actually run behind a reverse proxy (nginx, Caddy, +// a SaaS CDN) need a way to opt back into the real client IP. The +// `SNOWLUMA_WEBUI_TRUST_PROXY` env var lets them say "when the +// immediate TCP peer is THIS, treat the headers as authoritative". +// +// Supported values for SNOWLUMA_WEBUI_TRUST_PROXY: +// - unset / empty — default; ignore headers, use socket peer +// - "loopback" — trust headers when the socket peer is 127.0.0.1 +// or ::1 (typical for nginx/Caddy on the same host) +// - "1" / "true" / — trust headers from any peer (only safe behind a +// "all" trusted SaaS CDN that strips client-set headers) +// - comma-separated — trust headers when the socket peer matches one +// IP list of these IPs (reverse proxy on another machine) +// +// When trusted, we prefer X-Real-IP (a single value the reverse proxy +// overwrites unconditionally) and fall back to the first hop of +// X-Forwarded-For. We never parse the FULL XFF chain — if the proxy +// chain isn't fully trusted, the leftmost value can still be spoofed +// by the original client, and a single-tier proxy is the only setup +// this app realistically sees. + +import type { Context } from 'hono'; +import { getConnInfo } from '@hono/node-server/conninfo'; + +export type TrustProxyMode = + | { kind: 'none' } + | { kind: 'loopback' } + | { kind: 'all' } + | { kind: 'ip-list'; ips: Set }; + +export function parseTrustProxy(raw: string | undefined): TrustProxyMode { + const value = raw?.trim().toLowerCase() ?? ''; + if (!value) return { kind: 'none' }; + if (value === '1' || value === 'true' || value === 'all') return { kind: 'all' }; + if (value === 'loopback') return { kind: 'loopback' }; + const ips = new Set( + value.split(',').map((s) => s.trim()).filter(Boolean), + ); + if (ips.size === 0) return { kind: 'none' }; + return { kind: 'ip-list', ips }; +} + +export function describeTrustProxy(mode: TrustProxyMode): string { + switch (mode.kind) { + case 'none': return 'socket peer (default)'; + case 'all': return 'X-Real-IP / X-Forwarded-For from any peer'; + case 'loopback': return 'X-Real-IP / X-Forwarded-For when socket peer is loopback'; + case 'ip-list': return `X-Real-IP / X-Forwarded-For when socket peer is in [${[...mode.ips].join(',')}]`; + } +} + +function isLoopback(ip: string): boolean { + return ip === '127.0.0.1' || ip === '::1' || ip === '::ffff:127.0.0.1'; +} + +function shouldTrustHeaders(mode: TrustProxyMode, socketIp: string): boolean { + switch (mode.kind) { + case 'none': return false; + case 'all': return true; + case 'loopback': return isLoopback(socketIp); + case 'ip-list': return mode.ips.has(socketIp); + } +} + +/** + * Pick the right "client IP" for rate-limit keying. + * + * Exposed as a pure function over a small dependency surface so the + * unit tests can fabricate request shapes without spinning up a server. + */ +export function pickClientIp( + c: Pick, + mode: TrustProxyMode, + getSocketIp: () => string, +): string { + const socketIp = (() => { + try { return getSocketIp() || '127.0.0.1'; } + catch { return '127.0.0.1'; } + })(); + + if (!shouldTrustHeaders(mode, socketIp)) return socketIp; + + const realIp = c.req.header('x-real-ip')?.trim(); + if (realIp) return realIp; + const xff = c.req.header('x-forwarded-for'); + if (xff) { + const first = xff.split(',')[0].trim(); + if (first) return first; + } + return socketIp; +} + +/** Convenience binding for the live server: read socket via getConnInfo. */ +export function makeClientIpResolver(mode: TrustProxyMode): (c: Context) => string { + return (c) => pickClientIp(c, mode, () => { + try { return getConnInfo(c).remote.address ?? '127.0.0.1'; } + catch { return '127.0.0.1'; } + }); +} diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index bf792788..c71a5d11 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -1,7 +1,7 @@ import { serve } from '@hono/node-server'; -import { getConnInfo } from '@hono/node-server/conninfo'; import { serveStatic } from '@hono/node-server/serve-static'; import { Hono, type Context } from 'hono'; +import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger'; import { randomBytes } from 'crypto'; import type { OneBotManager } from '../onebot/manager'; @@ -66,19 +66,13 @@ function purgeExpiredTokens() { } /** - * Resolve the client IP from the underlying TCP socket via the official - * @hono/node-server conninfo helper. We deliberately do NOT trust - * `X-Forwarded-For` — the WebUI listens on a local port with no required - * reverse proxy, so accepting that header would let any client rotate it - * to bypass the per-IP login lockout. + * Resolve the client IP for per-IP rate limiting. Default is the TCP + * socket peer (cannot be spoofed by the client). Operators behind a + * reverse proxy must opt in via the `SNOWLUMA_WEBUI_TRUST_PROXY` env + * var; see `./client-ip.ts` for the accepted values. */ -function getClientIp(c: Context): string { - try { - return getConnInfo(c).remote.address ?? '127.0.0.1'; - } catch { - return '127.0.0.1'; - } -} +const trustProxyMode = parseTrustProxy(process.env.SNOWLUMA_WEBUI_TRUST_PROXY); +const getClientIp = makeClientIpResolver(trustProxyMode); async function fetchQqAvatar(uin: string): Promise<{ body: Uint8Array; contentType: string }> { const response = await fetch(`https://q1.qlogo.cn/g?b=qq&nk=${encodeURIComponent(uin)}&s=100`, { @@ -109,6 +103,10 @@ export async function initWebUI( } else if (auth.mustChangePassword()) { log.warn('password change is still required'); } + log.info('login rate-limit keyed by: %s', describeTrustProxy(trustProxyMode)); + if (trustProxyMode.kind === 'all') { + log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For'); + } const app = new Hono(); diff --git a/packages/core/tests/webui-client-ip.test.ts b/packages/core/tests/webui-client-ip.test.ts new file mode 100644 index 00000000..0a8159f3 --- /dev/null +++ b/packages/core/tests/webui-client-ip.test.ts @@ -0,0 +1,92 @@ +import { describe, expect, it } from 'vitest'; +import { + describeTrustProxy, + parseTrustProxy, + pickClientIp, + type TrustProxyMode, +} from '../src/webui/client-ip'; + +function mockCtx(headers: Record = {}) { + return { + req: { + header: (name: string) => headers[name.toLowerCase()], + }, + } as unknown as Parameters[0]; +} + +describe('parseTrustProxy', () => { + it('treats empty / unset as none (safe default)', () => { + expect(parseTrustProxy(undefined)).toEqual({ kind: 'none' }); + expect(parseTrustProxy('')).toEqual({ kind: 'none' }); + expect(parseTrustProxy(' ')).toEqual({ kind: 'none' }); + }); + + it('recognises "1" / "true" / "all" as full trust', () => { + expect(parseTrustProxy('1')).toEqual({ kind: 'all' }); + expect(parseTrustProxy('true')).toEqual({ kind: 'all' }); + expect(parseTrustProxy('ALL')).toEqual({ kind: 'all' }); + }); + + it('recognises "loopback" case-insensitively', () => { + expect(parseTrustProxy('Loopback')).toEqual({ kind: 'loopback' }); + }); + + it('parses a comma-separated IP list', () => { + const mode = parseTrustProxy('10.0.0.1, 192.168.1.5, '); + expect(mode.kind).toBe('ip-list'); + if (mode.kind !== 'ip-list') throw new Error('unreachable'); + expect([...mode.ips].sort()).toEqual(['10.0.0.1', '192.168.1.5']); + }); +}); + +describe('pickClientIp', () => { + const xff = { 'x-forwarded-for': '203.0.113.7, 10.0.0.1' }; + const realIp = { 'x-real-ip': '203.0.113.42' }; + const both = { ...xff, ...realIp }; + + it('returns socket peer and IGNORES headers when trust=none (default)', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx(both), mode, () => '198.51.100.9')).toBe('198.51.100.9'); + }); + + it('honors X-Real-IP first, then XFF first hop, when trust=all', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(xff), mode, () => '10.0.0.1')).toBe('203.0.113.7'); + }); + + it('falls back to socket peer when trust=all but no headers present', () => { + const mode: TrustProxyMode = { kind: 'all' }; + expect(pickClientIp(mockCtx({}), mode, () => '10.0.0.1')).toBe('10.0.0.1'); + }); + + it('trust=loopback honors headers only when socket is loopback', () => { + const mode: TrustProxyMode = { kind: 'loopback' }; + expect(pickClientIp(mockCtx(both), mode, () => '127.0.0.1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '::1')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '::ffff:127.0.0.1')).toBe('203.0.113.42'); + // Non-loopback peer → headers ignored, socket wins. + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.1')).toBe('10.0.0.1'); + }); + + it('trust=ip-list honors headers only when socket is in the list', () => { + const mode: TrustProxyMode = { kind: 'ip-list', ips: new Set(['10.0.0.1', '10.0.0.2']) }; + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.2')).toBe('203.0.113.42'); + expect(pickClientIp(mockCtx(both), mode, () => '10.0.0.9')).toBe('10.0.0.9'); + }); + + it('survives a socket resolver that throws', () => { + const mode: TrustProxyMode = { kind: 'none' }; + expect(pickClientIp(mockCtx({}), mode, () => { throw new Error('boom'); })).toBe('127.0.0.1'); + }); +}); + +describe('describeTrustProxy', () => { + it('renders each mode in a recognisable form for the boot log', () => { + expect(describeTrustProxy({ kind: 'none' })).toContain('socket peer'); + expect(describeTrustProxy({ kind: 'all' })).toContain('any peer'); + expect(describeTrustProxy({ kind: 'loopback' })).toContain('loopback'); + expect(describeTrustProxy({ kind: 'ip-list', ips: new Set(['10.0.0.1']) })) + .toContain('10.0.0.1'); + }); +}); From 2d21316a74a58ebff289b29b1b46f23bc4424c04 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sat, 16 May 2026 21:49:32 +0800 Subject: [PATCH 10/51] fix(onebot): bound download_file and drop unused error helper MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR #39 hardened most of the OneBot action surface but left download_file on the original `await response.arrayBuffer()` path — an authenticated client could still hand us a multi-GB URL (or a chunked response with no Content-Length) and OOM the bot. The base64 branch had the same problem in the other direction: `Buffer.from(huge, 'base64')` allocates the decoded payload before any size check. Match the loadBinarySource pattern that `0804351` introduced for highway uploads: * HTTP path runs through `fetchDownloadFile`: AbortSignal.timeout (60s), Content-Length precheck, then a streaming reader that aborts the moment the running total crosses the 1 GiB cap. * Base64 path rejects before `Buffer.from` based on the upper-bound `floor(len * 3 / 4)`, with a post-decode check for safety. * Writes go through `fs.promises.writeFile` so a multi-hundred-MB download doesn't stall every other bot action on the event loop. Also drop the `actionFailed` helper added in the same PR — it was intended as a sanitized-error wrapper but never wired up. Wiring it into the dozen-or-so `String(e)` sites is its own cleanup; for now remove the dead code (and the no-longer-used createLogger import). --- packages/core/src/onebot/actions/extended.ts | 108 ++++++++++++++----- 1 file changed, 82 insertions(+), 26 deletions(-) diff --git a/packages/core/src/onebot/actions/extended.ts b/packages/core/src/onebot/actions/extended.ts index 5c3df155..3935872d 100644 --- a/packages/core/src/onebot/actions/extended.ts +++ b/packages/core/src/onebot/actions/extended.ts @@ -2,18 +2,61 @@ import type { ApiHandler, ApiActionContext } from '../api-handler'; import { asMessage, asNumber, asString, asBoolean } from '../api-handler'; import type { ForwardPreviewMeta } from '../modules/message-actions'; import { RETCODE, failedResponse, okResponse } from '../types'; -import { createLogger } from '../../utils/logger'; -const log = createLogger('OneBot.Action'); +// Bounded download for the OneBot `download_file` action. An authenticated +// client could otherwise hand us a multi-GB URL (or chunked response with +// no Content-Length) and OOM the bot — `await response.arrayBuffer()` +// happily allocates the whole payload before any size check fires. +const DOWNLOAD_FILE_MAX_BYTES = 1024 * 1024 * 1024; // 1 GiB +const DOWNLOAD_FILE_TIMEOUT_MS = 60_000; -/** - * Standard error wrapper. Logs the full error (so operators can debug) but - * surfaces only `Error.message` (or the supplied fallback) to the caller. - */ -function actionFailed(action: string, err: unknown, fallback = 'action failed') { - const detail = err instanceof Error ? err.message : String(err); - log.warn('%s failed: %s', action, detail); - return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : fallback); +async function fetchDownloadFile( + url: string, + headers: Record, + maxBytes: number, + timeoutMs: number, +): Promise { + const response = await fetch(url, { + headers, + signal: AbortSignal.timeout(timeoutMs), + }); + if (!response.ok) throw new Error(`download failed: HTTP ${response.status}`); + + const declared = Number(response.headers.get('content-length') ?? '0'); + if (Number.isFinite(declared) && declared > maxBytes) { + throw new Error(`download too large: ${declared} > ${maxBytes}`); + } + + const reader = response.body?.getReader(); + if (!reader) { + const bytes = Buffer.from(await response.arrayBuffer()); + if (bytes.length > maxBytes) { + throw new Error(`download too large: ${bytes.length} > ${maxBytes}`); + } + return bytes; + } + + // Stream so a server that omits / understates Content-Length can't make + // us buffer past maxBytes — abort the read as soon as the running total + // crosses the cap. + 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 new Error(`download too large: > ${maxBytes}`); + } + chunks.push(value); + } + } finally { + reader.releaseLock(); + } + return Buffer.concat(chunks, total); } /** @@ -581,25 +624,38 @@ export function register(h: ApiHandler, ctx: ApiActionContext): void { return resolved; }; - let filePath: string; + let buf: Buffer; if (base64) { - const buf = Buffer.from(base64, 'base64'); - const safe = resolveSafePath(name, buf); - if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); - filePath = safe; - fs.writeFileSync(filePath, buf); + // Every 4 base64 chars decode to at most 3 bytes. Reject before + // `Buffer.from` allocates anything to avoid OOM on a giant payload + // that wouldn't pass the post-decode check anyway. + const upperBound = Math.floor((base64.length * 3) / 4); + if (upperBound > DOWNLOAD_FILE_MAX_BYTES) { + return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + } + buf = Buffer.from(base64, 'base64'); + if (buf.length > DOWNLOAD_FILE_MAX_BYTES) { + return failedResponse(RETCODE.BAD_REQUEST, `base64 payload too large: ${buf.length} > ${DOWNLOAD_FILE_MAX_BYTES} bytes`); + } } else { - const response = await fetch(url!, { - headers: parseDownloadHeaders(params.headers), - }); - if (!response.ok) return failedResponse(RETCODE.ACTION_FAILED, `download failed: ${response.status}`); - const buf = Buffer.from(await response.arrayBuffer()); - const safe = resolveSafePath(name, buf); - if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); - filePath = safe; - fs.writeFileSync(filePath, buf); + try { + buf = await fetchDownloadFile( + url!, + parseDownloadHeaders(params.headers), + DOWNLOAD_FILE_MAX_BYTES, + DOWNLOAD_FILE_TIMEOUT_MS, + ); + } catch (err) { + return failedResponse(RETCODE.ACTION_FAILED, err instanceof Error ? err.message : String(err)); + } } - return okResponse({ file: filePath }); + + const safe = resolveSafePath(name, buf); + if (!safe) return failedResponse(RETCODE.BAD_REQUEST, 'invalid file name'); + // Async write so we don't block the event loop on a GiB-class download + // (the prior `writeFileSync` stalled every other bot action while it ran). + await fs.promises.writeFile(safe, buf); + return okResponse({ file: safe }); }); h.registerAction('set_qq_profile', async (params) => { From a8661ea216af48fa552dcc71ec4a979a1a6838eb Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 00:23:37 +0800 Subject: [PATCH 11/51] feat(ui): add @snowluma/ui shared UI library Lifts the shadcn primitives + Tailwind 4 theme tokens from webui into a dedicated workspace package consumable by both webui and SnowLumaDesktop. - 14 primitives (Button, Dialog, AlertDialog, Input, Label, Checkbox, Select, Switch, Tabs, Card, Avatar, Badge, Progress, ScrollArea, Separator, Sheet, Skeleton, Tooltip) + sonner Toaster wrapper - Tailwind 4 theme tokens exported via styles/theme.css - tsup ESM build with declaration files - publishConfig.access=public mirroring @snowluma/sdk Consumers @import '@snowluma/ui/styles/theme.css' for tokens and add an @source directive to scan the package for utility classes. --- packages/ui/package.json | 88 +++ packages/ui/src/components/alert-dialog.tsx | 97 +++ packages/ui/src/components/avatar.tsx | 44 ++ packages/ui/src/components/badge.tsx | 26 + packages/ui/src/components/button.tsx | 42 ++ packages/ui/src/components/card.tsx | 50 ++ packages/ui/src/components/checkbox.tsx | 29 + packages/ui/src/components/dialog.tsx | 89 +++ packages/ui/src/components/input.tsx | 24 + packages/ui/src/components/label.tsx | 17 + packages/ui/src/components/progress.tsx | 32 + packages/ui/src/components/scroll-area.tsx | 49 ++ packages/ui/src/components/select.tsx | 141 ++++ packages/ui/src/components/separator.tsx | 23 + packages/ui/src/components/sheet.tsx | 66 ++ packages/ui/src/components/skeleton.tsx | 6 + packages/ui/src/components/switch.tsx | 30 + packages/ui/src/components/tabs.tsx | 52 ++ packages/ui/src/components/toaster.tsx | 29 + packages/ui/src/components/tooltip.tsx | 28 + packages/ui/src/index.ts | 68 ++ packages/ui/src/lib/cn.ts | 6 + packages/ui/src/styles/theme.css | 140 ++++ packages/ui/tsconfig.json | 16 + packages/ui/tsup.config.ts | 12 + pnpm-lock.yaml | 791 +++++++++++++++++++- 26 files changed, 1988 insertions(+), 7 deletions(-) create mode 100644 packages/ui/package.json create mode 100644 packages/ui/src/components/alert-dialog.tsx create mode 100644 packages/ui/src/components/avatar.tsx create mode 100644 packages/ui/src/components/badge.tsx create mode 100644 packages/ui/src/components/button.tsx create mode 100644 packages/ui/src/components/card.tsx create mode 100644 packages/ui/src/components/checkbox.tsx create mode 100644 packages/ui/src/components/dialog.tsx create mode 100644 packages/ui/src/components/input.tsx create mode 100644 packages/ui/src/components/label.tsx create mode 100644 packages/ui/src/components/progress.tsx create mode 100644 packages/ui/src/components/scroll-area.tsx create mode 100644 packages/ui/src/components/select.tsx create mode 100644 packages/ui/src/components/separator.tsx create mode 100644 packages/ui/src/components/sheet.tsx create mode 100644 packages/ui/src/components/skeleton.tsx create mode 100644 packages/ui/src/components/switch.tsx create mode 100644 packages/ui/src/components/tabs.tsx create mode 100644 packages/ui/src/components/toaster.tsx create mode 100644 packages/ui/src/components/tooltip.tsx create mode 100644 packages/ui/src/index.ts create mode 100644 packages/ui/src/lib/cn.ts create mode 100644 packages/ui/src/styles/theme.css create mode 100644 packages/ui/tsconfig.json create mode 100644 packages/ui/tsup.config.ts diff --git a/packages/ui/package.json b/packages/ui/package.json new file mode 100644 index 00000000..3388aa62 --- /dev/null +++ b/packages/ui/package.json @@ -0,0 +1,88 @@ +{ + "name": "@snowluma/ui", + "author": { + "name": "MotricSeven", + "email": "motricseven@gmail.com" + }, + "version": "1.8.1", + "description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components", + "keywords": [ + "snowluma", + "ui", + "shadcn", + "tailwind", + "react" + ], + "homepage": "https://github.com/SnowLuma/SnowLuma#readme", + "bugs": { + "url": "https://github.com/SnowLuma/SnowLuma/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/SnowLuma/SnowLuma.git", + "directory": "packages/ui" + }, + "license": "UNLICENSED", + "type": "module", + "sideEffects": [ + "**/*.css" + ], + "main": "./dist/index.js", + "types": "./dist/index.d.ts", + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.js" + }, + "./styles/theme.css": "./src/styles/theme.css", + "./package.json": "./package.json" + }, + "files": [ + "dist", + "src/styles" + ], + "scripts": { + "clean": "node -e \"const fs = require('node:fs'); fs.rmSync('dist', { recursive: true, force: true })\"", + "prebuild": "pnpm run clean", + "build": "tsup", + "dev": "tsup --watch", + "prepack": "pnpm run build", + "typecheck": "tsc --noEmit" + }, + "publishConfig": { + "access": "public" + }, + "engines": { + "node": ">=22" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + }, + "dependencies": { + "@radix-ui/react-alert-dialog": "^1.1.7", + "@radix-ui/react-checkbox": "^1.1.5", + "@radix-ui/react-dialog": "^1.1.7", + "@radix-ui/react-label": "^2.1.3", + "@radix-ui/react-scroll-area": "^1.2.4", + "@radix-ui/react-select": "^2.2.6", + "@radix-ui/react-separator": "^1.1.3", + "@radix-ui/react-slot": "^1.1.3", + "@radix-ui/react-switch": "^1.2.6", + "@radix-ui/react-tabs": "^1.1.13", + "@radix-ui/react-tooltip": "^1.1.9", + "class-variance-authority": "^0.7.1", + "clsx": "^2.1.1", + "lucide-react": "^0.469.0", + "sonner": "^2.0.6", + "tailwind-merge": "^3.5.0" + }, + "devDependencies": { + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "react": "^19.2.5", + "react-dom": "^19.2.5", + "tsup": "^8.5.0", + "typescript": "catalog:" + } +} diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsx new file mode 100644 index 00000000..0a20ddff --- /dev/null +++ b/packages/ui/src/components/alert-dialog.tsx @@ -0,0 +1,97 @@ +import * as React from 'react'; +import * as AlertDialogPrimitive from '@radix-ui/react-alert-dialog'; +import { cn } from '../lib/cn'; +import { buttonVariants } from './button'; + +const AlertDialog = AlertDialogPrimitive.Root; +const AlertDialogTrigger = AlertDialogPrimitive.Trigger; +const AlertDialogPortal = AlertDialogPrimitive.Portal; + +const AlertDialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogOverlay.displayName = 'AlertDialogOverlay'; + +const AlertDialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + + +)); +AlertDialogContent.displayName = 'AlertDialogContent'; + +const AlertDialogHeader = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const AlertDialogFooter = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const AlertDialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogTitle.displayName = 'AlertDialogTitle'; + +const AlertDialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogDescription.displayName = 'AlertDialogDescription'; + +const AlertDialogAction = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogAction.displayName = 'AlertDialogAction'; + +const AlertDialogCancel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +AlertDialogCancel.displayName = 'AlertDialogCancel'; + +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +}; diff --git a/packages/ui/src/components/avatar.tsx b/packages/ui/src/components/avatar.tsx new file mode 100644 index 00000000..768b6373 --- /dev/null +++ b/packages/ui/src/components/avatar.tsx @@ -0,0 +1,44 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +interface AvatarProps extends React.HTMLAttributes { + size?: number; +} + +const Avatar = React.forwardRef( + ({ className, size = 36, style, ...props }, ref) => ( +
+ ) +); +Avatar.displayName = 'Avatar'; + +const AvatarImage = React.forwardRef>( + ({ className, alt = '', ...props }, ref) => ( + {alt} + ) +); +AvatarImage.displayName = 'AvatarImage'; + +const AvatarFallback = React.forwardRef>( + ({ className, ...props }, ref) => ( + + ) +); +AvatarFallback.displayName = 'AvatarFallback'; + +export { Avatar, AvatarImage, AvatarFallback }; diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx new file mode 100644 index 00000000..25904349 --- /dev/null +++ b/packages/ui/src/components/badge.tsx @@ -0,0 +1,26 @@ +import * as React from 'react'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +export const badgeVariants = cva( + 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium transition-colors', + { + variants: { + variant: { + default: 'border-transparent bg-primary/15 text-primary', + secondary: 'border-transparent bg-secondary text-secondary-foreground', + destructive: 'border-transparent bg-destructive/15 text-destructive', + success: 'border-transparent bg-success/15 text-success', + warning: 'border-transparent bg-warning/15 text-warning', + outline: 'border-border text-foreground', + }, + }, + defaultVariants: { variant: 'default' }, + } +); + +export interface BadgeProps extends React.HTMLAttributes, VariantProps {} + +export function Badge({ className, variant, ...props }: BadgeProps) { + return ; +} diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx new file mode 100644 index 00000000..42a436fe --- /dev/null +++ b/packages/ui/src/components/button.tsx @@ -0,0 +1,42 @@ +import * as React from 'react'; +import { Slot } from '@radix-ui/react-slot'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +export const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring cursor-pointer", + { + variants: { + variant: { + default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:bg-primary/95', + destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90', + outline: 'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground', + secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80', + ghost: 'hover:bg-accent hover:text-accent-foreground', + link: 'text-primary underline-offset-4 hover:underline', + }, + size: { + default: 'h-9 px-4 py-2', + sm: 'h-8 rounded-md px-3 text-xs', + lg: 'h-10 rounded-md px-6', + icon: 'size-9', + 'icon-sm': 'size-8', + }, + }, + defaultVariants: { variant: 'default', size: 'default' }, + } +); + +export interface ButtonProps + extends React.ButtonHTMLAttributes, + VariantProps { + asChild?: boolean; +} + +export const Button = React.forwardRef( + ({ className, variant, size, asChild = false, ...props }, ref) => { + const Comp = asChild ? Slot : 'button'; + return ; + } +); +Button.displayName = 'Button'; diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx new file mode 100644 index 00000000..ace53f35 --- /dev/null +++ b/packages/ui/src/components/card.tsx @@ -0,0 +1,50 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +const Card = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ) +); +Card.displayName = 'Card'; + +const CardHeader = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ) +); +CardHeader.displayName = 'CardHeader'; + +const CardTitle = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ) +); +CardTitle.displayName = 'CardTitle'; + +const CardDescription = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ) +); +CardDescription.displayName = 'CardDescription'; + +const CardContent = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ) +); +CardContent.displayName = 'CardContent'; + +const CardFooter = React.forwardRef>( + ({ className, ...props }, ref) => ( +
+ ) +); +CardFooter.displayName = 'CardFooter'; + +export { Card, CardHeader, CardTitle, CardDescription, CardContent, CardFooter }; diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsx new file mode 100644 index 00000000..f7e0bc60 --- /dev/null +++ b/packages/ui/src/components/checkbox.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; +import * as CheckboxPrimitive from '@radix-ui/react-checkbox'; +import { Check, Minus } from 'lucide-react'; +import { cn } from '../lib/cn'; + +const Checkbox = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + {props.checked === 'indeterminate' ? : } + + +)); +Checkbox.displayName = 'Checkbox'; + +export { Checkbox }; diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx new file mode 100644 index 00000000..ba735bfd --- /dev/null +++ b/packages/ui/src/components/dialog.tsx @@ -0,0 +1,89 @@ +import * as React from 'react'; +import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { X } from 'lucide-react'; +import { cn } from '../lib/cn'; + +const Dialog = DialogPrimitive.Root; +const DialogTrigger = DialogPrimitive.Trigger; +const DialogPortal = DialogPrimitive.Portal; +const DialogClose = DialogPrimitive.Close; + +const DialogOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogOverlay.displayName = 'DialogOverlay'; + +const DialogContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef & { showClose?: boolean } +>(({ className, children, showClose = true, ...props }, ref) => ( + + + + {children} + {showClose && ( + + + Close + + )} + + +)); +DialogContent.displayName = 'DialogContent'; + +const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const DialogFooter = ({ className, ...props }: React.HTMLAttributes) => ( +
+); + +const DialogTitle = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogTitle.displayName = 'DialogTitle'; + +const DialogDescription = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +DialogDescription.displayName = 'DialogDescription'; + +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +}; diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx new file mode 100644 index 00000000..7b1bd1e7 --- /dev/null +++ b/packages/ui/src/components/input.tsx @@ -0,0 +1,24 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +const Input = React.forwardRef>( + ({ className, type, ...props }, ref) => ( + + ) +); +Input.displayName = 'Input'; + +export { Input }; diff --git a/packages/ui/src/components/label.tsx b/packages/ui/src/components/label.tsx new file mode 100644 index 00000000..6fdbf875 --- /dev/null +++ b/packages/ui/src/components/label.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import * as LabelPrimitive from '@radix-ui/react-label'; +import { cn } from '../lib/cn'; + +const Label = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +Label.displayName = 'Label'; + +export { Label }; diff --git a/packages/ui/src/components/progress.tsx b/packages/ui/src/components/progress.tsx new file mode 100644 index 00000000..0cc75e45 --- /dev/null +++ b/packages/ui/src/components/progress.tsx @@ -0,0 +1,32 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +interface ProgressProps extends React.HTMLAttributes { + value?: number; + indicatorClassName?: string; +} + +const Progress = React.forwardRef( + ({ className, value = 0, indicatorClassName, ...props }, ref) => { + const clamped = Math.max(0, Math.min(100, value)); + return ( +
+
+
+ ); + } +); +Progress.displayName = 'Progress'; + +export { Progress }; diff --git a/packages/ui/src/components/scroll-area.tsx b/packages/ui/src/components/scroll-area.tsx new file mode 100644 index 00000000..98d8f8c6 --- /dev/null +++ b/packages/ui/src/components/scroll-area.tsx @@ -0,0 +1,49 @@ +import * as React from 'react'; +import * as ScrollAreaPrimitive from '@radix-ui/react-scroll-area'; +import { cn } from '../lib/cn'; + +interface ScrollAreaProps extends React.ComponentPropsWithoutRef { + viewportClassName?: string; +} + +const ScrollArea = React.forwardRef, ScrollAreaProps>( + ({ className, children, viewportClassName, ...props }, ref) => ( + + div]:!block', viewportClassName)} + > + {children} + + + + + + ) +); +ScrollArea.displayName = 'ScrollArea'; + +const ScrollBar = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, orientation = 'vertical', ...props }, ref) => ( + + + +)); +ScrollBar.displayName = 'ScrollBar'; + +export { ScrollArea, ScrollBar }; diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx new file mode 100644 index 00000000..5d61b0af --- /dev/null +++ b/packages/ui/src/components/select.tsx @@ -0,0 +1,141 @@ +import * as React from 'react'; +import * as SelectPrimitive from '@radix-ui/react-select'; +import { Check, ChevronDown, ChevronUp } from 'lucide-react'; +import { cn } from '../lib/cn'; + +const Select = SelectPrimitive.Root; +const SelectGroup = SelectPrimitive.Group; +const SelectValue = SelectPrimitive.Value; + +const SelectTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + {children} + + + + +)); +SelectTrigger.displayName = 'SelectTrigger'; + +const SelectScrollUpButton = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)); +SelectScrollUpButton.displayName = 'SelectScrollUpButton'; + +const SelectScrollDownButton = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)); +SelectScrollDownButton.displayName = 'SelectScrollDownButton'; + +const SelectContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, position = 'popper', ...props }, ref) => ( + + + + + {children} + + + + +)); +SelectContent.displayName = 'SelectContent'; + +const SelectLabel = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SelectLabel.displayName = 'SelectLabel'; + +const SelectItem = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, children, ...props }, ref) => ( + + + + + + + {children} + +)); +SelectItem.displayName = 'SelectItem'; + +const SelectSeparator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SelectSeparator.displayName = 'SelectSeparator'; + +export { + Select, + SelectGroup, + SelectValue, + SelectTrigger, + SelectContent, + SelectLabel, + SelectItem, + SelectSeparator, + SelectScrollUpButton, + SelectScrollDownButton, +}; diff --git a/packages/ui/src/components/separator.tsx b/packages/ui/src/components/separator.tsx new file mode 100644 index 00000000..63dfdd8b --- /dev/null +++ b/packages/ui/src/components/separator.tsx @@ -0,0 +1,23 @@ +import * as React from 'react'; +import * as SeparatorPrimitive from '@radix-ui/react-separator'; +import { cn } from '../lib/cn'; + +const Separator = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, orientation = 'horizontal', decorative = true, ...props }, ref) => ( + +)); +Separator.displayName = 'Separator'; + +export { Separator }; diff --git a/packages/ui/src/components/sheet.tsx b/packages/ui/src/components/sheet.tsx new file mode 100644 index 00000000..9f4a8406 --- /dev/null +++ b/packages/ui/src/components/sheet.tsx @@ -0,0 +1,66 @@ +import * as React from 'react'; +import * as DialogPrimitive from '@radix-ui/react-dialog'; +import { X } from 'lucide-react'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +const Sheet = DialogPrimitive.Root; +const SheetTrigger = DialogPrimitive.Trigger; +const SheetClose = DialogPrimitive.Close; +const SheetPortal = DialogPrimitive.Portal; + +const SheetOverlay = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +SheetOverlay.displayName = 'SheetOverlay'; + +const sheetVariants = cva( + 'fixed z-50 gap-4 bg-card p-0 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500 outline-none', + { + variants: { + side: { + top: 'inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top', + bottom: 'inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom', + left: 'inset-y-0 left-0 h-full w-3/4 max-w-xs border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm', + right: 'inset-y-0 right-0 h-full w-3/4 max-w-xs border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm', + }, + }, + defaultVariants: { side: 'right' }, + } +); + +interface SheetContentProps + extends React.ComponentPropsWithoutRef, + VariantProps { + showClose?: boolean; +} + +const SheetContent = React.forwardRef, SheetContentProps>( + ({ side = 'right', className, children, showClose = true, ...props }, ref) => ( + + + + {children} + {showClose && ( + + + Close + + )} + + + ) +); +SheetContent.displayName = 'SheetContent'; + +export { Sheet, SheetTrigger, SheetClose, SheetContent, SheetPortal, SheetOverlay }; diff --git a/packages/ui/src/components/skeleton.tsx b/packages/ui/src/components/skeleton.tsx new file mode 100644 index 00000000..f89e9f2b --- /dev/null +++ b/packages/ui/src/components/skeleton.tsx @@ -0,0 +1,6 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +export function Skeleton({ className, ...props }: React.HTMLAttributes) { + return
; +} diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsx new file mode 100644 index 00000000..a8c875e2 --- /dev/null +++ b/packages/ui/src/components/switch.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import * as SwitchPrimitive from '@radix-ui/react-switch'; +import { cn } from '../lib/cn'; + +const Switch = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + + + +)); +Switch.displayName = 'Switch'; + +export { Switch }; diff --git a/packages/ui/src/components/tabs.tsx b/packages/ui/src/components/tabs.tsx new file mode 100644 index 00000000..21d44c14 --- /dev/null +++ b/packages/ui/src/components/tabs.tsx @@ -0,0 +1,52 @@ +import * as React from 'react'; +import * as TabsPrimitive from '@radix-ui/react-tabs'; +import { cn } from '../lib/cn'; + +const Tabs = TabsPrimitive.Root; + +const TabsList = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +TabsList.displayName = 'TabsList'; + +const TabsTrigger = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +TabsTrigger.displayName = 'TabsTrigger'; + +const TabsContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, ...props }, ref) => ( + +)); +TabsContent.displayName = 'TabsContent'; + +export { Tabs, TabsList, TabsTrigger, TabsContent }; diff --git a/packages/ui/src/components/toaster.tsx b/packages/ui/src/components/toaster.tsx new file mode 100644 index 00000000..73b50998 --- /dev/null +++ b/packages/ui/src/components/toaster.tsx @@ -0,0 +1,29 @@ +import { Toaster as Sonner, toast, type ToasterProps } from 'sonner'; + +/** + * SnowLuma-themed toaster. Uses the Tailwind `--*-foreground / --background` + * tokens defined in `@snowluma/ui/styles/theme.css` so toasts match the + * surrounding chrome in both light and dark mode. + */ +export function Toaster(props: ToasterProps) { + return ( + + ); +} + +export { toast }; +export type { ToasterProps }; diff --git a/packages/ui/src/components/tooltip.tsx b/packages/ui/src/components/tooltip.tsx new file mode 100644 index 00000000..0fde2304 --- /dev/null +++ b/packages/ui/src/components/tooltip.tsx @@ -0,0 +1,28 @@ +import * as React from 'react'; +import * as TooltipPrimitive from '@radix-ui/react-tooltip'; +import { cn } from '../lib/cn'; + +const TooltipProvider = TooltipPrimitive.Provider; +const Tooltip = TooltipPrimitive.Root; +const TooltipTrigger = TooltipPrimitive.Trigger; + +const TooltipContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, sideOffset = 6, ...props }, ref) => ( + + + +)); +TooltipContent.displayName = 'TooltipContent'; + +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider }; diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts new file mode 100644 index 00000000..7f50911c --- /dev/null +++ b/packages/ui/src/index.ts @@ -0,0 +1,68 @@ +export { cn } from './lib/cn'; +export { Button, buttonVariants, type ButtonProps } from './components/button'; +export { + AlertDialog, + AlertDialogPortal, + AlertDialogOverlay, + AlertDialogTrigger, + AlertDialogContent, + AlertDialogHeader, + AlertDialogFooter, + AlertDialogTitle, + AlertDialogDescription, + AlertDialogAction, + AlertDialogCancel, +} from './components/alert-dialog'; +export { Avatar, AvatarImage, AvatarFallback } from './components/avatar'; +export { Badge, badgeVariants, type BadgeProps } from './components/badge'; +export { + Card, + CardHeader, + CardTitle, + CardDescription, + CardContent, + CardFooter, +} from './components/card'; +export { Checkbox } from './components/checkbox'; +export { + Dialog, + DialogPortal, + DialogOverlay, + DialogTrigger, + DialogClose, + DialogContent, + DialogHeader, + DialogFooter, + DialogTitle, + DialogDescription, +} from './components/dialog'; +export { Input } from './components/input'; +export { Label } from './components/label'; +export { Progress } from './components/progress'; +export { ScrollArea, ScrollBar } from './components/scroll-area'; +export { + Select, + SelectGroup, + SelectValue, + SelectTrigger, + SelectContent, + SelectLabel, + SelectItem, + SelectSeparator, + SelectScrollUpButton, + SelectScrollDownButton, +} from './components/select'; +export { Separator } from './components/separator'; +export { + Sheet, + SheetTrigger, + SheetClose, + SheetContent, + SheetPortal, + SheetOverlay, +} from './components/sheet'; +export { Skeleton } from './components/skeleton'; +export { Switch } from './components/switch'; +export { Tabs, TabsList, TabsTrigger, TabsContent } from './components/tabs'; +export { Toaster, toast, type ToasterProps } from './components/toaster'; +export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from './components/tooltip'; diff --git a/packages/ui/src/lib/cn.ts b/packages/ui/src/lib/cn.ts new file mode 100644 index 00000000..a7c26636 --- /dev/null +++ b/packages/ui/src/lib/cn.ts @@ -0,0 +1,6 @@ +import { clsx, type ClassValue } from 'clsx'; +import { twMerge } from 'tailwind-merge'; + +export function cn(...inputs: ClassValue[]): string { + return twMerge(clsx(inputs)); +} diff --git a/packages/ui/src/styles/theme.css b/packages/ui/src/styles/theme.css new file mode 100644 index 00000000..f3ac6e24 --- /dev/null +++ b/packages/ui/src/styles/theme.css @@ -0,0 +1,140 @@ +/** + * @snowluma/ui — Tailwind 4 theme tokens + * + * Usage in consumers (webui, SnowLumaDesktop): + * @import "tailwindcss"; + * @import "@snowluma/ui/styles/theme.css"; + * + * Tailwind 4 will inline these via `@theme` and pick up classes used in + * `@snowluma/ui` components if the consumer adds: + * @source "../node_modules/@snowluma/ui/dist/**\/*.js"; + */ + +@custom-variant dark (&:where(.dark, .dark *)); + +:root { + --radius: 0.75rem; + + --background: oklch(99% 0.004 240); + --foreground: oklch(20% 0.03 250); + + --card: oklch(100% 0 0); + --card-foreground: oklch(20% 0.03 250); + + --popover: oklch(100% 0 0); + --popover-foreground: oklch(20% 0.03 250); + + /* sky-500 */ + --primary: oklch(68.5% 0.155 230); + --primary-foreground: oklch(99% 0.005 240); + + --secondary: oklch(96% 0.012 240); + --secondary-foreground: oklch(25% 0.03 250); + + --muted: oklch(96% 0.012 240); + --muted-foreground: oklch(50% 0.02 250); + + --accent: oklch(94% 0.03 230); + --accent-foreground: oklch(35% 0.07 230); + + --destructive: oklch(60% 0.22 27); + --destructive-foreground: oklch(99% 0.005 240); + + --success: oklch(70% 0.15 160); + --warning: oklch(78% 0.16 80); + + --border: oklch(92% 0.01 240); + --input: oklch(94% 0.012 240); + --ring: oklch(68.5% 0.155 230); + + --sidebar: oklch(98% 0.006 240); + --sidebar-foreground: oklch(25% 0.03 250); + --sidebar-primary: oklch(68.5% 0.155 230); + --sidebar-primary-foreground: oklch(99% 0.005 240); + --sidebar-accent: oklch(94% 0.025 230); + --sidebar-accent-foreground: oklch(35% 0.08 230); + --sidebar-border: oklch(92% 0.01 240); + --sidebar-ring: oklch(68.5% 0.155 230); +} + +.dark { + --background: oklch(16% 0.02 250); + --foreground: oklch(96% 0.01 240); + + --card: oklch(20% 0.025 250); + --card-foreground: oklch(96% 0.01 240); + + --popover: oklch(20% 0.025 250); + --popover-foreground: oklch(96% 0.01 240); + + --primary: oklch(75% 0.14 230); + --primary-foreground: oklch(15% 0.02 250); + + --secondary: oklch(25% 0.025 250); + --secondary-foreground: oklch(96% 0.01 240); + + --muted: oklch(24% 0.02 250); + --muted-foreground: oklch(68% 0.02 240); + + --accent: oklch(28% 0.05 230); + --accent-foreground: oklch(85% 0.1 230); + + --destructive: oklch(62% 0.2 27); + --destructive-foreground: oklch(98% 0.005 240); + + --success: oklch(72% 0.15 160); + --warning: oklch(80% 0.16 80); + + --border: oklch(28% 0.02 250); + --input: oklch(26% 0.02 250); + --ring: oklch(75% 0.14 230); + + --sidebar: oklch(18% 0.022 250); + --sidebar-foreground: oklch(92% 0.01 240); + --sidebar-primary: oklch(75% 0.14 230); + --sidebar-primary-foreground: oklch(15% 0.02 250); + --sidebar-accent: oklch(28% 0.05 230); + --sidebar-accent-foreground: oklch(85% 0.1 230); + --sidebar-border: oklch(26% 0.02 250); + --sidebar-ring: oklch(75% 0.14 230); +} + +@theme inline { + --color-background: var(--background); + --color-foreground: var(--foreground); + --color-card: var(--card); + --color-card-foreground: var(--card-foreground); + --color-popover: var(--popover); + --color-popover-foreground: var(--popover-foreground); + --color-primary: var(--primary); + --color-primary-foreground: var(--primary-foreground); + --color-secondary: var(--secondary); + --color-secondary-foreground: var(--secondary-foreground); + --color-muted: var(--muted); + --color-muted-foreground: var(--muted-foreground); + --color-accent: var(--accent); + --color-accent-foreground: var(--accent-foreground); + --color-destructive: var(--destructive); + --color-destructive-foreground: var(--destructive-foreground); + --color-success: var(--success); + --color-warning: var(--warning); + --color-border: var(--border); + --color-input: var(--input); + --color-ring: var(--ring); + --color-sidebar: var(--sidebar); + --color-sidebar-foreground: var(--sidebar-foreground); + --color-sidebar-primary: var(--sidebar-primary); + --color-sidebar-primary-foreground: var(--sidebar-primary-foreground); + --color-sidebar-accent: var(--sidebar-accent); + --color-sidebar-accent-foreground: var(--sidebar-accent-foreground); + --color-sidebar-border: var(--sidebar-border); + --color-sidebar-ring: var(--sidebar-ring); + + --radius-sm: calc(var(--radius) - 4px); + --radius-md: calc(var(--radius) - 2px); + --radius-lg: var(--radius); + --radius-xl: calc(var(--radius) + 4px); + + --font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif; + --font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace; +} diff --git a/packages/ui/tsconfig.json b/packages/ui/tsconfig.json new file mode 100644 index 00000000..8b69c957 --- /dev/null +++ b/packages/ui/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { + "outDir": "./dist", + "rootDir": "./src", + "declaration": true, + "declarationMap": true, + "sourceMap": true, + "jsx": "react-jsx", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "types": ["react", "react-dom"], + "ignoreDeprecations": "6.0" + }, + "include": ["src/**/*"], + "exclude": ["node_modules", "dist"] +} diff --git a/packages/ui/tsup.config.ts b/packages/ui/tsup.config.ts new file mode 100644 index 00000000..4908bb7e --- /dev/null +++ b/packages/ui/tsup.config.ts @@ -0,0 +1,12 @@ +import { defineConfig } from 'tsup'; + +export default defineConfig({ + entry: ['src/index.ts'], + format: ['esm'], + dts: true, + sourcemap: true, + clean: true, + external: ['react', 'react-dom'], + target: 'es2022', + treeshake: true, +}); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b648d291..7275beaa 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -38,7 +38,7 @@ importers: version: 1.19.14(hono@4.12.14) '@rollup/plugin-node-resolve': specifier: ^16.0.3 - version: 16.0.3 + version: 16.0.3(rollup@4.60.4) '@types/node': specifier: ^24.12.2 version: 24.12.2 @@ -78,6 +78,76 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(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/ui: + dependencies: + '@radix-ui/react-alert-dialog': + specifier: ^1.1.7 + version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-checkbox': + specifier: ^1.1.5 + version: 1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-dialog': + specifier: ^1.1.7 + version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-label': + specifier: ^2.1.3 + version: 2.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-scroll-area': + specifier: ^1.2.4 + version: 1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-select': + specifier: ^2.2.6 + version: 2.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-separator': + specifier: ^1.1.3 + version: 1.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': + specifier: ^1.1.3 + version: 1.2.4(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-switch': + specifier: ^1.2.6 + version: 1.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-tabs': + specifier: ^1.1.13 + version: 1.1.13(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-tooltip': + specifier: ^1.1.9 + version: 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + class-variance-authority: + specifier: ^0.7.1 + version: 0.7.1 + clsx: + specifier: ^2.1.1 + version: 2.1.1 + lucide-react: + specifier: ^0.469.0 + version: 0.469.0(react@19.2.5) + sonner: + specifier: ^2.0.6 + version: 2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + tailwind-merge: + specifier: ^3.5.0 + version: 3.5.0 + devDependencies: + '@types/react': + specifier: ^19.2.14 + version: 19.2.14 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.2.3(@types/react@19.2.14) + react: + specifier: ^19.2.5 + version: 19.2.5 + react-dom: + specifier: ^19.2.5 + version: 19.2.5(react@19.2.5) + tsup: + specifier: ^8.5.0 + version: 8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2) + typescript: + specifier: 'catalog:' + version: 6.0.2 + packages/websocket: devDependencies: '@types/node': @@ -639,6 +709,32 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-checkbox@1.3.3': + resolution: {integrity: sha512-wBbpv+NQftHDdG86Qc0pIyXk5IR3tM8Vd0nWLKDcX8nNn4nXFOFwsKuqw2okA/1D/mpaAkmuyndrPJTYDNZtFw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-collection@1.1.7': + resolution: {integrity: sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-compose-refs@1.1.2': resolution: {integrity: sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg==} peerDependencies: @@ -801,6 +897,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-roving-focus@1.1.11': + resolution: {integrity: sha512-7A6S9jSgm/S+7MdtNDSb+IU859vQqJ/QAtcYQcfFC6W8RS4IxIZDldLR0xqCFZ6DCyrQLjLPsxtTNch5jVA4lA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-scroll-area@1.2.10': resolution: {integrity: sha512-tAXIa1g3sM5CGpVT0uIbUx/U3Gs5N8T52IICuCtObaos1S8fzsrPXG5WObkQN3S6NVl6wKgPhAIiBGbWnvc97A==} peerDependencies: @@ -814,6 +923,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-select@2.2.6': + resolution: {integrity: sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-separator@1.1.8': resolution: {integrity: sha512-sDvqVY4itsKwwSMEe0jtKgfTh+72Sy3gPmQpjqcQneqQ4PFmr/1I0YA+2/puilhggCe2gJcx5EBAYFkWkdpa5g==} peerDependencies: @@ -845,6 +967,32 @@ packages: '@types/react': optional: true + '@radix-ui/react-switch@1.2.6': + resolution: {integrity: sha512-bByzr1+ep1zk4VubeEVViV592vu2lHE2BZY5OnzehZqOOgogN80+mNtCqPkhn2gklJqOpxWgPoYTSnhBCqpOXQ==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + + '@radix-ui/react-tabs@1.1.13': + resolution: {integrity: sha512-7xdcatg7/U+7+Udyoj2zodtI9H/IIopqo+YOIcZOq1nJwXWBZ9p8xiu5llXlekDbZkca79a/fozEYQXIA4sW6A==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-tooltip@1.2.8': resolution: {integrity: sha512-tY7sVt1yL9ozIxvmbtN5qtmH2krXcBCfjEiCgKGLqunJHvgvZG2Pcl2oQ3kbcZARb1BGEHdkLzcYGO8ynVlieg==} peerDependencies: @@ -903,6 +1051,15 @@ packages: '@types/react': optional: true + '@radix-ui/react-use-previous@1.1.1': + resolution: {integrity: sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ==} + peerDependencies: + '@types/react': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@radix-ui/react-use-rect@1.1.1': resolution: {integrity: sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w==} peerDependencies: @@ -1056,6 +1213,144 @@ packages: rollup: optional: true + '@rollup/rollup-android-arm-eabi@4.60.4': + resolution: {integrity: sha512-F5QXMSiFebS9hKZj02XhWLLnRpJ3B3AROP0tWbFBSj+6kCbg5m9j5JoHKd4mmSVy5mS/IMQloYgYxCuJC0fxEQ==} + cpu: [arm] + os: [android] + + '@rollup/rollup-android-arm64@4.60.4': + resolution: {integrity: sha512-GxxTKApUpzRhof7poWvCJHRF51C67u1R7D6DiluBE8wKU1u5GWE8t+v81JvJYtbawoBFX1hLv5Ei4eVjkWokaw==} + cpu: [arm64] + os: [android] + + '@rollup/rollup-darwin-arm64@4.60.4': + resolution: {integrity: sha512-tua0TaJxMOB1R0V0RS1jFZ/RpURFDJIOR2A6jWwQeawuFyS4gBW+rntLRaQd0EQ4bd6Vp44Z2rXW+YYDBsj6IA==} + cpu: [arm64] + os: [darwin] + + '@rollup/rollup-darwin-x64@4.60.4': + resolution: {integrity: sha512-CSKq7MsP+5PFIcydhAiR1K0UhEI1A2jWXVKHPCBZ151yOutENwvnPocgVHkivu2kviURtCEB6zUQw0vs8RrhMg==} + cpu: [x64] + os: [darwin] + + '@rollup/rollup-freebsd-arm64@4.60.4': + resolution: {integrity: sha512-+O8OkVdyvXMtJEciu2wS/pzm1IxntEEQx3z5TAVy4l32G0etZn+RsA48ARRrFm6Ri8fvqPQfgrvNxSjKAbnd3g==} + cpu: [arm64] + os: [freebsd] + + '@rollup/rollup-freebsd-x64@4.60.4': + resolution: {integrity: sha512-Iw3oMskH3AfNuhU0MSN7vNbdi4me/NiYo2azqPz/Le16zHSa+3RRmliCMWWQmh4lcndccU40xcJuTYJZxNo/lw==} + cpu: [x64] + os: [freebsd] + + '@rollup/rollup-linux-arm-gnueabihf@4.60.4': + resolution: {integrity: sha512-EIPRXTVQpHyF8WOo219AD2yEltPehLTcTMz2fn6JsatLYSzQf00hj3rulF+yauOlF9/FtM2WpkT/hJh/KJFGhA==} + cpu: [arm] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm-musleabihf@4.60.4': + resolution: {integrity: sha512-J3Yh9PzzF1Ovah2At+lHiGQdsYgArxBbXv/zHfSyaiFQEqvNv7DcW98pCrmdjCZBrqBiKrKKe2V+aaSGWuBe/w==} + cpu: [arm] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-arm64-gnu@4.60.4': + resolution: {integrity: sha512-BFDEZMYfUvLn37ONE1yMBojPxnMlTFsdyNoqncT0qFq1mAfllL+ATMMJd8TeuVMiX84s1KbcxcZbXInmcO2mRg==} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-arm64-musl@4.60.4': + resolution: {integrity: sha512-pc9EYOSlOgdQ2uPl1o9PF6/kLSgaUosia7gOuS8mB69IxJvlclko1MECXysjs5ryez1/5zjYqx3+xYU0TU6R1A==} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-loong64-gnu@4.60.4': + resolution: {integrity: sha512-NxnomyxYerDh5n4iLrNa+sH+Z+U4BMEE46V2PgQ/hoB909i8gV1M5wPojWg9fk1jWpO3IQnOs20K4wyZuFLEFQ==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-loong64-musl@4.60.4': + resolution: {integrity: sha512-nbJnQ8a3z1mtmrwImCYhc6BGpThAyYVRQxw9uKSKG4wR6aAYno9sVjJ0zaZcW9BPJX1GbrDPf+SvdWjgTuDmnw==} + cpu: [loong64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-ppc64-gnu@4.60.4': + resolution: {integrity: sha512-2EU6acNrQLd8tYvo/LXW535wupT3m6fo7HKo6lr7ktQoItxTyOL1ZCR/GfGCuXl2vR+zmfI6eRXkSemafv+iVg==} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-ppc64-musl@4.60.4': + resolution: {integrity: sha512-WeBtoMuaMxiiIrO2IYP3xs6GMWkJP2C0EoT8beTLkUPmzV1i/UcOSVw1d5r9KBODtHKilG5yFxsGRnBbK3wJ4A==} + cpu: [ppc64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-riscv64-gnu@4.60.4': + resolution: {integrity: sha512-FJHFfqpKUI3A10WrWKiFbBZ7yVbGT4q4B5o1qKFFojqpaYoh9LrQgqWCmmcxQzVSXYtyB5bzkXrYzlHTs21MYA==} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-riscv64-musl@4.60.4': + resolution: {integrity: sha512-mcEl6CUT5IAUmQf1m9FYSmVqCJlpQ8r8eyftFUHG8i9OhY7BkBXSUdnLH5DOf0wCOjcP9v/QO93zpmF1SptCCw==} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@rollup/rollup-linux-s390x-gnu@4.60.4': + resolution: {integrity: sha512-ynt3JxVd2w2buzoKDWIyiV1pJW93xlQic1THVLXilz429oijRpSHivZAgp65KBu+cMcgf1eVVjdnTLvPxgCuoQ==} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-gnu@4.60.4': + resolution: {integrity: sha512-Boiz5+MsaROEWDf+GGEwF8VMHGhlUoQMtIPjOgA5fv4osupqTVnJteQNKJwUcnUog2G55jYXH7KZFFiJe0TEzQ==} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rollup/rollup-linux-x64-musl@4.60.4': + resolution: {integrity: sha512-+qfSY27qIrFfI/Hom04KYFw3GKZSGU4lXus51wsb5EuySfFlWRwjkKWoE9emgRw/ukoT4Udsj4W/+xxG8VbPKg==} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rollup/rollup-openbsd-x64@4.60.4': + resolution: {integrity: sha512-VpTfOPHgVXEBeeR8hZ2O0F3aSso+JDWqTWmTmzcQKted54IAdUVbxE+j/MVxUsKa8L20HJhv3vUezVPoquqWjA==} + cpu: [x64] + os: [openbsd] + + '@rollup/rollup-openharmony-arm64@4.60.4': + resolution: {integrity: sha512-IPOsh5aRYuLv/nkU51X10Bf75Bsf6+gZdx1X+QP5QM6lIJFHHqbHLG0uJn/hWthzo13UAc2umiUorqZy3axoZg==} + cpu: [arm64] + os: [openharmony] + + '@rollup/rollup-win32-arm64-msvc@4.60.4': + resolution: {integrity: sha512-4QzE9E81OohJ/HKzHhsqU+zcYYojVOXlFMs1DdyMT6qXl/niOH7AVElmmEdUNHHS/oRkc++d5k6Vy85zFs0DEw==} + cpu: [arm64] + os: [win32] + + '@rollup/rollup-win32-ia32-msvc@4.60.4': + resolution: {integrity: sha512-zTPgT1YuHHcd+Tmx7h8aml0FWFVelV5N54oHow9SLj+GfoDy/huQ+UV396N/C7KpMDMiPspRktzM1/0r1usYEA==} + cpu: [ia32] + os: [win32] + + '@rollup/rollup-win32-x64-gnu@4.60.4': + resolution: {integrity: sha512-DRS4G7mi9lJxqEDezIkKCaUIKCrLUUDCUaCsTPCi/rtqaC6D/jjwslMQyiDU50Ka0JKpeXeRBFBAXwArY52vBw==} + cpu: [x64] + os: [win32] + + '@rollup/rollup-win32-x64-msvc@4.60.4': + resolution: {integrity: sha512-QVTUovf40zgTqlFVrKA1uXMVvU2QWEFWfAH8Wdc48IxLvrJMQVMBRjuQyUpzZCDkakImib9eVazbWlC6ksWtJw==} + cpu: [x64] + os: [win32] + '@standard-schema/spec@1.1.0': resolution: {integrity: sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==} @@ -1338,6 +1633,9 @@ packages: ajv@6.14.0: resolution: {integrity: sha512-IWrosm/yrn43eiKqkfkHis7QioDleaXQHdDVPKg0FSwwd/DuvyX79TZnFOnYpB7dcsFAMmtFztZuXPDvSePkFw==} + any-promise@1.3.0: + resolution: {integrity: sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A==} + aria-hidden@1.2.6: resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} engines: {node: '>=10'} @@ -1373,6 +1671,16 @@ packages: engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} hasBin: true + bundle-require@5.1.0: + resolution: {integrity: sha512-3WrrOuZiyaaZPWiEt4G3+IffISVC9HYlWueJEBWED4ZH4aIAC2PnkdnuRrR94M+w6yGWn4AglWtJtBI8YqvgoA==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + peerDependencies: + esbuild: '>=0.18' + + cac@6.7.14: + resolution: {integrity: sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==} + engines: {node: '>=8'} + caniuse-lite@1.0.30001788: resolution: {integrity: sha512-6q8HFp+lOQtcf7wBK+uEenxymVWkGKkjFpCvw5W25cmMwEDU45p1xQFBQv8JDlMMry7eNxyBaR+qxgmTUZkIRQ==} @@ -1395,6 +1703,17 @@ packages: resolution: {integrity: sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw==} engines: {node: '>=20'} + commander@4.1.1: + resolution: {integrity: sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==} + engines: {node: '>= 6'} + + confbox@0.1.8: + resolution: {integrity: sha512-RMtmw0iFkeR4YV+fUOSucriAQNb9g8zFR52MWCtl+cCZOFRNL6zeB395vPzFhEjjn4fMxXudmELnl/KF/WrK6w==} + + consola@3.4.2: + resolution: {integrity: sha512-5IKcdX0nnYavi6G7TtOhwkYzyjfJlatbjMjuLSfE2kYT5pMDOilZ4OvMhi637CcDICTmz3wARPoyhqyX1Y+XvA==} + engines: {node: ^14.18.0 || >=16.10.0} + convert-source-map@2.0.0: resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==} @@ -1560,6 +1879,9 @@ packages: resolution: {integrity: sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==} engines: {node: '>=10'} + fix-dts-default-cjs-exports@1.0.1: + resolution: {integrity: sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg==} + flat-cache@4.0.1: resolution: {integrity: sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==} engines: {node: '>=16'} @@ -1673,6 +1995,10 @@ packages: resolution: {integrity: sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==} hasBin: true + joycon@3.1.1: + resolution: {integrity: sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==} + engines: {node: '>=10'} + js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} @@ -1779,6 +2105,17 @@ packages: resolution: {integrity: sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==} engines: {node: '>= 12.0.0'} + lilconfig@3.1.3: + resolution: {integrity: sha512-/vlFKAoH5Cgt3Ie+JLhRbwOsCQePABiU3tJ1egGvyQ+33R/vcwM2Zl2QR/LzjsBeItPt3oSVXapn+m4nQDvpzw==} + engines: {node: '>=14'} + + lines-and-columns@1.2.4: + resolution: {integrity: sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg==} + + load-tsconfig@0.2.5: + resolution: {integrity: sha512-IXO6OCs9yg8tMKzfPZ1YmheJbZCiEsnBdcB03l0OcfK9prKnJb96siuHCr5Fl37/yo9DnKU+TLpxzTUspw9shg==} + engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} + locate-path@6.0.0: resolution: {integrity: sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==} engines: {node: '>=10'} @@ -1798,6 +2135,9 @@ packages: resolution: {integrity: sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==} engines: {node: 18 || 20 || >=22} + mlly@1.8.2: + resolution: {integrity: sha512-d+ObxMQFmbt10sretNDytwt85VrbkhhUA/JBGm1MPaWJ65Cl4wOgLaB1NYvJSZ0Ef03MMEU/0xpPMXUIQ29UfA==} + motion-dom@12.38.0: resolution: {integrity: sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA==} @@ -1821,6 +2161,9 @@ packages: ms@2.1.3: resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==} + mz@2.7.0: + resolution: {integrity: sha512-z81GNO7nnYMEhrGh9LeymoE4+Yr0Wn5McHIZMK5cfQCl+NDX08sCZgUc9/6MHni9IWuFLm1Z3HTCXu2z9fN62Q==} + nanoid@3.3.11: resolution: {integrity: sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==} engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} @@ -1835,6 +2178,10 @@ packages: node-releases@2.0.37: resolution: {integrity: sha512-1h5gKZCF+pO/o3Iqt5Jp7wc9rH3eJJ0+nh/CIoiRwjRxde/hAHyLPXYN4V3CqKAbiZPSeJFSWHmJsbkicta0Eg==} + object-assign@4.1.1: + resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==} + engines: {node: '>=0.10.0'} + obug@2.1.1: resolution: {integrity: sha512-uTqF9MuPraAQ+IsnPf366RG4cP9RtUi7MLO1N3KEc+wb0a6yKpeL0lmk2IB1jY5KHPAlTc6T/JRdC/YqxHNwkQ==} @@ -1871,6 +2218,31 @@ packages: resolution: {integrity: sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==} engines: {node: '>=12'} + pirates@4.0.7: + resolution: {integrity: sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==} + engines: {node: '>= 6'} + + pkg-types@1.3.1: + resolution: {integrity: sha512-/Jm5M4RvtBFVkKWRu2BLUTNP8/M2a+UwuAX+ae4770q1qVGtfjG+WTCupoZixokjmHiry8uI+dlY8KXYV5HVVQ==} + + postcss-load-config@6.0.1: + resolution: {integrity: sha512-oPtTM4oerL+UXmx+93ytZVN82RrlY/wPUV8IeDxFrzIjXOLF1pN+EmKPLbubvKHT2HC20xXsCAH2Z+CKV6Oz/g==} + engines: {node: '>= 18'} + peerDependencies: + jiti: '>=1.21.0' + postcss: '>=8.0.9' + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + jiti: + optional: true + postcss: + optional: true + tsx: + optional: true + yaml: + optional: true + postcss@8.5.10: resolution: {integrity: sha512-pMMHxBOZKFU6HgAZ4eyGnwXF/EvPGGqUr0MnZ5+99485wwW41kW91A4LOGxSHhgugZmSChL5AlElNdwlNgcnLQ==} engines: {node: ^10 || ^12 || >=14} @@ -1926,6 +2298,10 @@ packages: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} + resolve-from@5.0.0: + resolution: {integrity: sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw==} + engines: {node: '>=8'} + resolve-pkg-maps@1.0.0: resolution: {integrity: sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==} @@ -1939,6 +2315,11 @@ packages: engines: {node: ^20.19.0 || >=22.12.0} hasBin: true + rollup@4.60.4: + resolution: {integrity: sha512-WHeFSbZYsPu3+bLoNRUuAO+wavNlocOPf3wSHTP7hcFKVnJeWsYlCDbr3mTS14FCizf9ccIxXA8sGL8zKeQN3g==} + engines: {node: '>=18.0.0', npm: '>=8.0.0'} + hasBin: true + sass@1.99.0: resolution: {integrity: sha512-kgW13M54DUB7IsIRM5LvJkNlpH+WhMpooUcaWGFARkF1Tc82v9mIWkCbCYf+MBvpIUBSeSOTilpZjEPr2VYE6Q==} engines: {node: '>=14.0.0'} @@ -1977,16 +2358,31 @@ packages: siginfo@2.0.0: resolution: {integrity: sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==} + sonner@2.0.7: + resolution: {integrity: sha512-W6ZN4p58k8aDKA4XPcx2hpIQXBRAgyiWVkYhT7CvK6D3iAu7xjvVyhQHg2/iaKJZ1XVJ4r7XuwGL+WGEK37i9w==} + peerDependencies: + react: ^18.0.0 || ^19.0.0 || ^19.0.0-rc + react-dom: ^18.0.0 || ^19.0.0 || ^19.0.0-rc + source-map-js@1.2.1: resolution: {integrity: sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==} engines: {node: '>=0.10.0'} + source-map@0.7.6: + resolution: {integrity: sha512-i5uvt8C3ikiWeNZSVZNWcfZPItFQOsYTUAOkcUPGd8DqDy1uOUikjt5dG+uRlwyvR108Fb9DOd4GvXfT0N2/uQ==} + engines: {node: '>= 12'} + stackback@0.0.2: resolution: {integrity: sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==} std-env@4.1.0: resolution: {integrity: sha512-Rq7ybcX2RuC55r9oaPVEW7/xu3tj8u4GeBYHBWCychFtzMIr86A7e3PPEBPT37sHStKX3+TiX/Fr/ACmJLVlLQ==} + sucrase@3.35.1: + resolution: {integrity: sha512-DhuTmvZWux4H1UOnWMB3sk0sbaCVOoQZjv8u1rDoTV0HTdGem9hkAZtl4JZy8P2z4Bg0nT+YMeOFyVr4zcG5Tw==} + engines: {node: '>=16 || 14 >=14.17'} + hasBin: true + supports-preserve-symlinks-flag@1.0.0: resolution: {integrity: sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==} engines: {node: '>= 0.4'} @@ -2001,9 +2397,19 @@ packages: resolution: {integrity: sha512-1MOpMXuhGzGL5TTCZFItxCc0AARf1EZFQkGqMm7ERKj8+Hgr5oLvJOVFcC+lRmR8hCe2S3jC4T5D7Vg/d7/fhA==} engines: {node: '>=6'} + thenify-all@1.6.0: + resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} + engines: {node: '>=0.8'} + + thenify@3.3.1: + resolution: {integrity: sha512-RVZSIV5IG10Hk3enotrhvz0T9em6cyHBLkH/YAZuKqd8hRkKhSfCGIcP2KUY0EPxndzANBmNllzWPwak+bheSw==} + tinybench@2.9.0: resolution: {integrity: sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==} + tinyexec@0.3.2: + resolution: {integrity: sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==} + tinyexec@1.1.1: resolution: {integrity: sha512-VKS/ZaQhhkKFMANmAOhhXVoIfBXblQxGX1myCQ2faQrfmobMftXeJPcZGp0gS07ocvGJWDLZGyOZDadDBqYIJg==} engines: {node: '>=18'} @@ -2016,15 +2422,41 @@ packages: resolution: {integrity: sha512-Bf+ILmBgretUrdJxzXM0SgXLZ3XfiaUuOj/IKQHuTXip+05Xn+uyEYdVg0kYDipTBcLrCVyUzAPz7QmArb0mmw==} engines: {node: '>=14.0.0'} + tree-kill@1.2.2: + resolution: {integrity: sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==} + hasBin: true + ts-api-utils@2.5.0: resolution: {integrity: sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==} engines: {node: '>=18.12'} peerDependencies: typescript: '>=4.8.4' + ts-interface-checker@0.1.13: + resolution: {integrity: sha512-Y/arvbn+rrz3JCKl9C4kVNfTfSm2/mEp5FSz5EsZSANGPSlQrpRI5M4PKF+mJnE52jOO90PnPSc3Ur3bTQw0gA==} + tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + tsup@8.5.1: + resolution: {integrity: sha512-xtgkqwdhpKWr3tKPmCkvYmS9xnQK3m3XgxZHwSUjvfTjp7YfXe5tT3GgWi0F2N+ZSMsOeWeZFh7ZZFg5iPhing==} + engines: {node: '>=18'} + hasBin: true + peerDependencies: + '@microsoft/api-extractor': ^7.36.0 + '@swc/core': ^1 + postcss: ^8.4.12 + typescript: '>=4.5.0' + peerDependenciesMeta: + '@microsoft/api-extractor': + optional: true + '@swc/core': + optional: true + postcss: + optional: true + typescript: + optional: true + tsx@4.21.0: resolution: {integrity: sha512-5C1sg4USs1lfG0GFb2RLXsdpXqBSEhAaA/0kPL01wxzpMqLILNxIxIOKiILz+cdg/pLnOUxFYOR5yhHU666wbw==} engines: {node: '>=18.0.0'} @@ -2049,6 +2481,9 @@ packages: engines: {node: '>=14.17'} hasBin: true + ufo@1.6.4: + resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} + undici-types@7.16.0: resolution: {integrity: sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==} @@ -2595,6 +3030,34 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-checkbox@1.3.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + + '@radix-ui/react-collection@1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-compose-refs@1.1.2(@types/react@19.2.14)(react@19.2.5)': dependencies: react: 19.2.5 @@ -2737,6 +3200,23 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-roving-focus@1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-scroll-area@1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@radix-ui/number': 1.1.1 @@ -2754,6 +3234,35 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-select@2.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/number': 1.1.1 + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-collection': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-callback-ref': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-layout-effect': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-visually-hidden': 1.2.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + aria-hidden: 1.2.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-separator@1.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@radix-ui/react-primitive': 2.1.4(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) @@ -2777,6 +3286,37 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 + '@radix-ui/react-switch@1.2.6(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-previous': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-size': 1.1.1(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + + '@radix-ui/react-tabs@1.1.13(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-direction': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-roving-focus': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-tooltip@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@radix-ui/primitive': 1.1.3 @@ -2831,6 +3371,12 @@ snapshots: optionalDependencies: '@types/react': 19.2.14 + '@radix-ui/react-use-previous@1.1.1(@types/react@19.2.14)(react@19.2.5)': + dependencies: + react: 19.2.5 + optionalDependencies: + '@types/react': 19.2.14 + '@radix-ui/react-use-rect@1.1.1(@types/react@19.2.14)(react@19.2.5)': dependencies: '@radix-ui/rect': 1.1.1 @@ -2909,19 +3455,98 @@ snapshots: '@rolldown/pluginutils@1.0.0-rc.7': {} - '@rollup/plugin-node-resolve@16.0.3': + '@rollup/plugin-node-resolve@16.0.3(rollup@4.60.4)': dependencies: - '@rollup/pluginutils': 5.3.0 + '@rollup/pluginutils': 5.3.0(rollup@4.60.4) '@types/resolve': 1.20.2 deepmerge: 4.3.1 is-module: 1.0.0 resolve: 1.22.12 + optionalDependencies: + rollup: 4.60.4 - '@rollup/pluginutils@5.3.0': + '@rollup/pluginutils@5.3.0(rollup@4.60.4)': dependencies: '@types/estree': 1.0.8 estree-walker: 2.0.2 picomatch: 4.0.4 + optionalDependencies: + rollup: 4.60.4 + + '@rollup/rollup-android-arm-eabi@4.60.4': + optional: true + + '@rollup/rollup-android-arm64@4.60.4': + optional: true + + '@rollup/rollup-darwin-arm64@4.60.4': + optional: true + + '@rollup/rollup-darwin-x64@4.60.4': + optional: true + + '@rollup/rollup-freebsd-arm64@4.60.4': + optional: true + + '@rollup/rollup-freebsd-x64@4.60.4': + optional: true + + '@rollup/rollup-linux-arm-gnueabihf@4.60.4': + optional: true + + '@rollup/rollup-linux-arm-musleabihf@4.60.4': + optional: true + + '@rollup/rollup-linux-arm64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-arm64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-loong64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-loong64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-ppc64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-ppc64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-riscv64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-riscv64-musl@4.60.4': + optional: true + + '@rollup/rollup-linux-s390x-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-x64-gnu@4.60.4': + optional: true + + '@rollup/rollup-linux-x64-musl@4.60.4': + optional: true + + '@rollup/rollup-openbsd-x64@4.60.4': + optional: true + + '@rollup/rollup-openharmony-arm64@4.60.4': + optional: true + + '@rollup/rollup-win32-arm64-msvc@4.60.4': + optional: true + + '@rollup/rollup-win32-ia32-msvc@4.60.4': + optional: true + + '@rollup/rollup-win32-x64-gnu@4.60.4': + optional: true + + '@rollup/rollup-win32-x64-msvc@4.60.4': + optional: true '@standard-schema/spec@1.1.0': {} @@ -3221,6 +3846,8 @@ snapshots: json-schema-traverse: 0.4.1 uri-js: 4.4.1 + any-promise@1.3.0: {} + aria-hidden@1.2.6: dependencies: tslib: 2.8.1 @@ -3263,6 +3890,13 @@ snapshots: node-releases: 2.0.37 update-browserslist-db: 1.2.3(browserslist@4.28.2) + bundle-require@5.1.0(esbuild@0.27.7): + dependencies: + esbuild: 0.27.7 + load-tsconfig: 0.2.5 + + cac@6.7.14: {} + caniuse-lite@1.0.30001788: {} chai@6.2.2: {} @@ -3270,7 +3904,6 @@ snapshots: chokidar@4.0.3: dependencies: readdirp: 4.1.2 - optional: true class-variance-authority@0.7.1: dependencies: @@ -3280,6 +3913,12 @@ snapshots: commander@14.0.3: {} + commander@4.1.1: {} + + confbox@0.1.8: {} + + consola@3.4.2: {} + convert-source-map@2.0.0: {} cookie-es@3.1.1: {} @@ -3467,6 +4106,12 @@ snapshots: locate-path: 6.0.0 path-exists: 4.0.0 + fix-dts-default-cjs-exports@1.0.1: + dependencies: + magic-string: 0.30.21 + mlly: 1.8.2 + rollup: 4.60.4 + flat-cache@4.0.1: dependencies: flatted: 3.4.2 @@ -3551,6 +4196,8 @@ snapshots: jiti@2.6.1: {} + joycon@3.1.1: {} + js-tokens@4.0.0: {} jsesc@3.1.0: {} @@ -3627,6 +4274,12 @@ snapshots: lightningcss-win32-arm64-msvc: 1.32.0 lightningcss-win32-x64-msvc: 1.32.0 + lilconfig@3.1.3: {} + + lines-and-columns@1.2.4: {} + + load-tsconfig@0.2.5: {} + locate-path@6.0.0: dependencies: p-locate: 5.0.0 @@ -3647,6 +4300,13 @@ snapshots: dependencies: brace-expansion: 5.0.5 + mlly@1.8.2: + dependencies: + acorn: 8.16.0 + pathe: 2.0.3 + pkg-types: 1.3.1 + ufo: 1.6.4 + motion-dom@12.38.0: dependencies: motion-utils: 12.36.0 @@ -3663,6 +4323,12 @@ snapshots: ms@2.1.3: {} + mz@2.7.0: + dependencies: + any-promise: 1.3.0 + object-assign: 4.1.1 + thenify-all: 1.6.0 + nanoid@3.3.11: {} natural-compare@1.4.0: {} @@ -3672,6 +4338,8 @@ snapshots: node-releases@2.0.37: {} + object-assign@4.1.1: {} + obug@2.1.1: {} optionator@0.9.4: @@ -3703,6 +4371,22 @@ snapshots: picomatch@4.0.4: {} + pirates@4.0.7: {} + + pkg-types@1.3.1: + dependencies: + confbox: 0.1.8 + mlly: 1.8.2 + pathe: 2.0.3 + + postcss-load-config@6.0.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0): + dependencies: + lilconfig: 3.1.3 + optionalDependencies: + jiti: 2.6.1 + postcss: 8.5.10 + tsx: 4.21.0 + postcss@8.5.10: dependencies: nanoid: 3.3.11 @@ -3747,8 +4431,9 @@ snapshots: react@19.2.5: {} - readdirp@4.1.2: - optional: true + readdirp@4.1.2: {} + + resolve-from@5.0.0: {} resolve-pkg-maps@1.0.0: {} @@ -3780,6 +4465,37 @@ snapshots: '@rolldown/binding-win32-arm64-msvc': 1.0.0-rc.15 '@rolldown/binding-win32-x64-msvc': 1.0.0-rc.15 + rollup@4.60.4: + dependencies: + '@types/estree': 1.0.8 + optionalDependencies: + '@rollup/rollup-android-arm-eabi': 4.60.4 + '@rollup/rollup-android-arm64': 4.60.4 + '@rollup/rollup-darwin-arm64': 4.60.4 + '@rollup/rollup-darwin-x64': 4.60.4 + '@rollup/rollup-freebsd-arm64': 4.60.4 + '@rollup/rollup-freebsd-x64': 4.60.4 + '@rollup/rollup-linux-arm-gnueabihf': 4.60.4 + '@rollup/rollup-linux-arm-musleabihf': 4.60.4 + '@rollup/rollup-linux-arm64-gnu': 4.60.4 + '@rollup/rollup-linux-arm64-musl': 4.60.4 + '@rollup/rollup-linux-loong64-gnu': 4.60.4 + '@rollup/rollup-linux-loong64-musl': 4.60.4 + '@rollup/rollup-linux-ppc64-gnu': 4.60.4 + '@rollup/rollup-linux-ppc64-musl': 4.60.4 + '@rollup/rollup-linux-riscv64-gnu': 4.60.4 + '@rollup/rollup-linux-riscv64-musl': 4.60.4 + '@rollup/rollup-linux-s390x-gnu': 4.60.4 + '@rollup/rollup-linux-x64-gnu': 4.60.4 + '@rollup/rollup-linux-x64-musl': 4.60.4 + '@rollup/rollup-openbsd-x64': 4.60.4 + '@rollup/rollup-openharmony-arm64': 4.60.4 + '@rollup/rollup-win32-arm64-msvc': 4.60.4 + '@rollup/rollup-win32-ia32-msvc': 4.60.4 + '@rollup/rollup-win32-x64-gnu': 4.60.4 + '@rollup/rollup-win32-x64-msvc': 4.60.4 + fsevents: 2.3.3 + sass@1.99.0: dependencies: chokidar: 4.0.3 @@ -3809,12 +4525,29 @@ snapshots: siginfo@2.0.0: {} + sonner@2.0.7(react-dom@19.2.5(react@19.2.5))(react@19.2.5): + dependencies: + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + source-map-js@1.2.1: {} + source-map@0.7.6: {} + stackback@0.0.2: {} std-env@4.1.0: {} + sucrase@3.35.1: + dependencies: + '@jridgewell/gen-mapping': 0.3.13 + commander: 4.1.1 + lines-and-columns: 1.2.4 + mz: 2.7.0 + pirates: 4.0.7 + tinyglobby: 0.2.16 + ts-interface-checker: 0.1.13 + supports-preserve-symlinks-flag@1.0.0: {} tailwind-merge@3.5.0: {} @@ -3823,8 +4556,18 @@ snapshots: tapable@2.3.2: {} + thenify-all@1.6.0: + dependencies: + thenify: 3.3.1 + + thenify@3.3.1: + dependencies: + any-promise: 1.3.0 + tinybench@2.9.0: {} + tinyexec@0.3.2: {} + tinyexec@1.1.1: {} tinyglobby@0.2.16: @@ -3834,12 +4577,44 @@ snapshots: tinyrainbow@3.1.0: {} + tree-kill@1.2.2: {} + ts-api-utils@2.5.0(typescript@6.0.2): dependencies: typescript: 6.0.2 + ts-interface-checker@0.1.13: {} + tslib@2.8.1: {} + tsup@8.5.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0)(typescript@6.0.2): + dependencies: + bundle-require: 5.1.0(esbuild@0.27.7) + cac: 6.7.14 + chokidar: 4.0.3 + consola: 3.4.2 + debug: 4.4.3 + esbuild: 0.27.7 + fix-dts-default-cjs-exports: 1.0.1 + joycon: 3.1.1 + picocolors: 1.1.1 + postcss-load-config: 6.0.1(jiti@2.6.1)(postcss@8.5.10)(tsx@4.21.0) + resolve-from: 5.0.0 + rollup: 4.60.4 + source-map: 0.7.6 + sucrase: 3.35.1 + tinyexec: 0.3.2 + tinyglobby: 0.2.16 + tree-kill: 1.2.2 + optionalDependencies: + postcss: 8.5.10 + typescript: 6.0.2 + transitivePeerDependencies: + - jiti + - supports-color + - tsx + - yaml + tsx@4.21.0: dependencies: esbuild: 0.27.7 @@ -3866,6 +4641,8 @@ snapshots: typescript@6.0.2: {} + ufo@1.6.4: {} + undici-types@7.16.0: {} undici-types@7.19.2: {} From bc9f7b49bee0bc3d412fe055812bff52f133c2a9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 00:23:55 +0800 Subject: [PATCH 12/51] feat(core): support env-var overrides for webui port and bootstrap password MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two additions for trusted local launchers (notably SnowLumaDesktop) to configure core without writing to disk-shared config: - SNOWLUMA_WEBUI_PORT overrides runtime.json's webuiPort at startup without persisting; CLI/Docker users continue to drive it from the file. Mirrors the existing SNOWLUMA_HOOK_RUNTIME_DIR / *_TRUST_PROXY conventions. - SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD seeds the initial WebUI password on first launch (when webui.json doesn't yet exist), with mustChangePassword=false. After the file is persisted the env var is ignored — password rotation continues through the UI. --- packages/core/src/common/runtime.ts | 41 +++++++++++++++++++++-------- packages/core/src/webui/auth.ts | 31 ++++++++++++++++++++++ 2 files changed, 61 insertions(+), 11 deletions(-) diff --git a/packages/core/src/common/runtime.ts b/packages/core/src/common/runtime.ts index bfaa9737..d1f5e610 100644 --- a/packages/core/src/common/runtime.ts +++ b/packages/core/src/common/runtime.ts @@ -21,26 +21,45 @@ export function loadRuntimeConfig(): RuntimeConfig { fs.mkdirSync(CONFIG_DIR, { recursive: true }); const loaded = tryLoadRuntimeConfig(); + let normalized: RuntimeConfig; if (!loaded) { saveRuntimeConfig(DEFAULT_RUNTIME_CONFIG); - return { ...DEFAULT_RUNTIME_CONFIG }; + normalized = { ...DEFAULT_RUNTIME_CONFIG }; + } else { + normalized = { + webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099), + hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false), + }; + if ( + normalized.webuiPort !== loaded.webuiPort + || normalized.hookAutoLoad !== loaded.hookAutoLoad + ) { + saveRuntimeConfig(normalized); + } } - const normalized: RuntimeConfig = { - webuiPort: normalizePort(loaded.webuiPort ?? 5099, 5099), - hookAutoLoad: normalizeBool(loaded.hookAutoLoad, false), - }; - - if ( - normalized.webuiPort !== loaded.webuiPort - || normalized.hookAutoLoad !== loaded.hookAutoLoad - ) { - saveRuntimeConfig(normalized); + // SNOWLUMA_WEBUI_PORT overrides the on-disk value at runtime without + // rewriting runtime.json. Lets a trusted launcher (e.g. SnowLumaDesktop) + // pick a free port per-launch while CLI/Docker users continue to drive + // it from runtime.json. + const envPort = envPortOverride(); + if (envPort !== undefined) { + normalized = { ...normalized, webuiPort: envPort }; } return normalized; } +function envPortOverride(): number | undefined { + const raw = process.env.SNOWLUMA_WEBUI_PORT; + if (!raw || typeof raw !== 'string') return undefined; + const n = Number(raw.trim()); + if (!Number.isFinite(n)) return undefined; + const port = Math.trunc(n); + if (port <= 0 || port > 65535) return undefined; + return port; +} + function tryLoadRuntimeConfig(): RuntimeConfig | null { if (!fs.existsSync(RUNTIME_CONFIG_PATH)) return null; diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index b5688f50..79226178 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -24,6 +24,16 @@ export function isDevAuthMode(): boolean { return process.env.SNOWLUMA_DEV_MODE === '1'; } +function envBootstrapPassword(): string | null { + const raw = process.env.SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD; + if (!raw || typeof raw !== 'string') return null; + // Minimum sanity: avoid accidental empty / 1-char seeds. Strength + // rules still don't apply because we want trusted launchers to be + // able to pick a high-entropy random secret (e.g. base64(16)). + if (raw.length < 8) return null; + return raw; +} + export interface WebuiAuthState { passwordHash: string; // hex passwordSalt: string; // hex @@ -153,6 +163,27 @@ export class WebuiAuth { backupCorruptConfig(); } } + // SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD lets a trusted launcher seed the + // password on first run instead of having to scrape it from logs. + // Effect: write webui.json with the env-provided password, hashed, + // and mustChangePassword=false. Only honoured when there is NO existing + // webui.json — once persisted, password changes happen via the UI. + const envPassword = envBootstrapPassword(); + if (envPassword !== null) { + const salt = randomBytes(16); + const hash = hashPassword(envPassword, salt); + const now = new Date().toISOString(); + const state: WebuiAuthState = { + passwordHash: hash.toString('hex'), + passwordSalt: salt.toString('hex'), + mustChangePassword: false, + generatedAt: now, + updatedAt: now, + }; + atomicWrite(state); + log.info('webui credentials seeded from SNOWLUMA_WEBUI_BOOTSTRAP_PASSWORD'); + return new WebuiAuth(state, null, false); + } const initialPassword = randomBytes(8).toString('hex'); const state = generateInitialState(initialPassword); atomicWrite(state); From af1c50f4e7c69da083dd3ec0817aa78a33a2e9ff Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 00:24:10 +0800 Subject: [PATCH 13/51] feat(compat): add QQ compatibility manifest MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Static JSON served from raw.githubusercontent.com/.../main/compat/qq.json that SnowLumaDesktop polls (3-day cached fallback) to classify the local QQ install as known-good / known-bad / unknown / too-old. - compat/qq.json — initial allow-all manifest (policy.allowUnknown=true) - compat/qq.schema.json — JSON Schema for the manifest shape Editing this file is how we ship "QQ X.Y.Z breaks Hook" advisories without cutting a Desktop release. --- compat/qq.json | 19 +++++++++++++++ compat/qq.schema.json | 56 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 compat/qq.json create mode 100644 compat/qq.schema.json diff --git a/compat/qq.json b/compat/qq.json new file mode 100644 index 00000000..abb081bf --- /dev/null +++ b/compat/qq.json @@ -0,0 +1,19 @@ +{ + "$schema": "./qq.schema.json", + "version": 1, + "updatedAt": "2026-05-16T00:00:00Z", + "policy": { + "allowUnknown": true, + "warnUnknown": true + }, + "knownGoodVersions": [], + "knownBadVersions": [], + "minVersion": null, + "notes": [ + "QQ 兼容性 manifest — Desktop 启动时拉 https://raw.githubusercontent.com/SnowLuma/SnowLuma/main/compat/qq.json 校验本地 QQ 版本", + "policy.allowUnknown = true: 任何不在 knownBadVersions 里的版本都允许(理论上所有 QQ 新版本都可用)", + "knownBadVersions: 列在这里的版本 Desktop 会拒绝注入,弹出引导让用户切版本", + "minVersion: 设为 SemVer 字符串则更早的版本会被拒", + "知道某个版本会破坏 Hook 后把它加进 knownBadVersions,加 reason 字段说明" + ] +} diff --git a/compat/qq.schema.json b/compat/qq.schema.json new file mode 100644 index 00000000..0f0e3061 --- /dev/null +++ b/compat/qq.schema.json @@ -0,0 +1,56 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "SnowLuma QQ compatibility manifest", + "type": "object", + "required": ["version", "policy", "knownGoodVersions", "knownBadVersions"], + "properties": { + "$schema": { "type": "string" }, + "version": { "type": "integer", "const": 1 }, + "updatedAt": { "type": "string", "format": "date-time" }, + "policy": { + "type": "object", + "required": ["allowUnknown"], + "properties": { + "allowUnknown": { + "type": "boolean", + "description": "若 true,未在 known* 中列出的版本视为允许;若 false,需明确出现在 knownGoodVersions" + }, + "warnUnknown": { + "type": "boolean", + "description": "未列出的版本启动时是否弹警告" + } + } + }, + "knownGoodVersions": { + "type": "array", + "items": { + "type": "object", + "required": ["version"], + "properties": { + "version": { "type": "string", "description": "QQ 版本号字符串,如 '9.9.20.123'" }, + "note": { "type": "string" } + } + } + }, + "knownBadVersions": { + "type": "array", + "items": { + "type": "object", + "required": ["version"], + "properties": { + "version": { "type": "string" }, + "reason": { "type": "string" }, + "fixedInDesktopVersion": { "type": "string" } + } + } + }, + "minVersion": { + "type": ["string", "null"], + "description": "最低支持版本(SemVer),null = 不限" + }, + "notes": { + "type": "array", + "items": { "type": "string" } + } + } +} From 3e943e8f0da66fe9da9b4c30f44b50a4c9f34868 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 13:56:11 +0800 Subject: [PATCH 14/51] feat(ui): refresh theme tokens + add Popover/StatusDot/EmptyState/Kbd MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Visual overhaul to give @snowluma/ui a coherent, accessible identity. Tokens (styles/theme.css) - Deeper dark-mode surface ramp with more contrast between background / card / popover so dropdowns and dialogs read clearly in dark mode - New radius scale (xs → 3xl) anchored at 0.625rem for tighter feel - Layered shadow tokens (xs/sm/md/lg/xl) that adapt to mode - Semantic success / warning / info / destructive colour + foreground pairs replacing ad-hoc lookups - `--chrome-height` (52px) for consistent top-bar / sidebar header height - Utilities: `hover-lift`, `surface-glass`, `surface-gloss`; consumer- scoped scrollbar styling so native scrollbars match - Note: consumers must also `@import "tw-animate-css";` Components - Select: solid bg-popover + ring-1 ring-foreground/5; rotating chevron on open state; rounded-xl menu with shadow-xl (fixes the transparent dropdown bug) - Dialog / AlertDialog: bg-popover + ring; backdrop-blur on overlay; slide-in motion - Tooltip: ring + zoom-in motion, max-w-xs for long labels - Button: explicit transition list with active:translate-y-px; success / warning variants; icon-xs size - Input: hover border + focus ring + aria-invalid handling - Card: tighter line-height + typography - Badge: variants for success / warning / info / soft, size scale - ScrollArea: hover-only mode by default, slightly thicker thumb New components - Popover (radix wrapper) — for menus / inline overlays - StatusDot — semantic colored dot (replaces ad-hoc 🟢/🟡/🔴 emoji) - EmptyState — uniform placeholder for "nothing here yet" surfaces - Kbd — inline keyboard-key label --- packages/ui/package.json | 1 + packages/ui/src/components/alert-dialog.tsx | 13 +- packages/ui/src/components/badge.tsx | 23 ++- packages/ui/src/components/card.tsx | 20 +- packages/ui/src/components/dialog.tsx | 26 ++- packages/ui/src/components/empty-state.tsx | 36 ++++ packages/ui/src/components/input.tsx | 7 +- packages/ui/src/components/kbd.tsx | 17 ++ packages/ui/src/components/popover.tsx | 31 +++ packages/ui/src/components/scroll-area.tsx | 13 +- packages/ui/src/components/select.tsx | 43 ++-- packages/ui/src/components/status-dot.tsx | 49 +++++ packages/ui/src/components/tooltip.tsx | 5 +- packages/ui/src/index.ts | 4 + packages/ui/src/styles/theme.css | 211 +++++++++++++++----- pnpm-lock.yaml | 39 ++++ 16 files changed, 431 insertions(+), 107 deletions(-) create mode 100644 packages/ui/src/components/empty-state.tsx create mode 100644 packages/ui/src/components/kbd.tsx create mode 100644 packages/ui/src/components/popover.tsx create mode 100644 packages/ui/src/components/status-dot.tsx diff --git a/packages/ui/package.json b/packages/ui/package.json index 3388aa62..91326c8d 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -64,6 +64,7 @@ "@radix-ui/react-checkbox": "^1.1.5", "@radix-ui/react-dialog": "^1.1.7", "@radix-ui/react-label": "^2.1.3", + "@radix-ui/react-popover": "^1.1.7", "@radix-ui/react-scroll-area": "^1.2.4", "@radix-ui/react-select": "^2.2.6", "@radix-ui/react-separator": "^1.1.3", diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsx index 0a20ddff..02774795 100644 --- a/packages/ui/src/components/alert-dialog.tsx +++ b/packages/ui/src/components/alert-dialog.tsx @@ -14,8 +14,9 @@ const AlertDialogOverlay = React.forwardRef< @@ -31,10 +32,10 @@ const AlertDialogContent = React.forwardRef< @@ -54,7 +55,7 @@ const AlertDialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )); AlertDialogTitle.displayName = 'AlertDialogTitle'; @@ -62,7 +63,7 @@ const AlertDialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )); AlertDialogDescription.displayName = 'AlertDialogDescription'; diff --git a/packages/ui/src/components/badge.tsx b/packages/ui/src/components/badge.tsx index 25904349..45290da2 100644 --- a/packages/ui/src/components/badge.tsx +++ b/packages/ui/src/components/badge.tsx @@ -3,7 +3,7 @@ import { cva, type VariantProps } from 'class-variance-authority'; import { cn } from '../lib/cn'; export const badgeVariants = cva( - 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium transition-colors', + 'inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[11px] font-medium leading-none transition-colors', { variants: { variant: { @@ -12,15 +12,24 @@ export const badgeVariants = cva( destructive: 'border-transparent bg-destructive/15 text-destructive', success: 'border-transparent bg-success/15 text-success', warning: 'border-transparent bg-warning/15 text-warning', - outline: 'border-border text-foreground', + info: 'border-transparent bg-info/15 text-info', + outline: 'border-border bg-card text-foreground', + soft: 'border-transparent bg-muted text-muted-foreground', + }, + size: { + default: 'px-2 py-0.5 text-[11px]', + sm: 'px-1.5 py-px text-[10px]', + lg: 'px-2.5 py-1 text-xs', }, }, - defaultVariants: { variant: 'default' }, - } + defaultVariants: { variant: 'default', size: 'default' }, + }, ); -export interface BadgeProps extends React.HTMLAttributes, VariantProps {} +export interface BadgeProps + extends React.HTMLAttributes, + VariantProps {} -export function Badge({ className, variant, ...props }: BadgeProps) { - return ; +export function Badge({ className, variant, size, ...props }: BadgeProps) { + return ; } diff --git a/packages/ui/src/components/card.tsx b/packages/ui/src/components/card.tsx index ace53f35..87ff0efd 100644 --- a/packages/ui/src/components/card.tsx +++ b/packages/ui/src/components/card.tsx @@ -5,45 +5,45 @@ const Card = React.forwardRef (
- ) + ), ); Card.displayName = 'Card'; const CardHeader = React.forwardRef>( ({ className, ...props }, ref) => (
- ) + ), ); CardHeader.displayName = 'CardHeader'; const CardTitle = React.forwardRef>( ({ className, ...props }, ref) => ( -
- ) +
+ ), ); CardTitle.displayName = 'CardTitle'; const CardDescription = React.forwardRef>( ({ className, ...props }, ref) => ( -
- ) +
+ ), ); CardDescription.displayName = 'CardDescription'; const CardContent = React.forwardRef>( ({ className, ...props }, ref) => (
- ) + ), ); CardContent.displayName = 'CardContent'; const CardFooter = React.forwardRef>( ({ className, ...props }, ref) => ( -
- ) +
+ ), ); CardFooter.displayName = 'CardFooter'; diff --git a/packages/ui/src/components/dialog.tsx b/packages/ui/src/components/dialog.tsx index ba735bfd..ba375215 100644 --- a/packages/ui/src/components/dialog.tsx +++ b/packages/ui/src/components/dialog.tsx @@ -15,8 +15,9 @@ const DialogOverlay = React.forwardRef< @@ -32,16 +33,17 @@ const DialogContent = React.forwardRef< {children} {showClose && ( - + Close @@ -56,14 +58,18 @@ const DialogHeader = ({ className, ...props }: React.HTMLAttributes) => ( -
+
); const DialogTitle = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )); DialogTitle.displayName = 'DialogTitle'; @@ -71,7 +77,11 @@ const DialogDescription = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )); DialogDescription.displayName = 'DialogDescription'; diff --git a/packages/ui/src/components/empty-state.tsx b/packages/ui/src/components/empty-state.tsx new file mode 100644 index 00000000..77e1b51f --- /dev/null +++ b/packages/ui/src/components/empty-state.tsx @@ -0,0 +1,36 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +interface EmptyStateProps extends Omit, 'title'> { + icon?: React.ReactNode; + title: React.ReactNode; + description?: React.ReactNode; + action?: React.ReactNode; +} + +/** + * Generic "nothing here yet" placeholder. Used by Bot list, search-with-no- + * results, log filters that filtered everything out, etc. + */ +export function EmptyState({ icon, title, description, action, className, ...props }: EmptyStateProps) { + return ( +
+ {icon && ( +
+ {icon} +
+ )} +
+

{title}

+ {description &&

{description}

} +
+ {action &&
{action}
} +
+ ); +} diff --git a/packages/ui/src/components/input.tsx b/packages/ui/src/components/input.tsx index 7b1bd1e7..f8abeacb 100644 --- a/packages/ui/src/components/input.tsx +++ b/packages/ui/src/components/input.tsx @@ -7,17 +7,18 @@ const Input = React.forwardRef - ) + ), ); Input.displayName = 'Input'; diff --git a/packages/ui/src/components/kbd.tsx b/packages/ui/src/components/kbd.tsx new file mode 100644 index 00000000..5a93fe38 --- /dev/null +++ b/packages/ui/src/components/kbd.tsx @@ -0,0 +1,17 @@ +import * as React from 'react'; +import { cn } from '../lib/cn'; + +/** Small inline keyboard-key label, e.g. `⌘K`. */ +export const Kbd = React.forwardRef>( + ({ className, ...props }, ref) => ( + + ), +); +Kbd.displayName = 'Kbd'; diff --git a/packages/ui/src/components/popover.tsx b/packages/ui/src/components/popover.tsx new file mode 100644 index 00000000..86ac8997 --- /dev/null +++ b/packages/ui/src/components/popover.tsx @@ -0,0 +1,31 @@ +import * as React from 'react'; +import * as PopoverPrimitive from '@radix-ui/react-popover'; +import { cn } from '../lib/cn'; + +const Popover = PopoverPrimitive.Root; +const PopoverTrigger = PopoverPrimitive.Trigger; +const PopoverAnchor = PopoverPrimitive.Anchor; + +const PopoverContent = React.forwardRef< + React.ElementRef, + React.ComponentPropsWithoutRef +>(({ className, align = 'center', sideOffset = 6, ...props }, ref) => ( + + + +)); +PopoverContent.displayName = 'PopoverContent'; + +export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent }; diff --git a/packages/ui/src/components/scroll-area.tsx b/packages/ui/src/components/scroll-area.tsx index 98d8f8c6..c842f3aa 100644 --- a/packages/ui/src/components/scroll-area.tsx +++ b/packages/ui/src/components/scroll-area.tsx @@ -7,9 +7,10 @@ interface ScrollAreaProps extends React.ComponentPropsWithoutRef, ScrollAreaProps>( - ({ className, children, viewportClassName, ...props }, ref) => ( + ({ className, children, viewportClassName, type = 'hover', ...props }, ref) => ( @@ -22,7 +23,7 @@ const ScrollArea = React.forwardRef - ) + ), ); ScrollArea.displayName = 'ScrollArea'; @@ -35,13 +36,13 @@ const ScrollBar = React.forwardRef< orientation={orientation} className={cn( 'flex touch-none select-none p-0.5 transition-colors', - orientation === 'vertical' && 'h-full w-2 border-l border-l-transparent', - orientation === 'horizontal' && 'h-2 w-full flex-col border-t border-t-transparent', - className + orientation === 'vertical' && 'h-full w-2.5 border-l border-l-transparent', + orientation === 'horizontal' && 'h-2.5 w-full flex-col border-t border-t-transparent', + className, )} {...props} > - + )); ScrollBar.displayName = 'ScrollBar'; diff --git a/packages/ui/src/components/select.tsx b/packages/ui/src/components/select.tsx index 5d61b0af..d57d7cbd 100644 --- a/packages/ui/src/components/select.tsx +++ b/packages/ui/src/components/select.tsx @@ -14,18 +14,20 @@ const SelectTrigger = React.forwardRef< {children} - + )); @@ -37,7 +39,7 @@ const SelectScrollUpButton = React.forwardRef< >(({ className, ...props }, ref) => ( @@ -51,7 +53,7 @@ const SelectScrollDownButton = React.forwardRef< >(({ className, ...props }, ref) => ( @@ -67,17 +69,25 @@ const SelectContent = React.forwardRef< {children} @@ -91,7 +101,11 @@ const SelectLabel = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )); SelectLabel.displayName = 'SelectLabel'; @@ -102,14 +116,15 @@ const SelectItem = React.forwardRef< - + @@ -123,7 +138,7 @@ const SelectSeparator = React.forwardRef< React.ElementRef, React.ComponentPropsWithoutRef >(({ className, ...props }, ref) => ( - + )); SelectSeparator.displayName = 'SelectSeparator'; diff --git a/packages/ui/src/components/status-dot.tsx b/packages/ui/src/components/status-dot.tsx new file mode 100644 index 00000000..2f66c1ec --- /dev/null +++ b/packages/ui/src/components/status-dot.tsx @@ -0,0 +1,49 @@ +import * as React from 'react'; +import { cva, type VariantProps } from 'class-variance-authority'; +import { cn } from '../lib/cn'; + +/** + * A semantic colored status dot — drop-in replacement for ad-hoc emoji + * (🟢 / 🟡 / 🔴) so we keep visual rhythm with the rest of the Lucide + * iconography. `pulse` adds a soft halo for the "active" state. + */ +const dotVariants = cva('inline-block shrink-0 rounded-full', { + variants: { + tone: { + success: 'bg-success', + warning: 'bg-warning', + destructive: 'bg-destructive', + info: 'bg-info', + muted: 'bg-muted-foreground/50', + primary: 'bg-primary', + }, + size: { + xs: 'size-1.5', + sm: 'size-2', + md: 'size-2.5', + lg: 'size-3', + }, + }, + defaultVariants: { tone: 'muted', size: 'sm' }, +}); + +export interface StatusDotProps + extends React.HTMLAttributes, + VariantProps { + pulse?: boolean; +} + +export function StatusDot({ className, tone, size, pulse, ...props }: StatusDotProps) { + return ( + + + + ); +} diff --git a/packages/ui/src/components/tooltip.tsx b/packages/ui/src/components/tooltip.tsx index 0fde2304..f30b970a 100644 --- a/packages/ui/src/components/tooltip.tsx +++ b/packages/ui/src/components/tooltip.tsx @@ -15,9 +15,10 @@ const TooltipContent = React.forwardRef< ref={ref} sideOffset={sideOffset} className={cn( - 'z-50 overflow-hidden rounded-md border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-md', + 'z-50 max-w-xs overflow-hidden rounded-md border border-border bg-popover px-2.5 py-1.5 text-xs text-popover-foreground shadow-lg ring-1 ring-foreground/5', 'data-[state=delayed-open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=delayed-open]:fade-in-0', - className + 'data-[state=delayed-open]:zoom-in-95 data-[state=closed]:zoom-out-95', + className, )} {...props} /> diff --git a/packages/ui/src/index.ts b/packages/ui/src/index.ts index 7f50911c..b9eac5a2 100644 --- a/packages/ui/src/index.ts +++ b/packages/ui/src/index.ts @@ -66,3 +66,7 @@ export { Switch } from './components/switch'; export { Tabs, TabsList, TabsTrigger, TabsContent } from './components/tabs'; export { Toaster, toast, type ToasterProps } from './components/toaster'; export { Tooltip, TooltipTrigger, TooltipContent, TooltipProvider } from './components/tooltip'; +export { Popover, PopoverTrigger, PopoverAnchor, PopoverContent } from './components/popover'; +export { Kbd } from './components/kbd'; +export { StatusDot, type StatusDotProps } from './components/status-dot'; +export { EmptyState } from './components/empty-state'; diff --git a/packages/ui/src/styles/theme.css b/packages/ui/src/styles/theme.css index f3ac6e24..23dd490a 100644 --- a/packages/ui/src/styles/theme.css +++ b/packages/ui/src/styles/theme.css @@ -1,19 +1,18 @@ /** - * @snowluma/ui — Tailwind 4 theme tokens + * @snowluma/ui — Tailwind 4 theme tokens. * - * Usage in consumers (webui, SnowLumaDesktop): + * Consumer setup: * @import "tailwindcss"; + * @import "tw-animate-css"; * @import "@snowluma/ui/styles/theme.css"; - * - * Tailwind 4 will inline these via `@theme` and pick up classes used in - * `@snowluma/ui` components if the consumer adds: * @source "../node_modules/@snowluma/ui/dist/**\/*.js"; */ @custom-variant dark (&:where(.dark, .dark *)); :root { - --radius: 0.75rem; + /* Surface ramp — light mode: near-white surfaces over a faint blue base. */ + --radius: 0.625rem; --background: oklch(99% 0.004 240); --foreground: oklch(20% 0.03 250); @@ -24,79 +23,107 @@ --popover: oklch(100% 0 0); --popover-foreground: oklch(20% 0.03 250); - /* sky-500 */ - --primary: oklch(68.5% 0.155 230); + /* sky accent ramp */ + --primary: oklch(64% 0.16 230); --primary-foreground: oklch(99% 0.005 240); - --secondary: oklch(96% 0.012 240); - --secondary-foreground: oklch(25% 0.03 250); + --secondary: oklch(96.5% 0.012 240); + --secondary-foreground: oklch(22% 0.03 250); - --muted: oklch(96% 0.012 240); - --muted-foreground: oklch(50% 0.02 250); + --muted: oklch(96.5% 0.012 240); + --muted-foreground: oklch(48% 0.02 250); - --accent: oklch(94% 0.03 230); - --accent-foreground: oklch(35% 0.07 230); + --accent: oklch(94% 0.04 230); + --accent-foreground: oklch(28% 0.08 230); - --destructive: oklch(60% 0.22 27); + --destructive: oklch(58% 0.22 27); --destructive-foreground: oklch(99% 0.005 240); - --success: oklch(70% 0.15 160); - --warning: oklch(78% 0.16 80); + --success: oklch(64% 0.16 155); + --success-foreground: oklch(99% 0.005 240); - --border: oklch(92% 0.01 240); + --warning: oklch(76% 0.16 75); + --warning-foreground: oklch(20% 0.05 75); + + --info: oklch(64% 0.16 230); + --info-foreground: oklch(99% 0.005 240); + + --border: oklch(91% 0.012 240); --input: oklch(94% 0.012 240); - --ring: oklch(68.5% 0.155 230); + --ring: oklch(64% 0.16 230); --sidebar: oklch(98% 0.006 240); --sidebar-foreground: oklch(25% 0.03 250); - --sidebar-primary: oklch(68.5% 0.155 230); + --sidebar-primary: oklch(64% 0.16 230); --sidebar-primary-foreground: oklch(99% 0.005 240); - --sidebar-accent: oklch(94% 0.025 230); - --sidebar-accent-foreground: oklch(35% 0.08 230); - --sidebar-border: oklch(92% 0.01 240); - --sidebar-ring: oklch(68.5% 0.155 230); + --sidebar-accent: oklch(94% 0.03 230); + --sidebar-accent-foreground: oklch(28% 0.08 230); + --sidebar-border: oklch(91% 0.012 240); + --sidebar-ring: oklch(64% 0.16 230); + + --chrome-height: 3.25rem; /* 52px — uniform top-bar height */ + + --shadow-color: 240 6% 10%; + --shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.05); + --shadow-sm: 0 1px 3px 0 hsl(var(--shadow-color) / 0.08), 0 1px 2px -1px hsl(var(--shadow-color) / 0.06); + --shadow-md: 0 4px 6px -1px hsl(var(--shadow-color) / 0.08), 0 2px 4px -2px hsl(var(--shadow-color) / 0.04); + --shadow-lg: 0 10px 16px -3px hsl(var(--shadow-color) / 0.10), 0 4px 6px -4px hsl(var(--shadow-color) / 0.05); + --shadow-xl: 0 20px 28px -8px hsl(var(--shadow-color) / 0.14); } .dark { - --background: oklch(16% 0.02 250); - --foreground: oklch(96% 0.01 240); + --background: oklch(13% 0.02 250); + --foreground: oklch(96% 0.012 240); - --card: oklch(20% 0.025 250); - --card-foreground: oklch(96% 0.01 240); + --card: oklch(17% 0.022 250); + --card-foreground: oklch(96% 0.012 240); --popover: oklch(20% 0.025 250); - --popover-foreground: oklch(96% 0.01 240); + --popover-foreground: oklch(96% 0.012 240); - --primary: oklch(75% 0.14 230); - --primary-foreground: oklch(15% 0.02 250); + --primary: oklch(72% 0.16 230); + --primary-foreground: oklch(12% 0.025 250); - --secondary: oklch(25% 0.025 250); - --secondary-foreground: oklch(96% 0.01 240); + --secondary: oklch(22% 0.025 250); + --secondary-foreground: oklch(94% 0.012 240); - --muted: oklch(24% 0.02 250); - --muted-foreground: oklch(68% 0.02 240); + --muted: oklch(20% 0.022 250); + --muted-foreground: oklch(72% 0.02 240); - --accent: oklch(28% 0.05 230); - --accent-foreground: oklch(85% 0.1 230); + --accent: oklch(30% 0.06 230); + --accent-foreground: oklch(88% 0.12 230); - --destructive: oklch(62% 0.2 27); + --destructive: oklch(66% 0.22 27); --destructive-foreground: oklch(98% 0.005 240); - --success: oklch(72% 0.15 160); - --warning: oklch(80% 0.16 80); + --success: oklch(70% 0.16 155); + --success-foreground: oklch(12% 0.025 250); - --border: oklch(28% 0.02 250); - --input: oklch(26% 0.02 250); - --ring: oklch(75% 0.14 230); + --warning: oklch(80% 0.16 75); + --warning-foreground: oklch(20% 0.05 75); - --sidebar: oklch(18% 0.022 250); - --sidebar-foreground: oklch(92% 0.01 240); - --sidebar-primary: oklch(75% 0.14 230); - --sidebar-primary-foreground: oklch(15% 0.02 250); - --sidebar-accent: oklch(28% 0.05 230); - --sidebar-accent-foreground: oklch(85% 0.1 230); - --sidebar-border: oklch(26% 0.02 250); - --sidebar-ring: oklch(75% 0.14 230); + --info: oklch(72% 0.16 230); + --info-foreground: oklch(12% 0.025 250); + + --border: oklch(28% 0.025 250); + --input: oklch(26% 0.025 250); + --ring: oklch(72% 0.16 230); + + --sidebar: oklch(15% 0.022 250); + --sidebar-foreground: oklch(92% 0.012 240); + --sidebar-primary: oklch(72% 0.16 230); + --sidebar-primary-foreground: oklch(12% 0.025 250); + --sidebar-accent: oklch(28% 0.06 230); + --sidebar-accent-foreground: oklch(88% 0.12 230); + --sidebar-border: oklch(24% 0.025 250); + --sidebar-ring: oklch(72% 0.16 230); + + --shadow-color: 240 14% 4%; + --shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.30); + --shadow-sm: 0 1px 3px 0 hsl(var(--shadow-color) / 0.36), 0 1px 2px -1px hsl(var(--shadow-color) / 0.28); + --shadow-md: 0 4px 6px -1px hsl(var(--shadow-color) / 0.40), 0 2px 4px -2px hsl(var(--shadow-color) / 0.28); + --shadow-lg: 0 10px 16px -3px hsl(var(--shadow-color) / 0.50), 0 4px 6px -4px hsl(var(--shadow-color) / 0.32); + --shadow-xl: 0 20px 28px -8px hsl(var(--shadow-color) / 0.55); } @theme inline { @@ -117,7 +144,11 @@ --color-destructive: var(--destructive); --color-destructive-foreground: var(--destructive-foreground); --color-success: var(--success); + --color-success-foreground: var(--success-foreground); --color-warning: var(--warning); + --color-warning-foreground: var(--warning-foreground); + --color-info: var(--info); + --color-info-foreground: var(--info-foreground); --color-border: var(--border); --color-input: var(--input); --color-ring: var(--ring); @@ -130,11 +161,89 @@ --color-sidebar-border: var(--sidebar-border); --color-sidebar-ring: var(--sidebar-ring); + --radius-xs: calc(var(--radius) - 6px); --radius-sm: calc(var(--radius) - 4px); --radius-md: calc(var(--radius) - 2px); --radius-lg: var(--radius); --radius-xl: calc(var(--radius) + 4px); + --radius-2xl: calc(var(--radius) + 8px); + --radius-3xl: calc(var(--radius) + 16px); + + --shadow-xs: var(--shadow-xs); + --shadow-sm: var(--shadow-sm); + --shadow-md: var(--shadow-md); + --shadow-lg: var(--shadow-lg); + --shadow-xl: var(--shadow-xl); --font-sans: 'Inter', 'Noto Sans SC', system-ui, -apple-system, sans-serif; --font-mono: 'JetBrains Mono', 'Fira Code', ui-monospace, monospace; } + +@layer base { + * { + border-color: var(--border); + } + html, body, #root { + height: 100%; + } + body { + margin: 0; + background-color: var(--background); + color: var(--foreground); + font-family: var(--font-sans); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + line-height: 1.5; + overflow: hidden; /* desktop chrome: no body scroll, panels manage their own */ + } + ::selection { + background-color: color-mix(in oklab, var(--primary) 28%, transparent); + color: var(--foreground); + } + + *::-webkit-scrollbar { + width: 10px; + height: 10px; + } + *::-webkit-scrollbar-track { + background: transparent; + } + *::-webkit-scrollbar-thumb { + background-color: color-mix(in oklab, var(--muted-foreground) 35%, transparent); + border-radius: 9999px; + border: 2px solid transparent; + background-clip: content-box; + } + *::-webkit-scrollbar-thumb:hover { + background-color: color-mix(in oklab, var(--muted-foreground) 55%, transparent); + background-clip: content-box; + } + + html[data-density="compact"] body { + font-size: 13.5px; + line-height: 1.45; + } +} + +@layer utilities { + .hover-lift { + transition: transform 180ms cubic-bezier(0.22, 1, 0.36, 1), + box-shadow 220ms cubic-bezier(0.22, 1, 0.36, 1); + } + .hover-lift:hover { + transform: translateY(-1px); + box-shadow: var(--shadow-md); + } + .surface-gloss { + background-image: linear-gradient( + 180deg, + color-mix(in oklab, var(--foreground) 3%, transparent) 0%, + transparent 80% + ); + } + .surface-glass { + background-color: color-mix(in oklab, var(--popover) 92%, transparent); + backdrop-filter: saturate(180%) blur(12px); + -webkit-backdrop-filter: saturate(180%) blur(12px); + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 7275beaa..be5db7cb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -92,6 +92,9 @@ importers: '@radix-ui/react-label': specifier: ^2.1.3 version: 2.1.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-popover': + specifier: ^1.1.7 + version: 1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) '@radix-ui/react-scroll-area': specifier: ^1.2.4 version: 1.2.10(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) @@ -832,6 +835,19 @@ packages: '@types/react-dom': optional: true + '@radix-ui/react-popover@1.1.15': + resolution: {integrity: sha512-kr0X2+6Yy/vJzLYJUPCZEc8SfQcf+1COFoAqauJm74umQhta9M7lNJHP7QQS3vkvcGLQUbWpMzwrXYwrYztHKA==} + peerDependencies: + '@types/react': '*' + '@types/react-dom': '*' + react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc + peerDependenciesMeta: + '@types/react': + optional: true + '@types/react-dom': + optional: true + '@radix-ui/react-popper@1.2.8': resolution: {integrity: sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw==} peerDependencies: @@ -3144,6 +3160,29 @@ snapshots: '@types/react': 19.2.14 '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-popover@1.1.15(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': + dependencies: + '@radix-ui/primitive': 1.1.3 + '@radix-ui/react-compose-refs': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-context': 1.1.2(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-dismissable-layer': 1.1.11(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-focus-guards': 1.1.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-focus-scope': 1.1.7(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-id': 1.1.1(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-popper': 1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-portal': 1.1.9(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-presence': 1.1.5(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-primitive': 2.1.3(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5) + '@radix-ui/react-slot': 1.2.3(@types/react@19.2.14)(react@19.2.5) + '@radix-ui/react-use-controllable-state': 1.2.2(@types/react@19.2.14)(react@19.2.5) + aria-hidden: 1.2.6 + react: 19.2.5 + react-dom: 19.2.5(react@19.2.5) + react-remove-scroll: 2.7.2(@types/react@19.2.14)(react@19.2.5) + optionalDependencies: + '@types/react': 19.2.14 + '@types/react-dom': 19.2.3(@types/react@19.2.14) + '@radix-ui/react-popper@1.2.8(@types/react-dom@19.2.3(@types/react@19.2.14))(@types/react@19.2.14)(react-dom@19.2.5(react@19.2.5))(react@19.2.5)': dependencies: '@floating-ui/react-dom': 2.1.8(react-dom@19.2.5(react@19.2.5))(react@19.2.5) From 8a94188dc61d161f9f07b8d6a2eb938c6bf946ef Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 14:11:29 +0800 Subject: [PATCH 15/51] fix(ui): dark-mode Switch + Checkbox visibility Both controls used `bg-muted` / `bg-background` for unchecked / thumb which collapse to the same hue as the surrounding card in dark mode, making them effectively invisible. - Switch: unchecked track now bg-input (light) / bg-muted-foreground/25 (dark) with a shadow-inner; thumb uses bg-card (light) / bg-foreground/95 (dark) so it pops in both states. - Checkbox: explicit bg-card + hover:border-border/80; slightly larger radius (5px) for visual rhythm with the rest of the surface. --- packages/ui/src/components/checkbox.tsx | 5 +++-- packages/ui/src/components/switch.tsx | 15 ++++++++++----- 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/packages/ui/src/components/checkbox.tsx b/packages/ui/src/components/checkbox.tsx index f7e0bc60..e8119416 100644 --- a/packages/ui/src/components/checkbox.tsx +++ b/packages/ui/src/components/checkbox.tsx @@ -10,12 +10,13 @@ const Checkbox = React.forwardRef< diff --git a/packages/ui/src/components/switch.tsx b/packages/ui/src/components/switch.tsx index a8c875e2..4f4bf43f 100644 --- a/packages/ui/src/components/switch.tsx +++ b/packages/ui/src/components/switch.tsx @@ -9,18 +9,23 @@ const Switch = React.forwardRef< From 593f5f42bcc0b5de5de8f6ff89d7e031d6176179 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 14:24:09 +0800 Subject: [PATCH 16/51] fix(ui): Dialog and Select no longer overflow at narrow widths CSS grid's default `min-width: auto` per track was letting long selected-option text and file paths inside dialogs push the container past its `max-w-lg` cap, which on Windows / smaller viewports clipped the right edge of inputs and the Select chevron. - DialogContent / AlertDialogContent: `grid-cols-[minmax(0,1fr)]` clamps the single track to its container width; `w-[calc(100%-2rem)]` keeps a 1 rem gutter to the viewport edge on small screens. - SelectTrigger: `min-w-0` on the trigger itself plus a child-targeted truncate (`[&>span:not([data-radix-select-icon])]:truncate`) so the selected text shrinks before the chevron does; chevron gets `shrink-0` for the same reason. --- packages/ui/src/components/alert-dialog.tsx | 2 +- packages/ui/src/components/dialog.tsx | 5 ++++- packages/ui/src/components/select.tsx | 8 +++++--- 3 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/ui/src/components/alert-dialog.tsx b/packages/ui/src/components/alert-dialog.tsx index 02774795..2cb1b30a 100644 --- a/packages/ui/src/components/alert-dialog.tsx +++ b/packages/ui/src/components/alert-dialog.tsx @@ -32,7 +32,7 @@ const AlertDialogContent = React.forwardRef< span:not([data-radix-select-icon])]:flex-1 [&>span:not([data-radix-select-icon])]:min-w-0 [&>span:not([data-radix-select-icon])]:truncate [&>span:not([data-radix-select-icon])]:text-left', className, )} {...props} > {children} - - + + )); From d7252b6c31c58e47e9a2c574bb0f1bd97c1c78b5 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 14:42:29 +0800 Subject: [PATCH 17/51] feat(ui): Button success/warning variants + active translate + icon-xs Polish pass that an earlier edit lost: - Add `success` and `warning` button variants (semantic colour pairs consumers can reach for in confirm dialogs / status actions). - Outline gets a real card background + shadow so it pops on tinted surfaces (previously bg-transparent looked invisible on muted/40 rows). - Tighter motion: explicit transition list + `active:translate-y-px` so clicks feel mechanical. - New size `icon-xs` for inline action buttons that need to fit in a log-row toolbar without ballooning the row height. - Default radius bumped to `rounded-lg`; sm stays `rounded-md`. --- packages/ui/src/components/button.tsx | 34 ++++++++++++++++++--------- 1 file changed, 23 insertions(+), 11 deletions(-) diff --git a/packages/ui/src/components/button.tsx b/packages/ui/src/components/button.tsx index 42a436fe..25a16a0c 100644 --- a/packages/ui/src/components/button.tsx +++ b/packages/ui/src/components/button.tsx @@ -4,27 +4,39 @@ import { cva, type VariantProps } from 'class-variance-authority'; import { cn } from '../lib/cn'; export const buttonVariants = cva( - "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0 outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring cursor-pointer", + [ + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-lg text-sm font-medium", + "transition-[color,background-color,border-color,box-shadow,transform] duration-150 ease-out", + "disabled:pointer-events-none disabled:opacity-50", + "[&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 [&_svg]:shrink-0", + "outline-none focus-visible:ring-[3px] focus-visible:ring-ring/40 focus-visible:border-ring", + "active:translate-y-px cursor-pointer", + ].join(' '), { variants: { variant: { default: 'bg-primary text-primary-foreground shadow-sm hover:bg-primary/90 active:bg-primary/95', - destructive: 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90', - outline: 'border border-border bg-transparent hover:bg-accent hover:text-accent-foreground', - secondary: 'bg-secondary text-secondary-foreground hover:bg-secondary/80', - ghost: 'hover:bg-accent hover:text-accent-foreground', - link: 'text-primary underline-offset-4 hover:underline', + destructive: + 'bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90 active:bg-destructive/95', + outline: + 'border border-border bg-card text-foreground shadow-xs hover:bg-accent hover:text-accent-foreground hover:border-border/80', + secondary: 'bg-secondary text-secondary-foreground shadow-xs hover:bg-secondary/80', + ghost: 'text-foreground hover:bg-accent hover:text-accent-foreground', + link: 'text-primary underline-offset-4 hover:underline shadow-none', + success: 'bg-success text-success-foreground shadow-sm hover:bg-success/90', + warning: 'bg-warning text-warning-foreground shadow-sm hover:bg-warning/90', }, size: { default: 'h-9 px-4 py-2', sm: 'h-8 rounded-md px-3 text-xs', - lg: 'h-10 rounded-md px-6', - icon: 'size-9', - 'icon-sm': 'size-8', + lg: 'h-10 rounded-lg px-6', + icon: 'size-9 rounded-lg', + 'icon-sm': 'size-8 rounded-md', + 'icon-xs': 'size-7 rounded-md', }, }, defaultVariants: { variant: 'default', size: 'default' }, - } + }, ); export interface ButtonProps @@ -37,6 +49,6 @@ export const Button = React.forwardRef( ({ className, variant, size, asChild = false, ...props }, ref) => { const Comp = asChild ? Slot : 'button'; return ; - } + }, ); Button.displayName = 'Button'; From b441647df4fcc5fbaeee018078c4a74f2fc2044b Mon Sep 17 00:00:00 2001 From: airline233 Date: Sun, 17 May 2026 15:27:43 +0800 Subject: [PATCH 18/51] feat(http-server): support parse content-type of urlencoded --- .../src/onebot/network/http-server-adapter.ts | 66 ++++++-- .../tests/http-server-content-type.test.ts | 149 ++++++++++++++++++ 2 files changed, 203 insertions(+), 12 deletions(-) create mode 100644 packages/core/tests/http-server-content-type.test.ts diff --git a/packages/core/src/onebot/network/http-server-adapter.ts b/packages/core/src/onebot/network/http-server-adapter.ts index 778ae4b2..4c36e68a 100644 --- a/packages/core/src/onebot/network/http-server-adapter.ts +++ b/packages/core/src/onebot/network/http-server-adapter.ts @@ -136,19 +136,61 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter } else if (req.method === 'POST') { const bodyContent = await readRequestBody(req); if (bodyContent.trim()) { - try { - const parsedBody = JSON.parse(bodyContent); - if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { - if (parsedBody.action && !action) action = String(parsedBody.action); - if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { - params = parsedBody.params as Record; - } else { - params = parsedBody as Record; + const contentType = req.headers['content-type'] ?? ''; + if (contentType.includes('application/x-www-form-urlencoded')) { + const parsed = new URLSearchParams(bodyContent); + parsed.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; } - echo = parsedBody.echo; + }); + if (params.action && !action) { + action = String(params.action); + delete params.action; } - } catch { - writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + if (params.echo !== undefined) { + echo = params.echo; + delete params.echo; + } + } else if (contentType.includes('application/json') || !contentType) { + try { + const parsedBody = JSON.parse(bodyContent); + if (typeof parsedBody === 'object' && parsedBody !== null && !Array.isArray(parsedBody)) { + if (parsedBody.action && !action) action = String(parsedBody.action); + if (parsedBody.params && typeof parsedBody.params === 'object' && !Array.isArray(parsedBody.params)) { + params = parsedBody.params as Record; + } else { + params = parsedBody as Record; + } + echo = parsedBody.echo; + } + } catch { + if (contentType.includes('application/json')) { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: 'bad request: invalid json' }); + return; + } + // 无 content-type,JSON 失败则 fallback 到 urlencoded + const parsed = new URLSearchParams(bodyContent); + parsed.forEach((value, key) => { + try { + params[key] = JSON.parse(value); + } catch { + params[key] = value; + } + }); + if (params.action && !action) { + action = String(params.action); + delete params.action; + } + if (params.echo !== undefined) { + echo = params.echo; + delete params.echo; + } + } + } else { + writeJson(res, 400, { status: 'failed', retcode: 1400, data: null, wording: `bad request: unsupported content-type: ${contentType}` }); return; } } @@ -200,4 +242,4 @@ function writeJson(res: ServerResponse, statusCode: number, data: unknown): void res.statusCode = statusCode; res.setHeader('Content-Type', 'application/json; charset=utf-8'); res.end(JSON.stringify(data)); -} +} \ No newline at end of file diff --git a/packages/core/tests/http-server-content-type.test.ts b/packages/core/tests/http-server-content-type.test.ts new file mode 100644 index 00000000..71d7ea26 --- /dev/null +++ b/packages/core/tests/http-server-content-type.test.ts @@ -0,0 +1,149 @@ +// Tests for HTTP server adapter content-type parsing (POST body). +// Covers: application/x-www-form-urlencoded, application/json, +// no content-type fallback, and unsupported content-type rejection. + +import { describe, expect, it, vi, beforeAll, afterAll } from 'vitest'; +import http from 'http'; +import { HttpServerAdapter } from '../src/onebot/network/http-server-adapter'; +import type { NetworkAdapterContext } from '../src/onebot/network/adapter'; +import type { HttpServerNetwork } from '../src/onebot/types'; + +// ─── Helpers ─── + +function fakeCtx(handleFn: (action: string, params: Record) => unknown): NetworkAdapterContext { + return { + uin: '10001', + api: { + handle: vi.fn(async (action: string, params: Record) => { + const data = handleFn(action, params); + return { status: 'ok', retcode: 0, data }; + }), + } as any, + buildLifecycleEvent: vi.fn(() => ({})), + buildHeartbeatEvent: vi.fn(() => ({})), + }; +} + +function post(port: number, path: string, body: string, headers: Record = {}): Promise<{ status: number; body: any }> { + return new Promise((resolve, reject) => { + const req = http.request({ hostname: '127.0.0.1', port, path, method: 'POST', headers }, (res) => { + const chunks: Buffer[] = []; + res.on('data', (c) => chunks.push(c)); + res.on('end', () => { + const raw = Buffer.concat(chunks).toString('utf8'); + try { + resolve({ status: res.statusCode!, body: JSON.parse(raw) }); + } catch { + resolve({ status: res.statusCode!, body: raw }); + } + }); + }); + req.on('error', reject); + req.end(body); + }); +} + +// ─── Tests ─── + +describe('HttpServerAdapter content-type parsing', () => { + let adapter: HttpServerAdapter; + let handleFn: ReturnType) => unknown>>; + const PORT = 19876; + + beforeAll(async () => { + handleFn = vi.fn((_action: string, params: Record) => params); + const ctx = fakeCtx(handleFn); + const config: HttpServerNetwork = { name: 'test-http', port: PORT, enabled: true, messageFormat: 'array', reportSelfMessage: false }; + adapter = new HttpServerAdapter('test-http', config, ctx); + adapter.open(); + // Wait for server to be listening + await new Promise((resolve) => setTimeout(resolve, 100)); + }); + + afterAll(() => { + adapter.close(); + }); + + it('should parse application/json body', async () => { + const res = await post(PORT, '/send_message', JSON.stringify({ params: { group_id: 123, message: 'hi' } }), { + 'content-type': 'application/json', + }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 123, message: 'hi' }); + }); + + it('should parse application/x-www-form-urlencoded body', async () => { + handleFn.mockClear(); + const body = 'group_id=456&message=hello'; + const res = await post(PORT, '/send_message', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(res.body.status).toBe('ok'); + expect(handleFn).toHaveBeenCalledWith('send_message', { group_id: 456, message: 'hello' }); + }); + + it('should JSON-parse values in urlencoded body', async () => { + handleFn.mockClear(); + const body = 'user_id=789&data={"nested":true}'; + const res = await post(PORT, '/get_info', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('get_info', { user_id: 789, data: { nested: true } }); + }); + + it('should extract action from urlencoded body when path has no action', async () => { + handleFn.mockClear(); + const body = 'action=get_status&key=value'; + const res = await post(PORT, '/', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('get_status', { key: 'value' }); + }); + + it('should extract echo from urlencoded body', async () => { + handleFn.mockClear(); + const body = 'action=test_action&echo=12345&foo=bar'; + const res = await post(PORT, '/', body, { + 'content-type': 'application/x-www-form-urlencoded', + }); + expect(res.status).toBe(200); + expect(res.body.echo).toBe(12345); + expect(handleFn).toHaveBeenCalledWith('test_action', { foo: 'bar' }); + }); + + it('should reject unsupported content-type with 400', async () => { + const res = await post(PORT, '/send_message', '', { + 'content-type': 'application/xml', + }); + expect(res.status).toBe(400); + expect(res.body.wording).toContain('unsupported content-type'); + }); + + it('should reject invalid JSON with explicit application/json content-type', async () => { + const res = await post(PORT, '/send_message', 'not-json{{{', { + 'content-type': 'application/json', + }); + expect(res.status).toBe(400); + expect(res.body.wording).toContain('invalid json'); + }); + + it('should fallback to urlencoded when no content-type and body is not valid JSON', async () => { + handleFn.mockClear(); + const body = 'action=fallback_action¶m1=value1'; + const res = await post(PORT, '/', body, {}); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('fallback_action', { param1: 'value1' }); + }); + + it('should parse JSON when no content-type and body is valid JSON', async () => { + handleFn.mockClear(); + const body = JSON.stringify({ action: 'json_action', params: { x: 1 } }); + const res = await post(PORT, '/', body, {}); + expect(res.status).toBe(200); + expect(handleFn).toHaveBeenCalledWith('json_action', { x: 1 }); + }); +}); From b3e37e2f7c391390fba0e48634e7415d5de393b8 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 16:31:30 +0800 Subject: [PATCH 19/51] feat(ui): add indeterminate mode to Progress MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desktop's core-download dialog needs to show progress while the server returns no Content-Length (some mirrors omit it; the SnowLuma core release artifact does have it but GitHub's CDN sometimes strips it on redirects). Hard-coded 50% was a placeholder. Add an `indeterminate` boolean prop: when true, render a marquee bar that animates left-to-right indefinitely. When false, render the familiar bytes-done / bytes-total fill at `value%`. Hooked up via a new `@keyframes progress-marquee` in theme.css. Also dropped the bar's CSS transition from 500ms → 200ms so live download updates feel responsive instead of laggy. --- packages/ui/src/components/progress.tsx | 38 +++++++++++++++++++------ packages/ui/src/styles/theme.css | 9 ++++++ 2 files changed, 39 insertions(+), 8 deletions(-) diff --git a/packages/ui/src/components/progress.tsx b/packages/ui/src/components/progress.tsx index 0cc75e45..446ab746 100644 --- a/packages/ui/src/components/progress.tsx +++ b/packages/ui/src/components/progress.tsx @@ -4,28 +4,50 @@ import { cn } from '../lib/cn'; interface ProgressProps extends React.HTMLAttributes { value?: number; indicatorClassName?: string; + /** + * When true, the bar shows an animated marquee instead of a fixed + * width — useful when we know a job is running but don't yet know + * the total size (e.g. a download whose Content-Length is unknown). + */ + indeterminate?: boolean; } const Progress = React.forwardRef( - ({ className, value = 0, indicatorClassName, ...props }, ref) => { + ({ className, value = 0, indicatorClassName, indeterminate = false, ...props }, ref) => { const clamped = Math.max(0, Math.min(100, value)); return (
-
+ {indeterminate ? ( +
+ ) : ( +
+ )}
); - } + }, ); Progress.displayName = 'Progress'; diff --git a/packages/ui/src/styles/theme.css b/packages/ui/src/styles/theme.css index 23dd490a..1e02b17f 100644 --- a/packages/ui/src/styles/theme.css +++ b/packages/ui/src/styles/theme.css @@ -247,3 +247,12 @@ -webkit-backdrop-filter: saturate(180%) blur(12px); } } + +@keyframes progress-marquee { + 0% { + transform: translateX(-100%); + } + 100% { + transform: translateX(400%); + } +} From 0d54fd83c6f9e2c22385ac805bd6decc6c6d9354 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 16:49:27 +0800 Subject: [PATCH 20/51] feat(ui): add --titlebar-height token for Desktop's frameless window MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Desktop is switching from the native Windows titlebar to a custom one rendered in the renderer (frameless BrowserWindow + custom Min/Max/Close). The bar is 32px tall — the same height Windows draws its system titlebar — so expose it as a token here for any future Desktop layout that needs to subtract it. --- packages/ui/src/styles/theme.css | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/ui/src/styles/theme.css b/packages/ui/src/styles/theme.css index 1e02b17f..608b8b96 100644 --- a/packages/ui/src/styles/theme.css +++ b/packages/ui/src/styles/theme.css @@ -62,6 +62,7 @@ --sidebar-ring: oklch(64% 0.16 230); --chrome-height: 3.25rem; /* 52px — uniform top-bar height */ + --titlebar-height: 2rem; /* 32px — Windows native titlebar height */ --shadow-color: 240 6% 10%; --shadow-xs: 0 1px 2px 0 hsl(var(--shadow-color) / 0.05); From 0c5eef87e669330e9b02f4961424a770c0d5063b Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 17:24:21 +0800 Subject: [PATCH 21/51] ci: publish @snowluma/ui to npm on push to main Mirror of sdk-npm-publish.yml for the UI package. Same triggers (packages/ui/** + lockfile/workspace/tsconfig.base) and same already-published guard via `npm view`, so reruns are idempotent. Differences from the SDK workflow: - Drops the `test` step (UI package has no Vitest suite yet). - Filters and working-directory point at packages/ui. Auth uses the same `NPM_TOKEN` secret in the SnowLuma environment. Publishes with `--provenance` so the npm registry attests the build came from this exact GitHub Actions run. --- .github/workflows/ui-npm-publish.yml | 103 +++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 .github/workflows/ui-npm-publish.yml diff --git a/.github/workflows/ui-npm-publish.yml b/.github/workflows/ui-npm-publish.yml new file mode 100644 index 00000000..a7a43044 --- /dev/null +++ b/.github/workflows/ui-npm-publish.yml @@ -0,0 +1,103 @@ +name: Publish UI to npm + +on: + push: + branches: [main] + paths: + - 'packages/ui/**' + - 'package.json' + - 'pnpm-lock.yaml' + - 'pnpm-workspace.yaml' + - 'tsconfig.base.json' + workflow_dispatch: + +permissions: + contents: read + id-token: write + +concurrency: + group: ui-npm-publish-${{ github.ref }} + cancel-in-progress: false + +jobs: + publish: + name: Build and publish UI + runs-on: ubuntu-latest + environment: SnowLuma + steps: + - name: Checkout + uses: actions/checkout@v6 + + - name: Setup pnpm + uses: pnpm/action-setup@v6 + with: + version: 10.28.0 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v6 + with: + node-version: '22' + cache: 'pnpm' + registry-url: 'https://registry.npmjs.org' + + - name: Install dependencies + run: pnpm install --frozen-lockfile + + - name: Type check UI + run: pnpm --filter @snowluma/ui typecheck + + - name: Build UI + run: pnpm --filter @snowluma/ui build + + - name: Check npm package version + id: npm + working-directory: packages/ui + shell: bash + run: | + set -euo pipefail + package_name="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).name)")" + package_version="$(node -e "const fs = require('node:fs'); console.log(JSON.parse(fs.readFileSync('package.json', 'utf8')).version)")" + + { + echo "package_name=${package_name}" + echo "package_version=${package_version}" + } >> "${GITHUB_OUTPUT}" + + if npm view "${package_name}@${package_version}" version >/dev/null 2>&1; then + echo "already_published=true" >> "${GITHUB_OUTPUT}" + echo "::notice::${package_name}@${package_version} already exists on npm; skipping publish." + else + echo "already_published=false" >> "${GITHUB_OUTPUT}" + fi + + - name: Validate npm token + if: steps.npm.outputs.already_published != 'true' + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + if [ -z "${NODE_AUTH_TOKEN}" ]; then + echo 'Missing NPM_TOKEN in the SnowLuma environment secrets.' >&2 + exit 1 + fi + + - name: Publish UI to npm + if: steps.npm.outputs.already_published != 'true' + working-directory: packages/ui + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: npm publish --access public --provenance + + - name: Summary + shell: bash + run: | + { + echo "## UI npm publish" + echo + echo "| Key | Value |" + echo "| --- | --- |" + echo "| Package | \`${{ steps.npm.outputs.package_name }}\` |" + echo "| Version | \`${{ steps.npm.outputs.package_version }}\` |" + echo "| Already published | \`${{ steps.npm.outputs.already_published }}\` |" + echo "| Environment | \`SnowLuma\` |" + } >> "${GITHUB_STEP_SUMMARY}" From 37dd7d2173cacfb08980d216b25db8b58735542a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 18:20:05 +0800 Subject: [PATCH 22/51] fix(webui): rotate stale bootstrap password and highlight credentials log If the operator never completed the forced-change flow, the plaintext bootstrap password was unrecoverable on the next start (only the hash remained on disk, and the prior log line was likely gone). Now we detect a persisted state with mustChangePassword=true at load time and generate a fresh CSPRNG password so the operator can actually log in. The initial-credentials log block is also wrapped with separators and a bilingual notice so it stands out at boot. The 'initial credentials: user=admin password=%s' line is preserved verbatim because third-party launchers parse it. --- packages/core/src/webui/auth.ts | 11 +++++++++++ packages/core/src/webui/server.ts | 8 +++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/packages/core/src/webui/auth.ts b/packages/core/src/webui/auth.ts index 79226178..c8f6732e 100644 --- a/packages/core/src/webui/auth.ts +++ b/packages/core/src/webui/auth.ts @@ -151,6 +151,17 @@ export class WebuiAuth { const raw = fs.readFileSync(WEBUI_CONFIG_PATH, 'utf8'); const parsed = JSON.parse(raw) as unknown; if (isValidState(parsed)) { + if (parsed.mustChangePassword) { + // Previous start generated a bootstrap password but the operator + // never completed the forced-change flow. The plaintext is gone + // (only the hash is on disk, and the log line from last run may + // be lost), so rotate to a fresh CSPRNG password they can see. + const initialPassword = randomBytes(8).toString('hex'); + const state = generateInitialState(initialPassword); + atomicWrite(state); + log.warn('previous bootstrap password was never rotated; regenerated a new one'); + return new WebuiAuth(state, initialPassword, false); + } return new WebuiAuth(parsed, null, false); } log.error('webui.json schema invalid; backing up and regenerating credentials'); diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index c71a5d11..0c704a19 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -98,8 +98,14 @@ export async function initWebUI( log.warn('dev mode enabled: password=%s', WebuiAuth.devPassword); log.warn('dev mode skips config/webui.json and password rotation'); } else if (initialPassword) { + log.info('════════════════════════════════════════════════════════════════'); + log.info(' ★ WebUI 初始登录凭据 / Initial WebUI Credentials ★'); + log.info(' 请立即登录并修改密码 —— 关闭程序后此密码无法找回。'); + log.info(' 若跳过初始改密,下次启动将自动生成新的随机密码。'); + log.info(' Log in and change the password now; it will not be shown again.'); + log.info('────────────────────────────────────────────────────────────────'); log.info('initial credentials: user=admin password=%s', initialPassword); - log.info('password change required after first login'); + log.info('════════════════════════════════════════════════════════════════'); } else if (auth.mustChangePassword()) { log.warn('password change is still required'); } From 90884dfbb173068d8b92652a6f29db163a49f055 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 19:28:58 +0800 Subject: [PATCH 23/51] chore(release): v1.8.2 --- package.json | 2 +- packages/core/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 57eb5c9f..3de5e909 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.8.1", + "version": "1.8.2", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index aa65b55c..858d38b5 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.8.1", + "version": "1.8.2", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 3cfbfdd6..aed52074 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.8.1", + "version": "1.8.2", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 1e072aee..0cbb085e 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.1", + "version": "1.8.2", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 91326c8d..5a0a7d4b 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.1", + "version": "1.8.2", "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 6a11dc09..cd32d250 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.8.1", + "version": "1.8.2", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 17f0f9c4..086dd109 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.8.1", + "version": "1.8.2", "type": "module", "scripts": { "dev": "vite", From 360fe8bd49266d0f8b246f0f33ac9c9f299074dd Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Sun, 17 May 2026 23:47:12 +0800 Subject: [PATCH 24/51] fix(forward): carry image/video in private merged forward MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit For a private send_private_forward_msg, the inner image/record/video needs an OIDB upload scene — but uploadForwardNodes never received the recipient, so the SendContext fell back to {bridge} only and the element builder threw "private image target uid is missing". Plumb userId through uploadForwardNodes → buildForwardPushBody and, when the nodes contain media, resolve it to a uid via bridge.resolveUserUid() once up-front. Group forwards are unchanged (they already passed groupId). Mirrors NapCat's design where the destination peer is threaded all the way down to createSendElements. --- packages/core/src/bridge/actions/forward.ts | 33 +++++++++++++++++-- packages/core/src/bridge/bridge-interface.ts | 2 +- packages/core/src/bridge/bridge.ts | 2 +- .../src/onebot/modules/message-actions.ts | 5 ++- 4 files changed, 36 insertions(+), 6 deletions(-) diff --git a/packages/core/src/bridge/actions/forward.ts b/packages/core/src/bridge/actions/forward.ts index 6558c4b7..9ade79e2 100644 --- a/packages/core/src/bridge/actions/forward.ts +++ b/packages/core/src/bridge/actions/forward.ts @@ -29,14 +29,21 @@ async function buildForwardPushBody( bridge: Bridge, node: ForwardNodePayload, groupId?: number, + userUid?: string, ): Promise> { const fromUin = node.userUin > 0 ? node.userUin : toInt(bridge.identity.uin); if (fromUin <= 0) throw new Error('forward node user uin is invalid'); const nickname = node.nickname.trim() || String(fromUin); + // image/record/video upload inside a forward node must be scoped to the + // forward's recipient: group → groupId, private → recipient uid. + // Without this the OIDB upload (0x11c4/0x11c5) has no scene and the + // element builder throws "private image target uid is missing". const sendCtx = groupId !== undefined ? { bridge, groupId } - : { bridge }; + : userUid + ? { bridge, userUid } + : { bridge }; const elems = await buildSendElems(node.elements, sendCtx); const now = Math.floor(Date.now() / 1000); const random = Math.floor(Math.random() * 0x7fffffff) >>> 0; @@ -66,12 +73,32 @@ async function buildForwardPushBody( }; } -export async function uploadForwardNodes(bridge: Bridge, nodes: ForwardNodePayload[], groupId?: number): Promise { +export async function uploadForwardNodes( + bridge: Bridge, + nodes: ForwardNodePayload[], + groupId?: number, + userId?: number, +): Promise { if (!Array.isArray(nodes) || nodes.length === 0) { throw new Error('forward nodes are required'); } - const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId))); + // For a private forward to `userId`, any image/record/video inside a node + // needs the recipient's uid as upload scene. Resolve it once up-front, + // and only when at least one node actually contains media (saves an RPC + // for text-only forwards). + let userUid: string | undefined; + if (groupId === undefined && userId !== undefined && userId > 0) { + const hasMedia = nodes.some(node => node.elements.some( + e => e.type === 'image' || e.type === 'record' || e.type === 'video', + )); + if (hasMedia) { + const resolved = await bridge.resolveUserUid(userId); + if (resolved) userUid = resolved; + } + } + + const msgBody = await Promise.all(nodes.map(node => buildForwardPushBody(bridge, node, groupId, userUid))); const longMsgResult = protoEncode({ action: [ { diff --git a/packages/core/src/bridge/bridge-interface.ts b/packages/core/src/bridge/bridge-interface.ts index a459b8f8..1a73fa31 100644 --- a/packages/core/src/bridge/bridge-interface.ts +++ b/packages/core/src/bridge/bridge-interface.ts @@ -92,7 +92,7 @@ export interface BridgeInterface { fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>; // ─── Forward ─── - uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise; + uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise; fetchForwardNodes(resId: string): Promise; // ─── Message ops ─── diff --git a/packages/core/src/bridge/bridge.ts b/packages/core/src/bridge/bridge.ts index acdbcc1f..a3a64ebb 100644 --- a/packages/core/src/bridge/bridge.ts +++ b/packages/core/src/bridge/bridge.ts @@ -454,7 +454,7 @@ export class Bridge implements BridgeInterface { async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise { return fetchPrivatePttUrlByNode_(this, node); } async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise { return fetchGroupVideoUrlByNode_(this, groupId, node); } async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise { return fetchPrivateVideoUrlByNode_(this, node); } - async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise { return uploadForwardNodes_(this, nodes, groupId); } + async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise { return uploadForwardNodes_(this, nodes, groupId, userId); } async fetchForwardNodes(resId: string): Promise { return fetchForwardNodes_(this, resId); } async deleteGroupFile(groupId: number, fileId: string): Promise { return deleteGroupFile_(this, groupId, fileId); } async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); } diff --git a/packages/core/src/onebot/modules/message-actions.ts b/packages/core/src/onebot/modules/message-actions.ts index 5a847f9c..ffee4639 100644 --- a/packages/core/src/onebot/modules/message-actions.ts +++ b/packages/core/src/onebot/modules/message-actions.ts @@ -241,7 +241,10 @@ export async function sendPrivateForwardMessage( meta?: ForwardPreviewMeta, ): Promise<{ messageId: number; forwardId: string }> { const nodes = await parseForwardNodes(ref, messages); - const forwardId = await ref.bridge.uploadForwardNodes(nodes); + // userId is plumbed through so inner image/record/video can be uploaded + // under the recipient's scene (otherwise the OIDB private-image upload + // has no target uid and the element builder bails). + const forwardId = await ref.bridge.uploadForwardNodes(nodes, undefined, userId); const previewElement = buildForwardPreviewElement(forwardId, nodes, false, meta); const receipt = await ref.bridge.sendPrivateMessage(userId, [previewElement]); const messageId = hashMessageIdInt32(receipt.sequence, userId, PRIVATE_MESSAGE_EVENT); From 82b52a3b2d5c737fcce7d14616f359ade3cf1af8 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 00:10:12 +0800 Subject: [PATCH 25/51] update README --- README.md | 132 +++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 120 insertions(+), 12 deletions(-) diff --git a/README.md b/README.md index d28a6cd0..739c313b 100644 --- a/README.md +++ b/README.md @@ -1,22 +1,130 @@ -# ❄️ SnowLuma -> Next Remote Protocol Framework. +

❄️ SnowLuma

+

+ Next Remote Protocol Framework. +

-## 关于项目 -项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。 +

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

+ +

+ Releases · + Issues · + QQ 群 · + Telegram +

+ +--- + +## 简介 + +SnowLuma 在 QQ 客户端与生态侧之间承担协议转换工作,向上以 [OneBot v11](https://github.com/botuniverse/onebot-11) 标准协议暴露能力。Bridge 层负责会话与事件枢纽,再通过 WebSocket / HTTP / WebUI 等多种适配器对外提供接入。 + +项目持续迭代中,稳定版本通过 [Releases](https://github.com/SnowLuma/SnowLuma/releases) 发布。 + +## 特性 + +- **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,跨重启可用。 + +## 快速开始 + +下载预构建发布包: + +```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/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 +``` ## 鸣谢 -[LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) - Proto -[NapCatQQ](https://github.com/NapNeko/NapCatQQ) - Scaner/Packet +- [LagrangeV2](https://github.com/LagrangeDev/LagrangeV2) —— Proto 定义参考。 +- [NapCatQQ](https://github.com/NapNeko/NapCatQQ) —— Scanner 与 Packet 处理实现参考。 -## 辅助编程 +## 贡献者 -推荐 Opus4.6 + Gemini3.1pro 对本项目辅助开发 +感谢每一位为 SnowLuma 提交过代码的伙伴。 -本项目大量使用Ai技术。 + + Contributors + -## 加入我们 -[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe) +## Star 趋势 -[SnowLuma-TG](https://t.me/napcatqq) \ No newline at end of file + + + + + 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) From c6f4d5c5a277bc82329da4b14c120ae91c3680b5 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 00:10:43 +0800 Subject: [PATCH 26/51] chore(release): v1.8.3 --- package.json | 2 +- packages/core/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 3de5e909..49acb6e9 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.8.2", + "version": "1.8.3", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index 858d38b5..dcfbb1bb 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.8.2", + "version": "1.8.3", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index aed52074..08f97c34 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.8.2", + "version": "1.8.3", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 0cbb085e..238c3dcd 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.2", + "version": "1.8.3", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 5a0a7d4b..7baf9f05 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.2", + "version": "1.8.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 cd32d250..3245ccc5 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.8.2", + "version": "1.8.3", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 086dd109..b5352ec2 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.8.2", + "version": "1.8.3", "type": "module", "scripts": { "dev": "vite", From 51f46e15fdd160ea56e3d1cad2769203c419fd95 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 00:44:30 +0800 Subject: [PATCH 27/51] feat(logger): add file transport with daily rotation and size cap Adds a hand-rolled FileTransport that fans out every log line (debug and up, regardless of console filter) to ./logs/snowluma-YYYY-MM-DD.log. When the current file exceeds the configurable size cap it rolls into snowluma-YYYY-MM-DD.1.log, and files older than the retention window are unlinked at startup and on each day rollover. Config (all env, no settings.json): - SNOWLUMA_LOG_FILE 0 to disable file output (default: on) - SNOWLUMA_LOG_DIR output directory (default: ./logs) - SNOWLUMA_LOG_MAX_MB per-file cap, MB (default: 50) - SNOWLUMA_LOG_RETAIN_DAYS retention window (default: 7) closeLogger() awaits the WriteStream's finish event; SIGINT and SIGTERM handlers now await it before process.exit so the buffer makes it to disk. vitest config sets SNOWLUMA_LOG_FILE=0 to keep the suite from polluting cwd; the new tests under tests/log-file-transport.test.ts flip it back on per-test against a tmpdir. --- packages/core/src/index.ts | 17 +- packages/core/src/utils/log-file-transport.ts | 236 ++++++++++++++++++ packages/core/src/utils/logger.ts | 42 +++- .../core/tests/log-file-transport.test.ts | 159 ++++++++++++ packages/core/vitest.config.ts | 9 +- 5 files changed, 445 insertions(+), 18 deletions(-) create mode 100644 packages/core/src/utils/log-file-transport.ts create mode 100644 packages/core/tests/log-file-transport.test.ts diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index c69b3ca8..413024bc 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,7 +1,7 @@ import { BridgeManager } from './bridge/manager'; import { OneBotManager } from './onebot/manager'; import { loadRuntimeConfig } from './common/runtime'; -import { createLogger } from './utils/logger'; +import { closeLogger, createLogger } from './utils/logger'; import { HookManager } from './hook/hook-manager'; const runtimeConfig = loadRuntimeConfig(); @@ -38,13 +38,17 @@ async function main() { } } - // Graceful shutdown - process.on('SIGINT', () => { - log.warn('Shutting down...'); + // Graceful shutdown: dispose managers, await log flush, then exit. + // SIGINT (Ctrl-C) and SIGTERM (Docker/systemd) take the same path. + const shutdown = (signal: string) => async () => { + log.warn(`Shutting down (${signal})...`); oneBotManager.dispose(); hookManager.dispose(); + await closeLogger(); process.exit(0); - }); + }; + process.on('SIGINT', shutdown('SIGINT')); + process.on('SIGTERM', shutdown('SIGTERM')); } function resolveAutoLoad(fromConfig: boolean | undefined): boolean { @@ -57,7 +61,8 @@ function resolveAutoLoad(fromConfig: boolean | undefined): boolean { return fromConfig === true; } -main().catch((error) => { +main().catch(async (error) => { log.error(error instanceof Error ? (error.stack ?? error.message) : String(error)); + await closeLogger(); process.exit(1); }); diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/core/src/utils/log-file-transport.ts new file mode 100644 index 00000000..211a126d --- /dev/null +++ b/packages/core/src/utils/log-file-transport.ts @@ -0,0 +1,236 @@ +// File transport for the SnowLuma logger. +// +// Writes plain text (ANSI stripped) to: +// /snowluma-YYYY-MM-DD.log +// with daily rollover and a per-file size cap. When the cap is hit the +// in-flight file is closed and writes continue in +// snowluma-YYYY-MM-DD.1.log, .2.log, ... +// at the same date. Files older than the retain window are unlinked on +// startup and again on each day rollover. +// +// Disabled via SNOWLUMA_LOG_FILE=0. Any I/O failure during init or write +// degrades silently to console-only; we deliberately do NOT use the +// logger from inside this module to avoid recursion. + +import fs from 'node:fs'; +import path from 'node:path'; + +const DEFAULT_DIR = 'logs'; +const DEFAULT_MAX_MB = 50; +const DEFAULT_RETAIN_DAYS = 7; +const FILE_PREFIX = 'snowluma-'; +const FILE_SUFFIX = '.log'; +const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/; + +// eslint-disable-next-line no-control-regex +const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g; +// eslint-disable-next-line no-control-regex +const CTRL_RE = /[\x00-\x1A\x1C-\x1F\x7F]/g; + +function parsePositiveInt(v: string | undefined, dflt: number): number { + if (!v) return dflt; + const n = Number.parseInt(v, 10); + return Number.isFinite(n) && n > 0 ? n : dflt; +} + +function todayString(d: Date = new Date()): string { + const y = d.getFullYear(); + const m = String(d.getMonth() + 1).padStart(2, '0'); + const day = String(d.getDate()).padStart(2, '0'); + return `${y}-${m}-${day}`; +} + +function dateOf(s: string): Date { + const [y, m, d] = s.split('-').map((v) => Number.parseInt(v, 10)); + return new Date(y!, m! - 1, d!); +} + +function stripAnsi(line: string): string { + return line.replace(ANSI_RE, '').replace(CTRL_RE, ''); +} + +interface OpenFile { + stream: fs.WriteStream; + bytes: number; + date: string; + splitIndex: number; + path: string; +} + +export class FileTransport { + private disabled = false; + private readonly dir: string; + private readonly maxBytes: number; + private readonly retainDays: number; + private shared: OpenFile | null = null; + + constructor() { + this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR; + this.maxBytes = + parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024; + this.retainDays = parsePositiveInt( + process.env.SNOWLUMA_LOG_RETAIN_DAYS, + DEFAULT_RETAIN_DAYS, + ); + + if (process.env.SNOWLUMA_LOG_FILE === '0') { + this.disabled = true; + return; + } + + try { + fs.mkdirSync(this.dir, { recursive: true }); + } catch (err) { + this.disabled = true; + // Direct stderr — logger would recurse. + // eslint-disable-next-line no-console + console.error( + `[logger] failed to create log dir ${this.dir}: ${err instanceof Error ? err.message : String(err)}`, + ); + return; + } + + this.cleanup(); + } + + /** True when file output is suppressed (env disable or init failure). */ + get isDisabled(): boolean { + return this.disabled; + } + + /** Current target file path (or null if disabled / not yet opened). */ + get currentPath(): string | null { + return this.shared?.path ?? null; + } + + write(line: string): void { + if (this.disabled) return; + const today = todayString(); + const data = stripAnsi(line) + '\n'; + const bytes = Buffer.byteLength(data, 'utf8'); + + this.ensureForToday(today); + if (!this.shared) return; + + if (this.shared.bytes + bytes > this.maxBytes && this.shared.bytes > 0) { + this.rotateBySize(); + if (!this.shared) return; + } + + this.shared.stream.write(data); + this.shared.bytes += bytes; + } + + close(): Promise { + const f = this.shared; + this.shared = null; + if (!f) return Promise.resolve(); + return new Promise((resolve) => { + try { + f.stream.end(() => resolve()); + } catch { + resolve(); + } + }); + } + + private ensureForToday(today: string): void { + if (this.shared && this.shared.date === today) return; + + if (this.shared) { + try { + this.shared.stream.end(); + } catch { + /* ignore */ + } + this.shared = null; + // Day rolled over — also a good moment to evict stale files. + this.cleanup(); + } + + // Find the highest existing split index for today and continue appending + // to it (so multiple process starts on the same day share files). + let idx = 0; + while (fs.existsSync(this.pathFor(today, idx + 1))) idx++; + this.shared = this.openFile(today, idx); + } + + private rotateBySize(): void { + if (!this.shared) return; + const date = this.shared.date; + try { + this.shared.stream.end(); + } catch { + /* ignore */ + } + let next = this.shared.splitIndex + 1; + while (fs.existsSync(this.pathFor(date, next))) next++; + this.shared = this.openFile(date, next); + } + + private openFile(date: string, splitIndex: number): OpenFile | null { + const p = this.pathFor(date, splitIndex); + try { + let bytes = 0; + try { + bytes = fs.statSync(p).size; + } catch { + /* file doesn't exist yet */ + } + const stream = fs.createWriteStream(p, { flags: 'a' }); + stream.on('error', (err) => { + // eslint-disable-next-line no-console + console.error(`[logger] file write error on ${p}: ${err.message}`); + }); + return { stream, bytes, date, splitIndex, path: p }; + } catch (err) { + // eslint-disable-next-line no-console + console.error( + `[logger] failed to open log file ${p}: ${err instanceof Error ? err.message : String(err)}`, + ); + return null; + } + } + + private pathFor(date: string, splitIndex: number): string { + const tail = splitIndex > 0 ? `.${splitIndex}` : ''; + return path.join(this.dir, `${FILE_PREFIX}${date}${tail}${FILE_SUFFIX}`); + } + + private cleanup(): void { + let entries: string[]; + try { + entries = fs.readdirSync(this.dir); + } catch { + return; + } + const retainMs = this.retainDays * 24 * 60 * 60 * 1000; + const cutoff = Date.now() - retainMs; + for (const name of entries) { + const m = FILE_RE.exec(name); + if (!m) continue; + const dateStr = m[1]!; + const fileDate = dateOf(dateStr); + if (fileDate.getTime() < cutoff) { + try { + fs.unlinkSync(path.join(this.dir, name)); + } catch { + /* ignore */ + } + } + } + } +} + +let singleton: FileTransport | null = null; + +export function getFileTransport(): FileTransport { + if (!singleton) singleton = new FileTransport(); + return singleton; +} + +/** Reset state between tests. Closes the active file handle. */ +export async function _resetFileTransportForTesting(): Promise { + if (singleton) await singleton.close(); + singleton = null; +} diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts index 534bb7b0..a2c2b411 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -1,4 +1,5 @@ import { format } from 'util'; +import { getFileTransport } from './log-file-transport'; type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error'; @@ -94,7 +95,9 @@ function render(level: LogLevel, scope: string, args: unknown[]): string { } function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { - if (!shouldLog(level)) return; + // Console / subscriber level filter. File output is debug-and-up always; + // see log-file-transport.ts. + const passesConsole = shouldLog(level); const message = format(...args); const line = render(level, options.scope, args); const entry: LogEntry = { @@ -105,16 +108,33 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { message, line, }; - logEntries.push(entry); - if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift(); - for (const subscriber of logSubscribers) subscriber(entry); - const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; - // Strip ASCII control characters before writing to terminal to prevent - // BEL (0x07) in user-provided strings (e.g. group member names) from - // triggering Windows system beep sounds. ESC (0x1B) is preserved so the - // ANSI color sequences emitted by render() actually reach the terminal. - // eslint-disable-next-line no-control-regex - stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); + + if (passesConsole) { + logEntries.push(entry); + if (logEntries.length > MAX_LOG_ENTRIES) logEntries.shift(); + for (const subscriber of logSubscribers) subscriber(entry); + const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; + // Strip ASCII control characters before writing to terminal to prevent + // BEL (0x07) in user-provided strings (e.g. group member names) from + // triggering Windows system beep sounds. ESC (0x1B) is preserved so the + // ANSI color sequences emitted by render() actually reach the terminal. + // eslint-disable-next-line no-control-regex + stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); + } + + // File transport always sees every level (debug-and-up) for post-mortem + // value; ANSI stripping happens inside the transport. + getFileTransport().write(line); +} + +/** + * Flush and close the underlying log file. Call from shutdown hooks + * (SIGINT / SIGTERM / uncaughtException) so the WriteStream's internal + * buffer makes it to disk. Returns a promise that resolves once the OS + * has finalized the write. + */ +export function closeLogger(): Promise { + return getFileTransport().close(); } export function getRecentLogs(limit = 300): LogEntry[] { diff --git a/packages/core/tests/log-file-transport.test.ts b/packages/core/tests/log-file-transport.test.ts new file mode 100644 index 00000000..b07c6dcb --- /dev/null +++ b/packages/core/tests/log-file-transport.test.ts @@ -0,0 +1,159 @@ +// Tests for the file transport that backs the SnowLuma logger. +// Each test gets its own tmp dir and a fresh FileTransport so env / state +// from one test never bleeds into another. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { FileTransport } from '../src/utils/log-file-transport'; + +let tmpDir: string; +const ENV_KEYS = [ + 'SNOWLUMA_LOG_FILE', + 'SNOWLUMA_LOG_DIR', + 'SNOWLUMA_LOG_MAX_MB', + 'SNOWLUMA_LOG_RETAIN_DAYS', +] as const; +const savedEnv: Record = {}; + +function setEnv(env: Partial>): void { + for (const [k, v] of Object.entries(env)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } +} + +function listLogFiles(dir: string): string[] { + return fs.readdirSync(dir).filter((f) => f.endsWith('.log')).sort(); +} + +beforeEach(() => { + for (const k of ENV_KEYS) savedEnv[k] = process.env[k]; + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-log-')); + setEnv({ + SNOWLUMA_LOG_DIR: tmpDir, + SNOWLUMA_LOG_FILE: '1', + SNOWLUMA_LOG_MAX_MB: '1', + SNOWLUMA_LOG_RETAIN_DAYS: '7', + }); +}); + +afterEach(() => { + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } + fs.rmSync(tmpDir, { recursive: true, force: true }); + vi.useRealTimers(); +}); + +describe('FileTransport', () => { + it('creates today\'s file and writes a single line', async () => { + const t = new FileTransport(); + t.write('hello world'); + await t.close(); + + const files = listLogFiles(tmpDir); + expect(files).toHaveLength(1); + expect(files[0]).toMatch(/^snowluma-\d{4}-\d{2}-\d{2}\.log$/); + expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')).toBe('hello world\n'); + }); + + it('strips ANSI color escapes and ASCII control chars before writing', async () => { + const t = new FileTransport(); + t.write('\x1b[36mINFO\x1b[0m \x07[Bridge] msg'); + await t.close(); + + const [file] = listLogFiles(tmpDir); + expect(fs.readFileSync(path.join(tmpDir, file!), 'utf8')).toBe('INFO [Bridge] msg\n'); + }); + + it('rolls into a .1 file when the current file exceeds the size cap', async () => { + // 1MB cap from beforeEach. Write ~2 MB to force a single rotation. + const t = new FileTransport(); + const oneKB = 'x'.repeat(1023); // +1 byte newline = 1024 + for (let i = 0; i < 2048; i++) t.write(oneKB); + await t.close(); + + const files = listLogFiles(tmpDir); + expect(files.length).toBeGreaterThanOrEqual(2); + const base = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.log$/.test(f)); + const split = files.find((f) => /snowluma-\d{4}-\d{2}-\d{2}\.1\.log$/.test(f)); + expect(base).toBeDefined(); + expect(split).toBeDefined(); + }); + + it('opens a new file when the day rolls over mid-process', async () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date(2026, 4, 18, 23, 59, 0)); + const t = new FileTransport(); + t.write('day-one line'); + vi.setSystemTime(new Date(2026, 4, 19, 0, 0, 1)); + t.write('day-two line'); + await t.close(); + + const files = listLogFiles(tmpDir); + expect(files).toContain('snowluma-2026-05-18.log'); + expect(files).toContain('snowluma-2026-05-19.log'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-18.log'), 'utf8')) + .toContain('day-one line'); + expect(fs.readFileSync(path.join(tmpDir, 'snowluma-2026-05-19.log'), 'utf8')) + .toContain('day-two line'); + }); + + it('deletes files older than the retention window on startup', async () => { + const stalePath = path.join(tmpDir, 'snowluma-2020-01-01.log'); + fs.writeFileSync(stalePath, 'stale\n'); + const t = new FileTransport(); + t.write('fresh'); + await t.close(); + + expect(fs.existsSync(stalePath)).toBe(false); + }); + + it('keeps files inside the retention window', async () => { + const recent = new Date(); + recent.setDate(recent.getDate() - 2); + const recentName = `snowluma-${recent.getFullYear()}-${String(recent.getMonth() + 1).padStart(2, '0')}-${String(recent.getDate()).padStart(2, '0')}.log`; + const recentPath = path.join(tmpDir, recentName); + fs.writeFileSync(recentPath, 'recent\n'); + + const t = new FileTransport(); + await t.close(); + + expect(fs.existsSync(recentPath)).toBe(true); + }); + + it('SNOWLUMA_LOG_FILE=0 suppresses all file output', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + const t = new FileTransport(); + t.write('should not be written'); + await t.close(); + + expect(t.isDisabled).toBe(true); + expect(listLogFiles(tmpDir)).toHaveLength(0); + }); + + it('appends to the existing today file across restarts', async () => { + const a = new FileTransport(); + a.write('before restart'); + await a.close(); + + const b = new FileTransport(); + b.write('after restart'); + await b.close(); + + const files = listLogFiles(tmpDir); + expect(files).toHaveLength(1); + expect(fs.readFileSync(path.join(tmpDir, files[0]!), 'utf8')) + .toBe('before restart\nafter restart\n'); + }); + + it('exposes the current file path while open', () => { + const t = new FileTransport(); + t.write('x'); + expect(t.currentPath).not.toBeNull(); + expect(t.currentPath!).toMatch(/snowluma-\d{4}-\d{2}-\d{2}\.log$/); + }); +}); diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts index 64bbf402..4870d273 100644 --- a/packages/core/vitest.config.ts +++ b/packages/core/vitest.config.ts @@ -12,6 +12,13 @@ export default defineConfig({ }, test: { include: ['tests/**/*.test.ts'], - environment: 'node' + environment: 'node', + // Suppress the logger's file transport during tests so the suite + // doesn't litter cwd with logs/snowluma-*.log files. Tests that + // explicitly cover file output set their own SNOWLUMA_LOG_FILE='1' + // + SNOWLUMA_LOG_DIR=. + env: { + SNOWLUMA_LOG_FILE: '0' + } } }); From 93b9b03667710a46af615872d6e7f163b4670cde Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 00:50:15 +0800 Subject: [PATCH 28/51] feat(logger): add .child({ uin }) API and per-UIN file fan-out Logger now supports deriving a UIN-bound child: const log = createLogger('Bridge'); this.log = log.child({ uin: this.uin }); The child stamps a fixed-width [UIN] slot into rendered lines so the [Scope] column stays vertically aligned, and routes the same line to a per-UIN sub-file: logs/snowluma-YYYY-MM-DD.log (shared, all UINs) logs//snowluma-YYYY-MM-DD.log (per-account) Both pathways share daily rollover, size cap, and retention. LogEntry now carries uin so SSE subscribers (WebUI) can filter later. Other meta keys passed to child() are preserved in opts.meta for forward compat (requestId / traceId etc.) but not rendered yet. Module-level callers are unchanged; no callsites migrated in this PR. SNOWLUMA_LOG_PER_UIN=0 disables the per-account sub-file while keeping the shared one. --- packages/core/src/utils/log-file-transport.ts | 177 +++++++++++------ packages/core/src/utils/logger.ts | 69 +++++-- packages/core/tests/logger.test.ts | 180 ++++++++++++++++++ 3 files changed, 351 insertions(+), 75 deletions(-) create mode 100644 packages/core/tests/logger.test.ts diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/core/src/utils/log-file-transport.ts index 211a126d..0b5b6d8c 100644 --- a/packages/core/src/utils/log-file-transport.ts +++ b/packages/core/src/utils/log-file-transport.ts @@ -1,16 +1,20 @@ // File transport for the SnowLuma logger. // // Writes plain text (ANSI stripped) to: -// /snowluma-YYYY-MM-DD.log -// with daily rollover and a per-file size cap. When the cap is hit the -// in-flight file is closed and writes continue in +// /snowluma-YYYY-MM-DD.log (shared, all UINs) +// //snowluma-YYYY-MM-DD.log (per-account) +// +// Both pathways use the same daily rotation + per-file size cap. When the +// cap is hit the in-flight file is closed and writes continue in // snowluma-YYYY-MM-DD.1.log, .2.log, ... // at the same date. Files older than the retain window are unlinked on -// startup and again on each day rollover. +// startup and on each day rollover. // -// Disabled via SNOWLUMA_LOG_FILE=0. Any I/O failure during init or write -// degrades silently to console-only; we deliberately do NOT use the -// logger from inside this module to avoid recursion. +// Disabled via SNOWLUMA_LOG_FILE=0. Per-UIN sub-files are additionally +// gated by SNOWLUMA_LOG_PER_UIN=0 (still keeps the shared file). Any I/O +// failure during init or write degrades silently to console-only — we +// deliberately do NOT use the logger from inside this module to avoid +// recursion. import fs from 'node:fs'; import path from 'node:path'; @@ -57,73 +61,59 @@ interface OpenFile { path: string; } -export class FileTransport { +/** + * Owns one output directory: keeps at most one open WriteStream, handles + * daily rollover, per-file size cap, and retention cleanup. The shared + * top-level dir uses one of these; each per-UIN sub-dir gets its own. + */ +class FileWriter { private disabled = false; - private readonly dir: string; - private readonly maxBytes: number; - private readonly retainDays: number; - private shared: OpenFile | null = null; - - constructor() { - this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR; - this.maxBytes = - parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024; - this.retainDays = parsePositiveInt( - process.env.SNOWLUMA_LOG_RETAIN_DAYS, - DEFAULT_RETAIN_DAYS, - ); - - if (process.env.SNOWLUMA_LOG_FILE === '0') { - this.disabled = true; - return; - } + private file: OpenFile | null = null; + constructor( + private readonly dir: string, + private readonly maxBytes: number, + private readonly retainDays: number, + ) { try { - fs.mkdirSync(this.dir, { recursive: true }); + fs.mkdirSync(dir, { recursive: true }); } catch (err) { this.disabled = true; - // Direct stderr — logger would recurse. // eslint-disable-next-line no-console console.error( - `[logger] failed to create log dir ${this.dir}: ${err instanceof Error ? err.message : String(err)}`, + `[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`, ); return; } - this.cleanup(); } - /** True when file output is suppressed (env disable or init failure). */ get isDisabled(): boolean { return this.disabled; } - /** Current target file path (or null if disabled / not yet opened). */ get currentPath(): string | null { - return this.shared?.path ?? null; + return this.file?.path ?? null; } - write(line: string): void { + write(data: string, bytes: number): void { if (this.disabled) return; const today = todayString(); - const data = stripAnsi(line) + '\n'; - const bytes = Buffer.byteLength(data, 'utf8'); - this.ensureForToday(today); - if (!this.shared) return; + if (!this.file) return; - if (this.shared.bytes + bytes > this.maxBytes && this.shared.bytes > 0) { + if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) { this.rotateBySize(); - if (!this.shared) return; + if (!this.file) return; } - this.shared.stream.write(data); - this.shared.bytes += bytes; + this.file.stream.write(data); + this.file.bytes += bytes; } close(): Promise { - const f = this.shared; - this.shared = null; + const f = this.file; + this.file = null; if (!f) return Promise.resolve(); return new Promise((resolve) => { try { @@ -135,37 +125,36 @@ export class FileTransport { } private ensureForToday(today: string): void { - if (this.shared && this.shared.date === today) return; + if (this.file && this.file.date === today) return; - if (this.shared) { + if (this.file) { try { - this.shared.stream.end(); + this.file.stream.end(); } catch { /* ignore */ } - this.shared = null; - // Day rolled over — also a good moment to evict stale files. + this.file = null; this.cleanup(); } - // Find the highest existing split index for today and continue appending - // to it (so multiple process starts on the same day share files). + // Resume from the highest existing split index for today (so two + // process starts on the same day share files / don't clobber). let idx = 0; while (fs.existsSync(this.pathFor(today, idx + 1))) idx++; - this.shared = this.openFile(today, idx); + this.file = this.openFile(today, idx); } private rotateBySize(): void { - if (!this.shared) return; - const date = this.shared.date; + if (!this.file) return; + const date = this.file.date; try { - this.shared.stream.end(); + this.file.stream.end(); } catch { /* ignore */ } - let next = this.shared.splitIndex + 1; + let next = this.file.splitIndex + 1; while (fs.existsSync(this.pathFor(date, next))) next++; - this.shared = this.openFile(date, next); + this.file = this.openFile(date, next); } private openFile(date: string, splitIndex: number): OpenFile | null { @@ -210,8 +199,7 @@ export class FileTransport { const m = FILE_RE.exec(name); if (!m) continue; const dateStr = m[1]!; - const fileDate = dateOf(dateStr); - if (fileDate.getTime() < cutoff) { + if (dateOf(dateStr).getTime() < cutoff) { try { fs.unlinkSync(path.join(this.dir, name)); } catch { @@ -222,6 +210,75 @@ export class FileTransport { } } +export class FileTransport { + private readonly dir: string; + private readonly maxBytes: number; + private readonly retainDays: number; + private readonly enabled: boolean; + private readonly perUinEnabled: boolean; + private shared: FileWriter | null = null; + private perUin = new Map(); + + constructor() { + this.dir = process.env.SNOWLUMA_LOG_DIR || DEFAULT_DIR; + this.maxBytes = + parsePositiveInt(process.env.SNOWLUMA_LOG_MAX_MB, DEFAULT_MAX_MB) * 1024 * 1024; + this.retainDays = parsePositiveInt( + process.env.SNOWLUMA_LOG_RETAIN_DAYS, + DEFAULT_RETAIN_DAYS, + ); + this.enabled = process.env.SNOWLUMA_LOG_FILE !== '0'; + this.perUinEnabled = process.env.SNOWLUMA_LOG_PER_UIN !== '0'; + + if (this.enabled) { + const w = new FileWriter(this.dir, this.maxBytes, this.retainDays); + this.shared = w.isDisabled ? null : w; + } + } + + /** True when no file output will happen (env disable or init failure). */ + get isDisabled(): boolean { + return !this.shared; + } + + /** Current shared-file path (or null if disabled / not yet opened). */ + get currentPath(): string | null { + return this.shared?.currentPath ?? null; + } + + /** Path of the per-UIN file for the given UIN, if open. */ + perUinPath(uin: number): string | null { + return this.perUin.get(uin)?.currentPath ?? null; + } + + write(line: string, uin?: number): void { + if (!this.shared) return; + const data = stripAnsi(line) + '\n'; + const bytes = Buffer.byteLength(data, 'utf8'); + + this.shared.write(data, bytes); + + if (uin !== undefined && this.perUinEnabled) { + let w = this.perUin.get(uin); + if (!w) { + w = new FileWriter(path.join(this.dir, String(uin)), this.maxBytes, this.retainDays); + if (w.isDisabled) return; + this.perUin.set(uin, w); + } + w.write(data, bytes); + } + } + + async close(): Promise { + const closes: Promise[] = []; + if (this.shared) closes.push(this.shared.close()); + for (const w of this.perUin.values()) closes.push(w.close()); + this.shared = null; + this.perUin.clear(); + await Promise.all(closes); + } +} + let singleton: FileTransport | null = null; export function getFileTransport(): FileTransport { @@ -229,7 +286,7 @@ export function getFileTransport(): FileTransport { return singleton; } -/** Reset state between tests. Closes the active file handle. */ +/** Reset state between tests. Closes all active file handles. */ export async function _resetFileTransportForTesting(): Promise { if (singleton) await singleton.close(); singleton = null; diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts index a2c2b411..bb63fa0e 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -8,14 +8,26 @@ export interface LogEntry { time: string; level: LogLevel; scope: string; + /** QQ uin, when the source logger was derived via `.child({ uin })`. */ + uin?: number; message: string; line: string; } interface LogOptions { scope: string; + uin?: number; + /** Free-form meta carried across `.child(...)` calls. Currently only + * `uin` is rendered, but the bag is preserved for future fields + * (requestId / traceId / etc.). */ + meta?: Record; } +// Fixed-width slot for the UIN tag in rendered output so the [Scope] +// column stays vertically aligned across lines with and without a UIN. +// Width covers `[1234567890]` (12 chars); anything longer just won't pad. +const UIN_SLOT_WIDTH = 12; + const LEVEL_WEIGHT: Record = { debug: 10, info: 20, @@ -79,19 +91,26 @@ function currentTime(): string { return `${hh}:${mm}:${ss}`; } -function render(level: LogLevel, scope: string, args: unknown[]): string { +function render(level: LogLevel, options: LogOptions, args: unknown[]): string { const message = format(...args); const ts = currentTime(); const label = LEVEL_LABEL[level].padEnd(5, ' '); + const uinTag = options.uin !== undefined ? `[${options.uin}]` : ''; + const uinSlot = uinTag.padEnd(UIN_SLOT_WIDTH); if (!useColor()) { - return `${ts} ${label} [${scope}] ${message}`; + return `${ts} ${label} ${uinSlot} [${options.scope}] ${message}`; } const cTs = ansi(COLOR_DIM, ts); const cLabel = ansi(COLOR_CODE[level], label); - const cScope = ansi(COLOR_SCOPE, `[${scope}]`); - return `${cTs} ${cLabel} ${cScope} ${message}`; + // Pad first, then color only the visible tag so escape codes don't eat + // into the alignment width. + const cUin = uinTag + ? ansi(COLOR_DIM, uinTag) + ' '.repeat(UIN_SLOT_WIDTH - uinTag.length) + : ' '.repeat(UIN_SLOT_WIDTH); + const cScope = ansi(COLOR_SCOPE, `[${options.scope}]`); + return `${cTs} ${cLabel} ${cUin} ${cScope} ${message}`; } function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { @@ -99,12 +118,13 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { // see log-file-transport.ts. const passesConsole = shouldLog(level); const message = format(...args); - const line = render(level, options.scope, args); + const line = render(level, options, args); const entry: LogEntry = { id: nextLogId++, time: new Date().toISOString(), level, scope: options.scope, + ...(options.uin !== undefined ? { uin: options.uin } : {}), message, line, }; @@ -123,8 +143,9 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { } // File transport always sees every level (debug-and-up) for post-mortem - // value; ANSI stripping happens inside the transport. - getFileTransport().write(line); + // value; ANSI stripping happens inside the transport. UIN routes the + // line to its per-account sub-file in addition to the shared one. + getFileTransport().write(line, options.uin); } /** @@ -155,15 +176,33 @@ export interface Logger { success: (...args: unknown[]) => void; warn: (...args: unknown[]) => void; error: (...args: unknown[]) => void; + /** + * Derive a new logger that inherits this one's scope and carries + * additional metadata. Currently `uin` is the only key with rendering + * support (shown in the `[UIN]` slot and routed to a per-UIN file); + * other keys are preserved on the options bag for forward compat. + */ + child: (meta: { uin?: number; [k: string]: unknown }) => Logger; +} + +function makeLogger(opts: LogOptions): Logger { + return { + debug: (...args: unknown[]) => emit('debug', opts, args), + info: (...args: unknown[]) => emit('info', opts, args), + success: (...args: unknown[]) => emit('success', opts, args), + warn: (...args: unknown[]) => emit('warn', opts, args), + error: (...args: unknown[]) => emit('error', opts, args), + child: (meta) => { + const nextUin = typeof meta.uin === 'number' ? meta.uin : opts.uin; + return makeLogger({ + scope: opts.scope, + uin: nextUin, + meta: { ...(opts.meta ?? {}), ...meta }, + }); + }, + }; } export function createLogger(scope: string): Logger { - const options: LogOptions = { scope }; - return { - debug: (...args: unknown[]) => emit('debug', options, args), - info: (...args: unknown[]) => emit('info', options, args), - success: (...args: unknown[]) => emit('success', options, args), - warn: (...args: unknown[]) => emit('warn', options, args), - error: (...args: unknown[]) => emit('error', options, args), - }; + return makeLogger({ scope }); } diff --git a/packages/core/tests/logger.test.ts b/packages/core/tests/logger.test.ts new file mode 100644 index 00000000..7ac141ea --- /dev/null +++ b/packages/core/tests/logger.test.ts @@ -0,0 +1,180 @@ +// Tests for the core logger API: +// - createLogger() output shape (scope rendering) +// - .child({ uin }) derivation and the [UIN] slot in the rendered line +// - LogEntry.uin propagation to subscribers +// - File transport per-UIN fan-out (and the SNOWLUMA_LOG_PER_UIN=0 gate) +// +// We exercise the file transport via its real fs paths against tmpdirs +// so the test catches integration regressions, not just unit shape. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { createLogger, subscribeLogs, type LogEntry } from '../src/utils/logger'; +import { _resetFileTransportForTesting } from '../src/utils/log-file-transport'; + +let tmpDir: string; +const ENV_KEYS = [ + 'SNOWLUMA_LOG_FILE', + 'SNOWLUMA_LOG_PER_UIN', + 'SNOWLUMA_LOG_DIR', + 'SNOWLUMA_LOG_MAX_MB', + 'SNOWLUMA_LOG_RETAIN_DAYS', + 'SNOWLUMA_LOG_LEVEL', + 'NO_COLOR', +] as const; +const savedEnv: Record = {}; + +function setEnv(env: Partial>): void { + for (const [k, v] of Object.entries(env)) { + if (v === undefined) delete process.env[k]; + else process.env[k] = v; + } +} + +beforeEach(async () => { + for (const k of ENV_KEYS) savedEnv[k] = process.env[k]; + tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-logger-')); + setEnv({ + SNOWLUMA_LOG_DIR: tmpDir, + SNOWLUMA_LOG_FILE: '1', + SNOWLUMA_LOG_PER_UIN: '1', + SNOWLUMA_LOG_MAX_MB: '5', + SNOWLUMA_LOG_RETAIN_DAYS: '7', + NO_COLOR: '1', + }); + await _resetFileTransportForTesting(); +}); + +afterEach(async () => { + await _resetFileTransportForTesting(); + for (const k of ENV_KEYS) { + if (savedEnv[k] === undefined) delete process.env[k]; + else process.env[k] = savedEnv[k]; + } + fs.rmSync(tmpDir, { recursive: true, force: true }); +}); + +describe('createLogger', () => { + it('renders [Scope] with the empty UIN slot when no child binding', async () => { + const log = createLogger('Bridge'); + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + log.info('hello'); + unsub(); + + expect(captured).toHaveLength(1); + const entry = captured[0]!; + expect(entry.scope).toBe('Bridge'); + expect(entry.uin).toBeUndefined(); + // Plain-text line shape (NO_COLOR=1): + // HH:MM:SS · INFO_ · _<12 blank uin slot>_ · [Bridge] · msg + // where · = single separator space inside the template literal. + const tail = entry.line.slice(9); // drop "HH:MM:SS " + expect(tail).toBe(`INFO ${' '.repeat(12)} [Bridge] hello`); + }); + + it('child({ uin }) derives a logger that stamps the [UIN] slot', async () => { + const log = createLogger('Bridge').child({ uin: 12345 }); + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + log.info('via child'); + unsub(); + + expect(captured).toHaveLength(1); + const entry = captured[0]!; + expect(entry.uin).toBe(12345); + expect(entry.scope).toBe('Bridge'); + // "[12345]" is 7 chars; padEnd to 12 leaves 5 trailing spaces inside + // the slot, then 1 separator space before "[Bridge]". + const tail = entry.line.slice(9); + expect(tail).toBe(`INFO [12345] [Bridge] via child`); + }); + + it('child() does not mutate the parent logger', async () => { + const parent = createLogger('Bridge'); + const childA = parent.child({ uin: 100 }); + const childB = parent.child({ uin: 200 }); + + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + parent.info('parent'); + childA.info('a'); + childB.info('b'); + unsub(); + + expect(captured.map((e) => e.uin)).toEqual([undefined, 100, 200]); + }); + + it('child() can be chained; later uin wins, earlier meta is preserved', async () => { + const log = createLogger('Bridge').child({ uin: 100, foo: 'first' }).child({ bar: 'second' }); + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + log.info('chained'); + unsub(); + + // uin from first child survives through the second (which only sets bar) + expect(captured).toHaveLength(1); + expect(captured[0]!.uin).toBe(100); + }); + + it('writes the per-UIN sub-file in addition to the shared file', async () => { + const log = createLogger('Bridge').child({ uin: 67890 }); + log.info('to file'); + await _resetFileTransportForTesting(); + + const sharedFiles = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log')); + expect(sharedFiles).toHaveLength(1); + const sharedPath = path.join(tmpDir, sharedFiles[0]!); + expect(fs.readFileSync(sharedPath, 'utf8')).toContain('[67890]'); + + const uinSubDir = path.join(tmpDir, '67890'); + expect(fs.existsSync(uinSubDir)).toBe(true); + const uinFiles = fs.readdirSync(uinSubDir).filter((f) => f.endsWith('.log')); + expect(uinFiles).toHaveLength(1); + expect(fs.readFileSync(path.join(uinSubDir, uinFiles[0]!), 'utf8')) + .toContain('to file'); + }); + + it('lines without uin go only to the shared file', async () => { + const log = createLogger('App'); + log.info('no uin here'); + await _resetFileTransportForTesting(); + + const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log')); + expect(shared).toHaveLength(1); + // No numeric sub-dirs should have been created. + const subDirs = fs.readdirSync(tmpDir, { withFileTypes: true }) + .filter((d) => d.isDirectory()) + .map((d) => d.name); + expect(subDirs).toHaveLength(0); + }); + + it('SNOWLUMA_LOG_PER_UIN=0 suppresses the per-UIN sub-file but keeps the shared one', async () => { + setEnv({ SNOWLUMA_LOG_PER_UIN: '0' }); + await _resetFileTransportForTesting(); + + const log = createLogger('Bridge').child({ uin: 9999 }); + log.info('one line'); + await _resetFileTransportForTesting(); + + expect(fs.existsSync(path.join(tmpDir, '9999'))).toBe(false); + const shared = fs.readdirSync(tmpDir).filter((f) => f.endsWith('.log')); + expect(shared).toHaveLength(1); + expect(fs.readFileSync(path.join(tmpDir, shared[0]!), 'utf8')) + .toContain('one line'); + }); + + it('SNOWLUMA_LOG_FILE=0 also suppresses per-UIN files', async () => { + setEnv({ SNOWLUMA_LOG_FILE: '0' }); + await _resetFileTransportForTesting(); + + const log = createLogger('Bridge').child({ uin: 1 }); + log.info('hi'); + await _resetFileTransportForTesting(); + + const entries = fs.readdirSync(tmpDir); + expect(entries).toHaveLength(0); + }); +}); From 1d66693cc3540eaef381288730e288a232e25089 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 00:57:46 +0800 Subject: [PATCH 29/51] refactor(logger): bind per-account loggers in target classes Switches the per-account classes from module-level loggers to per-instance ones derived via Logger.child({ uin }) so their log lines land in both the shared file and the account's logs// sub-file, and the [UIN] slot appears in console output: - IdentityService (Identity scope) - IncomingPacketPipeline (Bridge + Event scopes) - OneBotInstance (Event scope) - HttpServerAdapter (OneBot.HTTP) - HttpPostAdapter (OneBot.POST) - WsClientAdapter (OneBot.WS-Client) - WsServerAdapter (OneBot.WS-Server) The standalone printEvent() in packet-pipeline now takes a Logger argument so it routes through this.eventLog instead of a captured module-level reference. Behavior unchanged otherwise; bridge.ts, bridge/manager.ts and process-level scopes (App / WebUI / Hook / OneBot.Config) keep their module-level loggers since they aren't bound to a single account. --- packages/core/src/bridge/identity-service.ts | 11 ++-- packages/core/src/bridge/packet-pipeline.ts | 54 +++++++++++-------- packages/core/src/onebot/instance.ts | 15 ++++-- .../src/onebot/network/http-post-adapter.ts | 13 +++-- .../src/onebot/network/http-server-adapter.ts | 15 ++++-- .../src/onebot/network/ws-client-adapter.ts | 11 ++-- .../src/onebot/network/ws-server-adapter.ts | 13 +++-- 7 files changed, 84 insertions(+), 48 deletions(-) diff --git a/packages/core/src/bridge/identity-service.ts b/packages/core/src/bridge/identity-service.ts index c6918284..d5e41d3e 100644 --- a/packages/core/src/bridge/identity-service.ts +++ b/packages/core/src/bridge/identity-service.ts @@ -6,9 +6,9 @@ import type { FriendInfo, GroupMemberInfo, QQGroupInfo, UserProfileInfo, GroupRequestInfo, } from './qq-info'; -import { createLogger } from '../utils/logger'; +import { createLogger, type Logger } from '../utils/logger'; -const log = createLogger('Identity'); +const moduleLogger = createLogger('Identity'); /** * Hooks Identity uses when its read methods miss every cache layer. Wired in @@ -112,9 +112,14 @@ export class IdentityService { private readonly db: DatabaseSync | null; private inTransaction = false; private fetcher: IdentityFetcher | null = null; + private readonly log: Logger; constructor(uin: string, dbPath: string | null) { this.uin_ = uin; + const uinNum = Number.parseInt(uin, 10); + this.log = Number.isFinite(uinNum) && uinNum > 0 + ? moduleLogger.child({ uin: uinNum }) + : moduleLogger; if (!dbPath) { this.db = null; @@ -840,7 +845,7 @@ export class IdentityService { try { fn(); } catch (err) { - log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err)); + this.log.error('identity db write failed [%s]: %s', label, err instanceof Error ? (err.stack ?? err.message) : String(err)); } } } diff --git a/packages/core/src/bridge/packet-pipeline.ts b/packages/core/src/bridge/packet-pipeline.ts index 47136fa5..4f661e10 100644 --- a/packages/core/src/bridge/packet-pipeline.ts +++ b/packages/core/src/bridge/packet-pipeline.ts @@ -20,10 +20,10 @@ import type { PacketInfo } from '../protocol/types'; import type { QQEventVariant } from './events'; import type { IdentityService } from './identity-service'; import type { BridgeEventBus } from './event-bus'; -import { createLogger } from '../utils/logger'; +import { createLogger, type Logger } from '../utils/logger'; -const log = createLogger('Bridge'); -const eventLog = createLogger('Event'); +const moduleLog = createLogger('Bridge'); +const moduleEventLog = createLogger('Event'); type GroupMemberIdentityEvent = Extract; @@ -43,8 +43,18 @@ export interface PacketPipelineDeps { export class IncomingPacketPipeline { private cmdHandlers_ = new Map(); private memberRefreshTasks_ = new Map>(); + private readonly log: Logger; + private readonly eventLog: Logger; - constructor(private readonly deps: PacketPipelineDeps) {} + constructor(private readonly deps: PacketPipelineDeps) { + // Tag every line we emit with this Bridge's UIN so per-account file + // routing works. Unparseable uin (shouldn't happen) falls back to + // the module-level logger so we still log, just without the slot. + const uinNum = Number.parseInt(deps.identity.uin, 10); + const bind = Number.isFinite(uinNum) && uinNum > 0 ? { uin: uinNum } : null; + this.log = bind ? moduleLog.child(bind) : moduleLog; + this.eventLog = bind ? moduleEventLog.child(bind) : moduleEventLog; + } registerCmd(cmd: string, parser: CmdParser): void { const arr = this.cmdHandlers_.get(cmd) ?? []; @@ -68,12 +78,12 @@ export class IncomingPacketPipeline { void this.dispatchAfterIdentityRefresh(event); } else { this.handleSideEffects(event); - printEvent(event); + printEvent(this.eventLog, event); this.emit(event); } } } catch (e) { - log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e)); + this.log.error('handler error for %s: %s', pkt.serviceCmd, e instanceof Error ? (e.stack ?? e.message) : String(e)); } } } @@ -93,12 +103,12 @@ export class IncomingPacketPipeline { try { refreshed = await this.prepareGroupMemberJoinIdentity(event); } catch (e) { - log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s', + this.log.warn('failed to resolve group member join identity: group=%d uid=%s err=%s', event.groupId, event.userUid ?? '', e instanceof Error ? e.message : String(e)); } this.handleSideEffects(event, refreshed); - printEvent(event); + printEvent(this.eventLog, event); this.emit(event); } @@ -166,9 +176,9 @@ export class IncomingPacketPipeline { const task = (async () => { try { await this.deps.refreshMemberCache(groupId, refreshGroupList, false); - log.debug('member cache refreshed: group=%d reason=%s', groupId, reason); + this.log.debug('member cache refreshed: group=%d reason=%s', groupId, reason); } catch (e) { - log.warn('failed to refresh member cache: group=%d reason=%s err=%s', + this.log.warn('failed to refresh member cache: group=%d reason=%s err=%s', groupId, reason, e instanceof Error ? e.message : String(e)); } finally { this.memberRefreshTasks_.delete(groupId); @@ -231,7 +241,7 @@ function formatEventUser(uin: number, uid?: string): string { return uid || '未知用户'; } -function printEvent(event: QQEventVariant): void { +function printEvent(log: Logger, event: QQEventVariant): void { switch (event.kind) { case 'group_message': case 'friend_message': @@ -239,37 +249,37 @@ function printEvent(event: QQEventVariant): void { // Message logging is handled by OneBot layer with message ID break; case 'group_recall': - eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin); + log.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin); break; case 'friend_recall': - eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin); + log.warn('私聊撤回 %d 撤回了消息', event.userUin); break; case 'group_member_join': - eventLog.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId); + log.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId); break; case 'group_member_leave': - eventLog.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId); + log.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId); break; case 'group_mute': - eventLog.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration); + log.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration); break; case 'group_admin': - eventLog.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-'); + log.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-'); break; case 'friend_poke': - eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin); + log.info('戳一戳 %d -> %d', event.userUin, event.targetUin); break; case 'group_poke': - eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin); + log.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin); break; case 'friend_request': - eventLog.warn('好友请求 %d: %s', event.fromUin, event.message); + log.warn('好友请求 %d: %s', event.fromUin, event.message); break; case 'group_invite': - eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId); + log.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId); break; case 'group_essence': - eventLog.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-'); + log.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-'); break; } } diff --git a/packages/core/src/onebot/instance.ts b/packages/core/src/onebot/instance.ts index ab11372e..3a3ce334 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/core/src/onebot/instance.ts @@ -19,9 +19,9 @@ import { HttpPostAdapter, type NetworkAdapterContext, } from './network'; -import { createLogger } from '../utils/logger'; +import { createLogger, type Logger } from '../utils/logger'; -const log = createLogger('Event'); +const moduleLog = createLogger('Event'); export class OneBotInstance { readonly uin: string; @@ -40,12 +40,17 @@ export class OneBotInstance { private online = true; private heartbeatTimer: NodeJS.Timeout | null = null; private static readonly HEARTBEAT_INTERVAL = 30000; + private readonly log: Logger; get nickname(): string { return this.bridge.identity.nickname; } constructor(uin: string, bridge: BridgeInterface, config: OneBotConfig) { this.uin = uin; this.bridge = bridge; + const uinNum = Number.parseInt(uin, 10); + this.log = Number.isFinite(uinNum) && uinNum > 0 + ? moduleLog.child({ uin: uinNum }) + : moduleLog; this.rkeyCache = new RKeyCache(); this.mediaStore = new MediaStore(path.join('data', this.uin, 'media.db')); @@ -206,7 +211,7 @@ export class OneBotInstance { try { await existing.reload(net as never); } catch (err) { - log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err)); + this.log.warn('reload [%s] failed: %s', name, err instanceof Error ? err.message : String(err)); } } else if (net.enabled !== false) { const factory = factories.get(name); @@ -268,12 +273,12 @@ export class OneBotInstance { const userId = toInt(event.user_id); const sender = event.sender as any; const nickname = sender?.card || sender?.nickname || String(userId); - log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`); + this.log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`); } else { const userId = toInt(event.user_id); const sender = event.sender as any; const nickname = sender?.nickname || String(userId); - log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`); + this.log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`); } } diff --git a/packages/core/src/onebot/network/http-post-adapter.ts b/packages/core/src/onebot/network/http-post-adapter.ts index b0803903..b32af2e7 100644 --- a/packages/core/src/onebot/network/http-post-adapter.ts +++ b/packages/core/src/onebot/network/http-post-adapter.ts @@ -10,21 +10,24 @@ import { type DispatchPayload, type EventReportOptions, } from '../event-filter'; -import { createLogger } from '../../utils/logger'; +import { createLogger, type Logger } from '../../utils/logger'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { executeQuickOperation } from './quick-operation'; -const log = createLogger('OneBot.POST'); +const moduleLog = createLogger('OneBot.POST'); const DEFAULT_TIMEOUT_MS = 5000; export class HttpPostAdapter extends IOneBotNetworkAdapter { private options: EventReportOptions; private signature_: string; + private readonly log: Logger; constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx); this.options = resolveReportOptions(config); this.signature_ = bindingSignature(config); + const uinNum = Number.parseInt(ctx.uin, 10); + this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog; } override get isActive(): boolean { @@ -106,11 +109,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { } } } else { - log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status); + this.log.warn('[%s] POST %s returned %d', this.name, this.config.url, response.status); } } catch (error) { if (this.isEnabled) { - log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error)); + this.log.warn('[%s] POST %s failed: %s', this.name, this.config.url, error instanceof Error ? error.message : String(error)); } } } @@ -121,7 +124,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { if (!operation || typeof operation !== 'object') return; await executeQuickOperation(event, operation, this.ctx.api); } catch (error) { - log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error)); + this.log.warn('[%s] quick operation failed: %s', this.name, error instanceof Error ? error.message : String(error)); } } } diff --git a/packages/core/src/onebot/network/http-server-adapter.ts b/packages/core/src/onebot/network/http-server-adapter.ts index 778ae4b2..24b4b8db 100644 --- a/packages/core/src/onebot/network/http-server-adapter.ts +++ b/packages/core/src/onebot/network/http-server-adapter.ts @@ -12,14 +12,21 @@ import { } from 'http'; import type { HttpServerNetwork, JsonObject, JsonValue } from '../types'; import type { DispatchPayload } from '../event-filter'; -import { createLogger } from '../../utils/logger'; +import { createLogger, type Logger } from '../../utils/logger'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { isAuthorized, normalizePath } from './utils'; -const log = createLogger('OneBot.HTTP'); +const moduleLog = createLogger('OneBot.HTTP'); export class HttpServerAdapter extends IOneBotNetworkAdapter { private server: Server | null = null; + private readonly log: Logger; + + constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) { + super(name, config, ctx); + const uinNum = Number.parseInt(ctx.uin, 10); + this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog; + } override get isActive(): boolean { // HTTP server never receives events — `isActive` purely tracks the @@ -81,7 +88,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter this.server = server; server.on('listening', () => { - log.success( + this.log.success( '[%s] listening %s:%d%s', this.name, this.config.host ?? '0.0.0.0', @@ -90,7 +97,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter ); }); server.on('error', (err) => { - log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); + this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); }); server.listen(this.config.port, this.config.host ?? '0.0.0.0'); diff --git a/packages/core/src/onebot/network/ws-client-adapter.ts b/packages/core/src/onebot/network/ws-client-adapter.ts index 0f9ac953..348a3137 100644 --- a/packages/core/src/onebot/network/ws-client-adapter.ts +++ b/packages/core/src/onebot/network/ws-client-adapter.ts @@ -13,11 +13,11 @@ import { type DispatchPayload, type EventReportOptions, } from '../event-filter'; -import { createLogger } from '../../utils/logger'; +import { createLogger, type Logger } from '../../utils/logger'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { rawDataToString, safeClose, safeSend } from './utils'; -const log = createLogger('OneBot.WS-Client'); +const moduleLog = createLogger('OneBot.WS-Client'); const DEFAULT_RECONNECT_INTERVAL_MS = 5000; export class WsClientAdapter extends IOneBotNetworkAdapter { @@ -26,11 +26,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { private options: EventReportOptions; private role: WsRole; private explicitlyClosed = false; + private readonly log: Logger; constructor(name: string, config: WsClientNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx); this.options = resolveReportOptions(config); this.role = config.role ?? 'Universal'; + const uinNum = Number.parseInt(ctx.uin, 10); + this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog; } override get isActive(): boolean { @@ -111,7 +114,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { this.socket = socket; socket.on('open', () => { - log.info('[%s] connected %s', this.name, this.config.url); + this.log.info('[%s] connected %s', this.name, this.config.url); this.sendBootstrapMetaEvents(socket); }); @@ -126,7 +129,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { }); socket.on('error', (err: Error) => { - log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err)); + this.log.warn('[%s] error %s: %s', this.name, this.config.url, err instanceof Error ? err.message : String(err)); }); } diff --git a/packages/core/src/onebot/network/ws-server-adapter.ts b/packages/core/src/onebot/network/ws-server-adapter.ts index 5edc08a0..d4686bb0 100644 --- a/packages/core/src/onebot/network/ws-server-adapter.ts +++ b/packages/core/src/onebot/network/ws-server-adapter.ts @@ -14,11 +14,11 @@ import { type DispatchPayload, type EventReportOptions, } from '../event-filter'; -import { createLogger } from '../../utils/logger'; +import { createLogger, type Logger } from '../../utils/logger'; import { IOneBotNetworkAdapter, NetworkReloadType, type NetworkAdapterContext } from './adapter'; import { isAuthorized, parseRequestPath, rawDataToString, safeClose, safeSend, normalizePath } from './utils'; -const log = createLogger('OneBot.WS-Server'); +const moduleLog = createLogger('OneBot.WS-Server'); interface ForwardConn { socket: WebSocket; @@ -30,10 +30,13 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { private wss: WebSocketServer | null = null; private connections = new Map(); private options: EventReportOptions; + private readonly log: Logger; constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) { super(name, config, ctx); this.options = resolveReportOptions(config); + const uinNum = Number.parseInt(ctx.uin, 10); + this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog; } override get isActive(): boolean { @@ -114,7 +117,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { this.wss = wss; wss.on('listening', () => { - log.success( + this.log.success( '[%s] listening %s:%d%s', this.name, this.config.host ?? '0.0.0.0', @@ -124,7 +127,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { }); wss.on('error', (err: Error) => { - log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); + this.log.warn('[%s] server error: %s', this.name, err instanceof Error ? err.message : String(err)); }); wss.on('connection', (socket: WebSocket, request: IncomingMessage) => this.onConnection(socket, request)); @@ -145,7 +148,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter { }); socket.on('close', () => this.connections.delete(socket)); socket.on('error', (err: Error) => { - log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err)); + this.log.warn('[%s] socket error: %s', this.name, err instanceof Error ? err.message : String(err)); }); if (role === 'Event' || role === 'Universal') { From 1ba45e2659a78bff65d9cb96952a04b04b8f4d66 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 01:19:30 +0800 Subject: [PATCH 30/51] feat(logger): observability for OneBot action dispatch Every OneBot action call now emits a single debug line under [Bridge.Action]: DEBUG [Bridge.Action] send_group_msg group_id=12345 message=[len=3] On failure, dispatch logs a warn with the full stack instead of silently folding the error into the response. Unknown actions also get a debug entry so "the bot is ignoring me" is no longer invisible. Notes: - New summarizeParams() helper caps each value at 40 chars / line at 200 chars to keep arrays / nested payloads from blowing the line width. Lives in utils/log-summary.ts for reuse (highway will too). - ApiHandler now takes an optional uin and binds a child logger so per-account file routing works. OneBotInstance passes its parsed uin. - Control-char strip in logger/file-transport was exempting only ESC; also exempt TAB (0x09) and LF (0x0A) so stack traces stay multi-line in both console and file output. - vitest.config sets SNOWLUMA_LOG_LEVEL=debug so the ring buffer receives the new debug entries that tests assert on. --- packages/core/src/onebot/api-handler.ts | 21 ++- packages/core/src/onebot/instance.ts | 2 +- packages/core/src/utils/log-file-transport.ts | 4 +- packages/core/src/utils/log-summary.ts | 60 ++++++++ packages/core/src/utils/logger.ts | 7 +- .../core/tests/api-handler-logging.test.ts | 130 ++++++++++++++++++ packages/core/vitest.config.ts | 7 +- 7 files changed, 224 insertions(+), 7 deletions(-) create mode 100644 packages/core/src/utils/log-summary.ts create mode 100644 packages/core/tests/api-handler-logging.test.ts diff --git a/packages/core/src/onebot/api-handler.ts b/packages/core/src/onebot/api-handler.ts index 2be74ec7..f0c3da02 100644 --- a/packages/core/src/onebot/api-handler.ts +++ b/packages/core/src/onebot/api-handler.ts @@ -2,6 +2,10 @@ import type { JsonObject, JsonValue, MessageMeta } from './types'; import type { ForwardPreviewMeta } from './modules/message-actions'; import type { BridgeInterface } from '../bridge/bridge-interface'; import { RETCODE, failedResponse } from './types'; +import { createLogger, type Logger } from '../utils/logger'; +import { summarizeParams } from '../utils/log-summary'; + +const moduleLog = createLogger('Bridge.Action'); import { register as registerInfo } from './actions/info'; import { register as registerMessage } from './actions/message'; @@ -101,8 +105,10 @@ type ActionHandler = (params: JsonObject) => Promise(); + private readonly log: Logger; - constructor(context: ApiActionContext) { + constructor(context: ApiActionContext, uin?: number) { + this.log = typeof uin === 'number' && uin > 0 ? moduleLog.child({ uin }) : moduleLog; registerInfo(this, context); registerMessage(this, context); registerFriend(this, context); @@ -120,12 +126,25 @@ export class ApiHandler { async handle(action: string, params: JsonObject): Promise { const handler = this.handlers.get(action); if (!handler) { + this.log.debug('unknown action %s', action); return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action'); } + // Entry log goes to file always (debug); console only when level is + // dialed down to debug. Caller-perspective summary lets the operator + // grep "what did the bot get asked to do" without scraping wire logs. + this.log.debug('%s params=%s', action, summarizeParams(params)); + try { return await handler(params); } catch (error) { + // Action failures are almost always param-shape problems coming + // from the OneBot client; warn (not error) is the right level so + // the log file stays a useful signal of real internal faults. + this.log.warn('%s failed: %s\n%s', + action, + error instanceof Error ? error.message : String(error), + error instanceof Error ? (error.stack ?? '') : ''); const message = error instanceof Error ? error.message : 'internal error'; return failedResponse(RETCODE.INTERNAL_ERROR, message); } diff --git a/packages/core/src/onebot/instance.ts b/packages/core/src/onebot/instance.ts index 3a3ce334..7a57b9ea 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/core/src/onebot/instance.ts @@ -90,7 +90,7 @@ export class OneBotInstance { }; this.ctx = ctx; - this.apiHandler = new ApiHandler(buildApiContext(ctx)); + this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined); this.networkManager = new OneBotNetworkManager(); this.installAdaptersFromConfig(config); void this.networkManager.openAll(); diff --git a/packages/core/src/utils/log-file-transport.ts b/packages/core/src/utils/log-file-transport.ts index 0b5b6d8c..e716c35e 100644 --- a/packages/core/src/utils/log-file-transport.ts +++ b/packages/core/src/utils/log-file-transport.ts @@ -28,8 +28,10 @@ const FILE_RE = /^snowluma-(\d{4}-\d{2}-\d{2})(?:\.(\d+))?\.log$/; // eslint-disable-next-line no-control-regex const ANSI_RE = /\x1B\[[0-?]*[ -/]*[@-~]/g; +// Preserve TAB (0x09), LF (0x0A) and ESC (0x1B) — TAB / LF for legit +// multi-line records (stack traces), ESC is stripped through ANSI_RE. // eslint-disable-next-line no-control-regex -const CTRL_RE = /[\x00-\x1A\x1C-\x1F\x7F]/g; +const CTRL_RE = /[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g; function parsePositiveInt(v: string | undefined, dflt: number): number { if (!v) return dflt; diff --git a/packages/core/src/utils/log-summary.ts b/packages/core/src/utils/log-summary.ts new file mode 100644 index 00000000..94ef38b1 --- /dev/null +++ b/packages/core/src/utils/log-summary.ts @@ -0,0 +1,60 @@ +// Compact one-line param summary for log output. +// +// OneBot action params can include large message arrays / nested +// payloads that would blow the line width to multiple kilobytes if we +// JSON.stringify them naively. This helper produces a flat +// `k1=v1 k2=v2 ...` rendering with per-field truncation and a hard +// total cap, designed to be grep-friendly without flooding the log +// file. + +const MAX_FIELD = 40; +const MAX_TOTAL = 200; + +function valueRepr(v: unknown): string { + if (v === null) return 'null'; + if (v === undefined) return 'undefined'; + switch (typeof v) { + case 'string': + return v.length > MAX_FIELD ? `"${v.slice(0, MAX_FIELD)}..."` : `"${v}"`; + case 'number': + case 'boolean': + case 'bigint': + return String(v); + case 'object': + if (Array.isArray(v)) return `[len=${v.length}]`; + return '{...}'; + default: + return typeof v; + } +} + +/** + * Render a params object as a single line for logging. Skips deep + * traversal: nested objects collapse to `{...}`, arrays to `[len=N]`. + * Strings are quoted; long ones are truncated with an ellipsis. + * + * Output is capped at MAX_TOTAL chars; on overflow the tail is + * replaced with `...` so the next field doesn't get half-rendered. + */ +export function summarizeParams(params: unknown): string { + if (params === null || params === undefined) return '{}'; + if (typeof params !== 'object') { + const s = String(params); + return s.length > MAX_TOTAL ? `${s.slice(0, MAX_TOTAL)}...` : s; + } + if (Array.isArray(params)) return `[len=${params.length}]`; + + const out: string[] = []; + let total = 0; + for (const [k, v] of Object.entries(params as Record)) { + const entry = `${k}=${valueRepr(v)}`; + // +1 accounts for the separating space we'd insert when joining. + if (total > 0 && total + entry.length + 1 > MAX_TOTAL) { + out.push('...'); + break; + } + out.push(entry); + total += entry.length + (out.length > 1 ? 1 : 0); + } + return out.join(' '); +} diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts index bb63fa0e..9b4c7f0b 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -136,10 +136,11 @@ function emit(level: LogLevel, options: LogOptions, args: unknown[]): void { const stream = level === 'warn' || level === 'error' ? process.stderr : process.stdout; // Strip ASCII control characters before writing to terminal to prevent // BEL (0x07) in user-provided strings (e.g. group member names) from - // triggering Windows system beep sounds. ESC (0x1B) is preserved so the - // ANSI color sequences emitted by render() actually reach the terminal. + // triggering Windows system beep sounds. Exempt TAB (0x09), LF (0x0A) + // and ESC (0x1B) so multi-line records (stack traces) and ANSI color + // sequences emitted by render() pass through intact. // eslint-disable-next-line no-control-regex - stream.write(line.replace(/[\x00-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); + stream.write(line.replace(/[\x00-\x08\x0B-\x1A\x1C-\x1F\x7F]/g, '') + '\n'); } // File transport always sees every level (debug-and-up) for post-mortem diff --git a/packages/core/tests/api-handler-logging.test.ts b/packages/core/tests/api-handler-logging.test.ts new file mode 100644 index 00000000..6e3ef718 --- /dev/null +++ b/packages/core/tests/api-handler-logging.test.ts @@ -0,0 +1,130 @@ +// Tests for ApiHandler's central dispatch logging. +// Verifies that every action call emits a debug entry line, failures +// fold into a warn line with stack, and unknown actions are surfaced. +// Also covers the summarizeParams helper used to keep the entry log +// from blowing the line width. + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { ApiHandler } from '../src/onebot/api-handler'; +import { subscribeLogs, type LogEntry } from '../src/utils/logger'; +import { summarizeParams } from '../src/utils/log-summary'; + +// Minimal context — we never reach the real action handlers; we +// register our own via registerAction. +function emptyContext(): any { + return { + bridge: {}, + getLoginInfo: () => ({ userId: 0, nickname: '' }), + isOnline: () => true, + getMessage: () => null, + getMessageMeta: () => null, + sendPrivateMessage: async () => ({ messageId: 0 }), + sendGroupMessage: async () => ({ messageId: 0 }), + deleteMessage: async () => {}, + canSendImage: () => true, + canSendRecord: () => true, + getFriendList: async () => [], + getImageInfo: async () => null, + getRecordInfo: async () => null, + }; +} + +let captured: LogEntry[]; +let unsub: () => void; +const savedLogLevel = process.env.SNOWLUMA_LOG_LEVEL; + +beforeEach(() => { + process.env.SNOWLUMA_LOG_LEVEL = 'debug'; + captured = []; + unsub = subscribeLogs((e) => captured.push(e)); +}); + +afterEach(() => { + unsub(); + if (savedLogLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL; + else process.env.SNOWLUMA_LOG_LEVEL = savedLogLevel; +}); + +describe('summarizeParams', () => { + it('renders flat scalar fields as k=v pairs', () => { + const out = summarizeParams({ group_id: 12345, auto_escape: false, foo: 'bar' }); + expect(out).toBe('group_id=12345 auto_escape=false foo="bar"'); + }); + + it('truncates long string values with an ellipsis', () => { + const long = 'x'.repeat(80); + const out = summarizeParams({ s: long }); + expect(out).toMatch(/^s="x{40}\.\.\."$/); + }); + + it('collapses arrays and nested objects rather than dumping them', () => { + const out = summarizeParams({ messages: [1, 2, 3, 4], meta: { a: 1, b: 2 } }); + expect(out).toBe('messages=[len=4] meta={...}'); + }); + + it('caps the total line and tags the cut with ellipsis', () => { + const params: Record = {}; + for (let i = 0; i < 30; i++) params[`field_with_some_padding_${i}`] = i; + const out = summarizeParams(params); + expect(out.length).toBeLessThan(220); + expect(out.endsWith('...')).toBe(true); + }); + + it('handles null / undefined inputs gracefully', () => { + expect(summarizeParams(null)).toBe('{}'); + expect(summarizeParams(undefined)).toBe('{}'); + }); +}); + +describe('ApiHandler dispatch logging', () => { + it('emits a debug entry under [Bridge.Action] when an action is called', async () => { + const handler = new ApiHandler(emptyContext(), 12345); + handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null })); + + await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] }); + + const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug'); + expect(entry).toBeDefined(); + expect(entry!.uin).toBe(12345); + expect(entry!.message).toContain('echo'); + expect(entry!.message).toContain('group_id=67890'); + expect(entry!.message).toContain('message=[len=3]'); + }); + + it('emits a warn line with the error stack when the handler throws', async () => { + const handler = new ApiHandler(emptyContext(), 12345); + handler.registerAction('boom', async () => { + throw new Error('kapow'); + }); + + const result = await handler.handle('boom', {}); + expect(result.status).toBe('failed'); + + const warn = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'warn'); + expect(warn).toBeDefined(); + expect(warn!.message).toContain('boom'); + expect(warn!.message).toContain('kapow'); + // stack contains the test file path; just check that something stack-shaped is appended + expect(warn!.message).toMatch(/at\s+/); + }); + + it('logs unknown actions at debug level', async () => { + const handler = new ApiHandler(emptyContext(), 99); + await handler.handle('not_a_real_action', {}); + + const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action')); + expect(entry).toBeDefined(); + expect(entry!.level).toBe('debug'); + }); + + it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => { + const handler = new ApiHandler(emptyContext()); + handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null })); + + await handler.handle('ping', {}); + + const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug'); + expect(entry).toBeDefined(); + expect(entry!.uin).toBeUndefined(); + }); +}); diff --git a/packages/core/vitest.config.ts b/packages/core/vitest.config.ts index 4870d273..cae60282 100644 --- a/packages/core/vitest.config.ts +++ b/packages/core/vitest.config.ts @@ -17,8 +17,13 @@ export default defineConfig({ // doesn't litter cwd with logs/snowluma-*.log files. Tests that // explicitly cover file output set their own SNOWLUMA_LOG_FILE='1' // + SNOWLUMA_LOG_DIR=. + // + // Run at debug level so tests asserting on debug-level log entries + // (e.g. action dispatch entry lines) actually see them via the + // ring buffer / subscribers, which sit behind the console-level gate. env: { - SNOWLUMA_LOG_FILE: '0' + SNOWLUMA_LOG_FILE: '0', + SNOWLUMA_LOG_LEVEL: 'debug' } } }); From 7ec479bb889e88cd3d6dbc80e9bfd7304b0b5f11 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 01:29:06 +0800 Subject: [PATCH 31/51] feat(logger): protocol-layer observability for highway and msg-push MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Highway upload path now emits per-type entry + shared pipeline ops: DEBUG [Highway.Image] uploading 234567 bytes md5=abc12345... → group 12345 DEBUG [Highway] image OIDB requires bytes, PUT 234567 bytes (sub=top) DEBUG [Highway] image PUT done in 1234ms -- or -- DEBUG [Highway] image fast-upload hit (server already had bytes) The three pipeline-side lines come from runNtv2Upload() and are shared across image/video/ptt; the per-type entry log lives in each *-upload.ts wrapper so the scope identifies the media kind. md5 is truncated to its first 8 hex chars for line width; PUT latency is reported in ms. MsgPush silent dispatch defaults are now visible at debug: DEBUG [MsgPush.Unknown] no decoder for PkgType=999 subType=0 DEBUG [MsgPush.Unknown] Event0x2DC unknown subType=42 DEBUG [MsgPush.Unknown] Event0x210 unknown subType=42 Captures protocol drift (new NT QQ subtypes) and "we forgot to register this PkgType" oversights, neither of which used to leave any trace in the log. All new lines are debug-level so console output (default info) stays unchanged; file transport sees them for post-mortem. --- .../core/src/bridge/highway/image-upload.ts | 15 ++ packages/core/src/bridge/highway/pipeline.ts | 17 ++ .../core/src/bridge/highway/ptt-upload.ts | 17 +- .../core/src/bridge/highway/video-upload.ts | 18 +- .../bridge/msg-push/decoders/event-0x210.ts | 4 + .../bridge/msg-push/decoders/event-0x2dc.ts | 4 + packages/core/src/bridge/msg-push/registry.ts | 9 +- .../core/tests/observability-logs.test.ts | 188 ++++++++++++++++++ 8 files changed, 266 insertions(+), 6 deletions(-) create mode 100644 packages/core/tests/observability-logs.test.ts diff --git a/packages/core/src/bridge/highway/image-upload.ts b/packages/core/src/bridge/highway/image-upload.ts index 4a670890..6d43e303 100644 --- a/packages/core/src/bridge/highway/image-upload.ts +++ b/packages/core/src/bridge/highway/image-upload.ts @@ -7,6 +7,7 @@ import type { Bridge } from '../bridge'; import type { MessageElement } from '../events'; +import { createLogger } from '../../utils/logger'; import { GROUP_IMAGE_CMD_ID, PRIVATE_IMAGE_CMD_ID } from './highway-client'; import { finalizeMediaMsgInfo, @@ -16,6 +17,14 @@ import { } from './pipeline'; import { computeHashes, detectImageFormat, loadBinarySource } from './utils'; +const moduleLog = createLogger('Highway.Image'); + +function loggerFor(bridge: Bridge) { + const raw = bridge.identity?.uin; + const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; +} + interface ImageData { /** Empty when the caller is forwarding from cached fingerprints. */ bytes: Uint8Array; @@ -106,7 +115,13 @@ export async function uploadImageMsgInfo( targetIdOrUid: string | number, element: MessageElement, ): Promise { + const log = loggerFor(bridge); const image = await loadImage(element); + log.debug('uploading %d bytes md5=%s... → %s %s', + image.fileSize, + image.md5Hex.slice(0, 8), + isGroup ? 'group' : 'c2c', + String(targetIdOrUid)); const uploads: MediaSubFileUpload[] = [{ source: 'top', diff --git a/packages/core/src/bridge/highway/pipeline.ts b/packages/core/src/bridge/highway/pipeline.ts index ee4fd5d6..b04b6b32 100644 --- a/packages/core/src/bridge/highway/pipeline.ts +++ b/packages/core/src/bridge/highway/pipeline.ts @@ -25,6 +25,9 @@ import { NTV2UploadRichMediaRespSchema, } from '../proto/highway'; import { buildHighwayExtend, fetchHighwaySession, uploadHighwayHttp } from './highway-client'; +import { createLogger } from '../../utils/logger'; + +const moduleLog = createLogger('Highway'); // ─────────────── public types ─────────────── @@ -123,6 +126,11 @@ export function hexToBytes(hex: string): Uint8Array { export async function runNtv2Upload(params: NtV2UploadParams): Promise { const { bridge, isGroup, targetIdOrUid, oidbCmd, serviceCmd, uploads } = params; const label = params.label ?? 'media'; + const raw = bridge.identity?.uin; + const uinNum = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + const log = Number.isFinite(uinNum) && uinNum > 0 + ? moduleLog.child({ uin: uinNum }) + : moduleLog; // Build the full body once. Pulling this in here means each format file // only specifies the seven fields that actually vary. @@ -184,6 +192,7 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { return session; }; + let didPut = false; for (const sub of uploads) { const target = sub.source === 'top' ? upload : upload.subFileInfos?.[sub.source]; const uKey = target?.uKey ?? ''; @@ -203,7 +212,15 @@ export async function runNtv2Upload(params: NtV2UploadParams): Promise { sub.sha1 as any, // sha1 may be Uint8Array | Uint8Array[]; the helper accepts both sub.subFileIndex ?? 0, ); + log.debug('%s OIDB requires bytes, PUT %d bytes (sub=%s)', label, sub.bytes.length, String(sub.source)); + const t0 = Date.now(); await uploadHighwayHttp(bridge, await getSession(), sub.cmdId, sub.bytes, sub.md5, extend); + log.debug('%s PUT done in %dms', label, Date.now() - t0); + didPut = true; + } + + if (!didPut) { + log.debug('%s fast-upload hit (server already had bytes)', label); } return upload; diff --git a/packages/core/src/bridge/highway/ptt-upload.ts b/packages/core/src/bridge/highway/ptt-upload.ts index ccb617b8..b3cf868b 100644 --- a/packages/core/src/bridge/highway/ptt-upload.ts +++ b/packages/core/src/bridge/highway/ptt-upload.ts @@ -22,7 +22,13 @@ import { type MediaSubFileUpload, } from './pipeline'; -const log = createLogger('Ptt'); +const moduleLog = createLogger('Highway.Ptt'); + +function loggerFor(bridge: Bridge) { + const raw = bridge.identity?.uin; + const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; +} export const PRIVATE_PTT_CMD_ID = 1007; export const GROUP_PTT_CMD_ID = 1008; @@ -105,7 +111,7 @@ async function loadPtt(element: MessageElement, tempDir: string): Promise { try { fs.unlinkSync(silk.path); } catch { /* ignore */ } }); - log.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration); + moduleLog.debug('converted record to silk: %s -> %s (duration=%ds)', inputPath, silk.path, silk.duration); } const silkBytes = new Uint8Array(fs.readFileSync(silk.path)); @@ -141,8 +147,15 @@ export async function uploadPttMsgInfo( targetIdOrUid: string | number, element: MessageElement, ): Promise { + const log = loggerFor(bridge); const tempDir = defaultPttTempDir(); const ptt = await loadPtt(element, tempDir); + log.debug('uploading %d bytes md5=%s... → %s %s duration=%ds', + ptt.fileSize, + ptt.md5Hex.slice(0, 8), + isGroup ? 'group' : 'c2c', + String(targetIdOrUid), + ptt.duration); try { const uploads: MediaSubFileUpload[] = [{ source: 'top', diff --git a/packages/core/src/bridge/highway/video-upload.ts b/packages/core/src/bridge/highway/video-upload.ts index a0778c6e..96191ad3 100644 --- a/packages/core/src/bridge/highway/video-upload.ts +++ b/packages/core/src/bridge/highway/video-upload.ts @@ -29,7 +29,13 @@ import { type MediaSubFileUpload, } from './pipeline'; -const log = createLogger('Video'); +const moduleLog = createLogger('Highway.Video'); + +function loggerFor(bridge: Bridge) { + const raw = bridge.identity?.uin; + const uin = typeof raw === 'string' ? Number.parseInt(raw, 10) : 0; + return Number.isFinite(uin) && uin > 0 ? moduleLog.child({ uin }) : moduleLog; +} export const PRIVATE_VIDEO_CMD_ID = 1001; export const PRIVATE_VIDEO_THUMB_CMD_ID = 1002; @@ -323,7 +329,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{ try { thumbBytes = (await loadBinarySource(element.thumbUrl, 'video thumbnail')).bytes; } catch (err) { - log.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err)); + moduleLog.warn('custom video thumbnail load failed: %s', err instanceof Error ? err.message : String(err)); } } @@ -337,7 +343,7 @@ async function loadThumb(element: MessageElement, videoPath: string): Promise<{ thumbBytes = new Uint8Array(info.image); } } catch (err) { - log.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err)); + moduleLog.warn('video thumbnail generation failed: %s', err instanceof Error ? err.message : String(err)); } } @@ -430,7 +436,13 @@ export async function uploadVideoMsgInfo( targetIdOrUid: string | number, element: MessageElement, ): Promise { + const log = loggerFor(bridge); const video = await loadVideo(element); + log.debug('uploading %d bytes md5=%s... → %s %s', + video.fileSize, + video.md5Hex.slice(0, 8), + isGroup ? 'group' : 'c2c', + String(targetIdOrUid)); try { const uploads: MediaSubFileUpload[] = [ { diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts index 5343d4bb..cbce944f 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x210.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x210.ts @@ -14,6 +14,9 @@ import { Event0x210SubType } from '../enums'; import { resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, } from '../helpers'; +import { createLogger } from '../../../utils/logger'; + +const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x210: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x210SubType) { @@ -21,6 +24,7 @@ export const decodeEvent0x210: MsgPushDecoder = (ctx) => { case Event0x210SubType.FriendRecallNotice: return decodeFriendRecall(ctx); case Event0x210SubType.FriendPokeNotice: return decodeFriendPoke(ctx); } + unknownLog.debug('Event0x210 unknown subType=%d', ctx.head.subType); return []; }; diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts index e8f485a8..7b072b83 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts @@ -16,6 +16,9 @@ import { resolveUidToUin, parseU64OrZero, buildTemplateMap, findTemplateValue, unwrapGroupNotifyPayload, } from '../helpers'; +import { createLogger } from '../../../utils/logger'; + +const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x2DCSubType) { @@ -24,6 +27,7 @@ export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx); case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx); } + unknownLog.debug('Event0x2DC unknown subType=%d', ctx.head.subType); return []; }; diff --git a/packages/core/src/bridge/msg-push/registry.ts b/packages/core/src/bridge/msg-push/registry.ts index 1ac309ec..4a3e9a18 100644 --- a/packages/core/src/bridge/msg-push/registry.ts +++ b/packages/core/src/bridge/msg-push/registry.ts @@ -9,6 +9,7 @@ import type { MsgPushContext } from './context'; import type { PkgType } from './enums'; const log = createLogger('MsgPush'); +const unknownLog = createLogger('MsgPush.Unknown'); export type MsgPushDecoder = (ctx: MsgPushContext) => QQEventVariant[]; @@ -27,7 +28,13 @@ export class MsgPushRegistry { decode(ctx: MsgPushContext): QQEventVariant[] { const decoder = this.decoders_.get(ctx.head.msgType as PkgType); - if (!decoder) return []; + if (!decoder) { + // Unrecognized PkgType: either we don't care about this notify, or + // the QQ NT client added a new variant. Surface at debug so a + // protocol change can be spotted without spamming production logs. + unknownLog.debug('no decoder for PkgType=%d subType=%d', ctx.head.msgType, ctx.head.subType); + return []; + } try { return decoder(ctx); } catch (e) { diff --git a/packages/core/tests/observability-logs.test.ts b/packages/core/tests/observability-logs.test.ts new file mode 100644 index 00000000..ee3a871e --- /dev/null +++ b/packages/core/tests/observability-logs.test.ts @@ -0,0 +1,188 @@ +// Tests for the new PR5 observability log lines: +// - [Highway.Image] entry log on uploadImageMsgInfo +// - [Highway] fast-upload hit when OIDB returns no uKey +// - [Highway] OIDB-requires-bytes + PUT-done with elapsed ms +// - [MsgPush.Unknown] unrecognized PkgType +// - [MsgPush.Unknown] wrapper decoder unknown subType +// +// Highway transport is mocked the same way pipeline.test.ts does it so +// runNtv2Upload exercises real OIDB encode/decode but skips actual +// network I/O. + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { subscribeLogs, type LogEntry } from '../src/utils/logger'; + +vi.mock('../src/bridge/highway/highway-client', () => ({ + fetchHighwaySession: vi.fn(async () => ({ sessionId: 'fake-session' })), + uploadHighwayHttp: vi.fn(async () => undefined), + buildHighwayExtend: vi.fn(() => new Uint8Array([0xAA, 0xBB])), + PRIVATE_IMAGE_CMD_ID: 1003, + GROUP_IMAGE_CMD_ID: 1004, +})); + +import { + runNtv2Upload, + type MediaSubFileUpload, +} from '../src/bridge/highway/pipeline'; +import { protoEncode } from '../src/protobuf/decode'; +import { makeOidbBaseSchema } from '../src/bridge/proto/oidb'; +import { + NTV2UploadRichMediaRespSchema, +} from '../src/bridge/proto/highway'; +import { MsgPushRegistry } from '../src/bridge/msg-push/registry'; +import type { MsgPushContext } from '../src/bridge/msg-push/context'; +import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc'; + +function encodeOidbResponse(body: unknown): Buffer { + const baseSchema = makeOidbBaseSchema(NTV2UploadRichMediaRespSchema); + return Buffer.from(protoEncode({ + command: 0x11C4, subCommand: 100, errorCode: 0, + body: body as Record, + errorMsg: '', reserved: 1, + }, baseSchema)); +} + +function fakeBridge(responseData: Buffer, uin = '12345'): any { + return { + identity: { uin }, + sendRawPacket: vi.fn(async () => ({ + success: true, + gotResponse: true, + errorCode: 0, + errorMessage: '', + responseData, + })), + }; +} + +let captured: LogEntry[]; +let unsub: () => void; + +beforeEach(() => { + captured = []; + unsub = subscribeLogs((e) => captured.push(e)); +}); + +afterEach(() => { + unsub(); +}); + +describe('PR5 — highway pipeline logging', () => { + it('logs fast-upload hit when the server returns no uKey', async () => { + // upload.uKey absent → no PUT performed. + const bridge = fakeBridge(encodeOidbResponse({ + upload: { msgInfo: { msgInfoBody: [], extBizInfo: {} } }, + })); + + const params = { + bridge, + isGroup: true, + targetIdOrUid: 67890, + oidbCmd: 0x11C4, + serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100', + requestId: 1, + businessType: 1, + uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }], + compatQmsgSceneType: 2, + extBizInfo: { pic: {} }, + uploads: [{ + source: 'top', + cmdId: 1004, + bytes: new Uint8Array([1, 2, 3]), + md5: new Uint8Array(16), + sha1: new Uint8Array(20), + }] as MediaSubFileUpload[], + label: 'image', + }; + + await runNtv2Upload(params); + + const hit = captured.find((e) => + e.scope === 'Highway' && e.message.includes('fast-upload hit')); + expect(hit).toBeDefined(); + expect(hit!.uin).toBe(12345); + }); + + it('logs OIDB-requires-bytes and PUT-done with elapsed ms when uKey is present', async () => { + const bridge = fakeBridge(encodeOidbResponse({ + upload: { + uKey: 'server-needs-bytes-please', + ipv4s: [{ ipv4: '1.2.3.4', port: 80 }], + msgInfo: { msgInfoBody: [], extBizInfo: {} }, + }, + })); + + const params = { + bridge, + isGroup: true, + targetIdOrUid: 67890, + oidbCmd: 0x11C4, + serviceCmd: 'OidbSvcTrpcTcp.0x11c4_100', + requestId: 1, + businessType: 1, + uploadInfo: [{ fileInfo: { fileName: 'a.jpg' }, subFileType: 0 }], + compatQmsgSceneType: 2, + extBizInfo: { pic: {} }, + uploads: [{ + source: 'top', + cmdId: 1004, + bytes: new Uint8Array(1024), + md5: new Uint8Array(16), + sha1: new Uint8Array(20), + }] as MediaSubFileUpload[], + label: 'image', + }; + + await runNtv2Upload(params); + + const requiresBytes = captured.find((e) => + e.scope === 'Highway' && e.message.includes('OIDB requires bytes')); + const putDone = captured.find((e) => + e.scope === 'Highway' && /PUT done in \d+ms/.test(e.message)); + + expect(requiresBytes).toBeDefined(); + expect(putDone).toBeDefined(); + + const fastHit = captured.find((e) => + e.scope === 'Highway' && e.message.includes('fast-upload hit')); + expect(fastHit).toBeUndefined(); + }); +}); + +describe('PR5 — MsgPush unknown dispatch logging', () => { + it('logs an unknown PkgType under [MsgPush.Unknown]', () => { + const reg = new MsgPushRegistry(); + // No decoders registered → any pkgType is unknown. + const ctx = { + head: { msgType: 9999, subType: 0, timestamp: 0 }, + content: new Uint8Array(0), + identity: {} as any, + fromUin: 0, + selfUin: 0, + } as unknown as MsgPushContext; + + reg.decode(ctx); + + const entry = captured.find((e) => + e.scope === 'MsgPush.Unknown' && e.message.includes('PkgType=9999')); + expect(entry).toBeDefined(); + expect(entry!.level).toBe('debug'); + }); + + it('logs an unknown wrapper subType under [MsgPush.Unknown] (Event0x2DC)', () => { + const ctx = { + head: { msgType: 732, subType: 999, timestamp: 0 }, + content: new Uint8Array(0), + identity: {} as any, + fromUin: 0, + selfUin: 0, + } as unknown as MsgPushContext; + + decodeEvent0x2DC(ctx); + + const entry = captured.find((e) => + e.scope === 'MsgPush.Unknown' && /Event0x2DC unknown subType=999/.test(e.message)); + expect(entry).toBeDefined(); + expect(entry!.level).toBe('debug'); + }); +}); From 84e746c2784104369f1175ff923a37c60cd6825c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 01:36:12 +0800 Subject: [PATCH 32/51] chore(observability): defensive depth pass MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two related cleanups so unexpected failures stop being invisible: void-promise wrappers Every `void this.something()` fire-and-forget call now has a .catch(err => log.warn(...)) attached. Affected sites: - packet-pipeline.ts: dispatchAfterIdentityRefresh - instance.ts: openAll / applyConfigDiff / closeAll / emitEvent - http-post-adapter.ts: postEvent - ws-client-adapter.ts: handleApiMessage Most of the network-manager fan-outs already isolate per-adapter errors, but the outer catches guard against future refactors and surface stack traces immediately rather than as unhandled rejection warnings. silent-catch sweep (Bridge.Web) bridge/web/group-honor.ts, group-essence.ts, group-notice.ts had `} catch (e) { return undefined; }` patterns that turned every QQ Web API failure into a silent empty response. Now log.warn with the full stack first, then return the same fallback so behavior is unchanged. The commented-out `// console.error(e)` debris is gone. Plus one console → logger conversion in message-parser.ts (music sign fallback path). --- packages/core/src/bridge/packet-pipeline.ts | 5 ++++- packages/core/src/bridge/web/group-essence.ts | 5 +++++ packages/core/src/bridge/web/group-honor.ts | 6 +++++- packages/core/src/bridge/web/group-notice.ts | 20 +++++++++++++------ packages/core/src/onebot/instance.ts | 20 ++++++++++++++----- packages/core/src/onebot/message-parser.ts | 5 ++++- .../src/onebot/network/http-post-adapter.ts | 4 +++- .../src/onebot/network/ws-client-adapter.ts | 4 +++- 8 files changed, 53 insertions(+), 16 deletions(-) diff --git a/packages/core/src/bridge/packet-pipeline.ts b/packages/core/src/bridge/packet-pipeline.ts index 4f661e10..19654a08 100644 --- a/packages/core/src/bridge/packet-pipeline.ts +++ b/packages/core/src/bridge/packet-pipeline.ts @@ -75,7 +75,10 @@ export class IncomingPacketPipeline { const events = handler(pkt, this.deps.identity); for (const event of events) { if (this.needsPreDispatchIdentityRefresh(event)) { - void this.dispatchAfterIdentityRefresh(event); + void this.dispatchAfterIdentityRefresh(event).catch((err) => { + this.log.warn('dispatchAfterIdentityRefresh failed: %s', + err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); } else { this.handleSideEffects(event); printEvent(this.eventLog, event); diff --git a/packages/core/src/bridge/web/group-essence.ts b/packages/core/src/bridge/web/group-essence.ts index d942dedf..bf1710ce 100644 --- a/packages/core/src/bridge/web/group-essence.ts +++ b/packages/core/src/bridge/web/group-essence.ts @@ -1,4 +1,7 @@ import { RequestUtil, cookieToString, getBknFromCookie } from './request-util'; +import { createLogger } from '../../utils/logger'; + +const log = createLogger('Bridge.Web'); // 定义接口返回类型 export interface GroupEssenceMsgRet { @@ -39,6 +42,8 @@ export async function getGroupEssenceMsg( ); return ret.retcode === 0 ? ret : undefined; } catch (e) { + log.warn('getGroupEssenceMsg failed (group=%s page=%d/%d): %s', + groupCode, pageStart, pageLimit, e instanceof Error ? (e.stack ?? e.message) : String(e)); return undefined; } } diff --git a/packages/core/src/bridge/web/group-honor.ts b/packages/core/src/bridge/web/group-honor.ts index f77fdc3a..c9162b09 100644 --- a/packages/core/src/bridge/web/group-honor.ts +++ b/packages/core/src/bridge/web/group-honor.ts @@ -1,4 +1,7 @@ import { RequestUtil, cookieToString } from './request-util'; +import { createLogger } from '../../utils/logger'; + +const log = createLogger('Bridge.Web'); export enum WebHonorType { TALKATIVE = 'talkative', @@ -43,7 +46,8 @@ export async function getHonorListWebAPI(cookieObject: Record, g description: item?.desc, })); } catch (e) { - // console.error(e); + log.warn('getHonorListWebAPI failed (group=%s type=%d): %s', + groupCode, type, e instanceof Error ? (e.stack ?? e.message) : String(e)); return []; } } \ No newline at end of file diff --git a/packages/core/src/bridge/web/group-notice.ts b/packages/core/src/bridge/web/group-notice.ts index ba01fcef..cbe98158 100644 --- a/packages/core/src/bridge/web/group-notice.ts +++ b/packages/core/src/bridge/web/group-notice.ts @@ -1,7 +1,8 @@ import { RequestUtil, cookieToString } from './request-util'; import https from 'node:https'; -// import { readFileSync } from 'node:fs'; -// import * as console from "node:console"; +import { createLogger } from '../../utils/logger'; + +const log = createLogger('Bridge.Web'); export interface SetNoticeRetSuccess { ec?: number; @@ -112,6 +113,7 @@ export async function setGroupNoticeWebAPI( ); return ret; } catch (e) { + log.warn('group-notice add failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); return undefined; } } @@ -158,7 +160,8 @@ export async function getGroupNoticeWebAPI( ); // console.log(JSON.stringify(ret, null, 2)); return ret?.ec === 0 ? ret : undefined; - } catch { + } catch (e) { + log.warn('getGroupNoticeList failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); return undefined; } } @@ -215,11 +218,15 @@ export async function uploadGroupNoticeImage( } }); }); - req.on('error', () => resolve(undefined)); + req.on('error', (err) => { + log.warn('uploadGroupNoticeImage transport error: %s', err.message); + resolve(undefined); + }); req.write(body); req.end(); }); - } catch { + } catch (e) { + log.warn('uploadGroupNoticeImage failed: %s', e instanceof Error ? (e.stack ?? e.message) : String(e)); return undefined; } } @@ -260,7 +267,8 @@ export async function deleteGroupNotice( false ); return ret?.ec === 0; - } catch { + } catch (e) { + log.warn('deleteGroupNotice failed (group=%s fid=%s): %s', groupCode, fid, e instanceof Error ? (e.stack ?? e.message) : String(e)); return false; } } \ No newline at end of file diff --git a/packages/core/src/onebot/instance.ts b/packages/core/src/onebot/instance.ts index 7a57b9ea..1e42cfab 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/core/src/onebot/instance.ts @@ -93,7 +93,9 @@ export class OneBotInstance { this.apiHandler = new ApiHandler(buildApiContext(ctx), uinNum > 0 ? uinNum : undefined); this.networkManager = new OneBotNetworkManager(); this.installAdaptersFromConfig(config); - void this.networkManager.openAll(); + void this.networkManager.openAll().catch((err) => { + this.log.warn('openAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); this.startHeartbeat(); this.rkeyCache.warmUp(this.bridge, this.uin); @@ -104,7 +106,9 @@ export class OneBotInstance { } reloadConfig(config: OneBotConfig): void { - void this.applyConfigDiff(config); + void this.applyConfigDiff(config).catch((err) => { + this.log.warn('applyConfigDiff failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); } dispose(): void { @@ -112,7 +116,9 @@ export class OneBotInstance { this.stopHeartbeat(); this.disposeEventPipeline?.(); this.disposeEventPipeline = null; - void this.networkManager.closeAll(); + void this.networkManager.closeAll().catch((err) => { + this.log.warn('closeAll failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); this.messageStore.close(); this.mediaStore.close(); } @@ -141,8 +147,12 @@ export class OneBotInstance { this.cacheMessageEvent(event); this.logReceivedMessage(event); // NetworkManager builds the dispatch payload once and fans out to every - // active adapter in parallel via Promise.allSettled. - void this.networkManager.emitEvent(event); + // active adapter in parallel via Promise.allSettled — per-adapter errors + // are already isolated, so the outer promise should never reject. The + // .catch is a belt-and-suspenders guard against future refactors. + void this.networkManager.emitEvent(event).catch((err) => { + this.log.warn('emitEvent failed: %s', err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); } private buildNetworkContext(): NetworkAdapterContext { diff --git a/packages/core/src/onebot/message-parser.ts b/packages/core/src/onebot/message-parser.ts index 2d9f7950..f971aa0f 100644 --- a/packages/core/src/onebot/message-parser.ts +++ b/packages/core/src/onebot/message-parser.ts @@ -4,6 +4,9 @@ import type { MessageElement } from '../bridge/events'; import type { JsonValue, JsonObject } from './types'; +import { createLogger } from '../utils/logger'; + +const log = createLogger('MsgParser'); export interface ParseMessageOptions { resolveReplySequence?: (replyMessageId: number) => number | null; @@ -271,7 +274,7 @@ async function segmentToElement(type: string, data: Record, opt const musicJson = await resp.text(); return { type: 'json', text: musicJson }; } catch (e) { - console.warn(`[MsgParser] music sign failed: ${e}, falling back to local card`); + log.warn('music sign failed: %s, falling back to local card', e instanceof Error ? e.message : String(e)); // Fallback: build a basic card locally const title = String(data.title ?? 'Music'); const jsonData = JSON.stringify({ diff --git a/packages/core/src/onebot/network/http-post-adapter.ts b/packages/core/src/onebot/network/http-post-adapter.ts index b32af2e7..15ec6ff1 100644 --- a/packages/core/src/onebot/network/http-post-adapter.ts +++ b/packages/core/src/onebot/network/http-post-adapter.ts @@ -77,7 +77,9 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter { if (!this.isEnabled) return; const json = pickDispatchJson(payload, this.options); if (json === null) return; - void this.postEvent(json, event); + void this.postEvent(json, event).catch((err) => { + this.log.warn('[%s] postEvent threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); } private async postEvent(payload: string, event: JsonObject): Promise { diff --git a/packages/core/src/onebot/network/ws-client-adapter.ts b/packages/core/src/onebot/network/ws-client-adapter.ts index 348a3137..c38120e0 100644 --- a/packages/core/src/onebot/network/ws-client-adapter.ts +++ b/packages/core/src/onebot/network/ws-client-adapter.ts @@ -119,7 +119,9 @@ export class WsClientAdapter extends IOneBotNetworkAdapter { }); socket.on('message', (raw: Buffer) => { - void this.handleApiMessage(socket, raw); + void this.handleApiMessage(socket, raw).catch((err) => { + this.log.warn('[%s] handleApiMessage threw: %s', this.name, err instanceof Error ? (err.stack ?? err.message) : String(err)); + }); }); socket.on('close', () => { From 257686eac6517c9fc860d7259682384e108985ac Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 12:32:18 +0800 Subject: [PATCH 33/51] feat(logger): identity-aware readable event rendering MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Notice events (recall / join / leave / poke / admin / mute / essence / request / invite) and the received-message log now resolve group IDs and user IDs against the Identity cache so output reads as human names instead of raw QQ numbers. Before: [Event] 群撤回 12345 | 67890 被 99999 撤回 [Event] 群 12345 | NickName(67890): ID:42 你好 [图片] After: [Event] 群撤回 [SnowLuma群(12345)] | [Alice(67890)] 被 [Bob(99999)] 撤回 [Event] 群 [SnowLuma群(12345)] | [Alice(67890)]: ID:42 你好 [图片] Reply segments now expand one level via messageStore.findEvent — "[回复:42]" becomes "[回复 [Alice(100)]: 早安]" when the original is still in the message store, falling back to the bare id when it isn't. New file utils/event-format.ts owns: - formatGroup / formatUser identity-aware name resolution - formatMessageSegments shared element preview (replaces the inline switch in logReceivedMessage) - formatReply one-level reply chain expansion - formatEvent notice-class event renderer Every formatter wraps its lookup in try/catch and degrades to the prior numeric form on cache miss / throw, so log formatting can never crash the calling path. The QQ numeric ID is preserved alongside the name so third-party parsers that scrape uids still find them. 26 unit tests cover cache hit / miss, malformed input, throw recovery, and per-event-kind rendering shapes. --- packages/core/src/bridge/packet-pipeline.ts | 71 ++---- packages/core/src/onebot/instance.ts | 77 +++--- packages/core/src/utils/event-format.ts | 207 ++++++++++++++++ packages/core/tests/event-format.test.ts | 247 ++++++++++++++++++++ 4 files changed, 518 insertions(+), 84 deletions(-) create mode 100644 packages/core/src/utils/event-format.ts create mode 100644 packages/core/tests/event-format.test.ts diff --git a/packages/core/src/bridge/packet-pipeline.ts b/packages/core/src/bridge/packet-pipeline.ts index 19654a08..f6df7002 100644 --- a/packages/core/src/bridge/packet-pipeline.ts +++ b/packages/core/src/bridge/packet-pipeline.ts @@ -21,10 +21,23 @@ import type { QQEventVariant } from './events'; import type { IdentityService } from './identity-service'; import type { BridgeEventBus } from './event-bus'; import { createLogger, type Logger } from '../utils/logger'; +import { formatEvent } from '../utils/event-format'; const moduleLog = createLogger('Bridge'); const moduleEventLog = createLogger('Event'); +// Notice kinds that get logged as a warning (operationally important +// state changes that an operator probably wants to see at default +// info level). Everything else falls through to info. +const WARN_EVENT_KINDS = new Set([ + 'group_recall', + 'friend_recall', + 'group_member_leave', + 'group_mute', + 'friend_request', + 'group_invite', +]); + type GroupMemberIdentityEvent = Extract; export type CmdParser = (pkt: PacketInfo, identity: IdentityService) => QQEventVariant[]; @@ -81,7 +94,7 @@ export class IncomingPacketPipeline { }); } else { this.handleSideEffects(event); - printEvent(this.eventLog, event); + printEvent(this.eventLog, this.deps.identity, event); this.emit(event); } } @@ -239,50 +252,16 @@ export class IncomingPacketPipeline { } } -function formatEventUser(uin: number, uid?: string): string { - if (uin > 0) return String(uin); - return uid || '未知用户'; -} - -function printEvent(log: Logger, event: QQEventVariant): void { - switch (event.kind) { - case 'group_message': - case 'friend_message': - case 'temp_message': - // Message logging is handled by OneBot layer with message ID - break; - case 'group_recall': - log.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin); - break; - case 'friend_recall': - log.warn('私聊撤回 %d 撤回了消息', event.userUin); - break; - case 'group_member_join': - log.info('入群 %s 加入 %d', formatEventUser(event.userUin, event.userUid), event.groupId); - break; - case 'group_member_leave': - log.warn('退群 %s %s %d', formatEventUser(event.userUin, event.userUid), event.isKick ? '被踢出' : '退出', event.groupId); - break; - case 'group_mute': - log.warn('禁言 %d | %d %d秒', event.groupId, event.userUin, event.duration); - break; - case 'group_admin': - log.info('管理 %d | %d %s管理员', event.groupId, event.userUin, event.set ? '+' : '-'); - break; - case 'friend_poke': - log.info('戳一戳 %d -> %d', event.userUin, event.targetUin); - break; - case 'group_poke': - log.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin); - break; - case 'friend_request': - log.warn('好友请求 %d: %s', event.fromUin, event.message); - break; - case 'group_invite': - log.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId); - break; - case 'group_essence': - log.info('精华 %d | %s精华', event.groupId, event.set ? '+' : '-'); - break; +function printEvent(log: Logger, identity: IdentityService, event: QQEventVariant): void { + // Message-class events (group/friend/temp message) get rendered by the + // OneBot layer's logReceivedMessage — its output already includes the + // assigned message ID, which the raw packet doesn't have. Returning + // null here is the formatter's signal to skip. + const message = formatEvent(identity, event); + if (!message) return; + if (WARN_EVENT_KINDS.has(event.kind)) { + log.warn('%s', message); + } else { + log.info('%s', message); } } diff --git a/packages/core/src/onebot/instance.ts b/packages/core/src/onebot/instance.ts index 1e42cfab..1d2cefcc 100644 --- a/packages/core/src/onebot/instance.ts +++ b/packages/core/src/onebot/instance.ts @@ -10,7 +10,7 @@ import { RKeyCache } from './instance-rkey'; import { buildApiContext, type OneBotInstanceContext } from './instance-context'; import { registerEventPipeline } from './event-pipeline'; import { GROUP_MESSAGE_EVENT, PRIVATE_MESSAGE_EVENT, hashMessageIdInt32 } from './message-id'; -import type { JsonObject, MessageMeta, OneBotConfig, NetworkBase } from './types'; +import type { JsonObject, JsonValue, MessageMeta, OneBotConfig, NetworkBase } from './types'; import { OneBotNetworkManager, WsServerAdapter, @@ -20,6 +20,7 @@ import { type NetworkAdapterContext, } from './network'; import { createLogger, type Logger } from '../utils/logger'; +import { formatGroup, formatMessageSegments, formatReply, formatUser } from '../utils/event-format'; const moduleLog = createLogger('Event'); @@ -239,56 +240,56 @@ export class OneBotInstance { const messageId = toInt(event.message_id); const isGroup = event.message_type === 'group'; - - // Build message preview - const parts: string[] = []; + const idStr = `ID:${messageId}`; + const selfTag = isSelf ? '[自身] ' : ''; + const identity = this.bridge.identity; + + // Walk the segment array once: render via the shared formatter for + // non-reply segments, and resolve `reply` segments through the + // message store so the chain reference becomes legible + // ("[回复 : ...]" instead of "[回复:1234567890]"). + const renderedParts: string[] = []; const message = event.message; - if (Array.isArray(message)) { for (const seg of message) { if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; - const type = String(seg.type ?? ''); - const data: Record = ( - typeof seg.data === 'object' && seg.data !== null && !Array.isArray(seg.data) - ) ? seg.data : {}; - - if (type === 'text' && data.text) { - const text = String(data.text); - const preview = text.length > 50 ? text.substring(0, 50) + '...' : text; - parts.push(preview); - } else if (type === 'image') { - parts.push('[图片]'); - } else if (type === 'face') { - parts.push('[表情]'); - } else if (type === 'at') { - parts.push(`@${data.qq || ''}`); - } else if (type === 'reply') { - parts.push(`[回复:${data.id || ''}]`); - } else if (type === 'record') { - parts.push('[语音]'); - } else if (type === 'video') { - parts.push('[视频]'); + const type = String((seg as JsonObject).type ?? ''); + const data = (typeof (seg as JsonObject).data === 'object' && (seg as JsonObject).data !== null && !Array.isArray((seg as JsonObject).data)) + ? (seg as JsonObject).data as Record + : {}; + if (type === 'reply') { + const replyId = toInt(data.id); + renderedParts.push(formatReply(this.messageStore, identity, replyId)); } else { - parts.push(`[${type}]`); + renderedParts.push(formatMessageSegments([seg as JsonValue])); } } + } else if (typeof message === 'string') { + renderedParts.push(formatMessageSegments(message)); } - - const content = parts.join(' ').trim() || '[空消息]'; - const idStr = `ID:${messageId}`; - const selfTag = isSelf ? '[自身] ' : ''; - + const content = renderedParts.join(' ').trim() || '[空消息]'; + if (isGroup) { const groupId = toInt(event.group_id); const userId = toInt(event.user_id); - const sender = event.sender as any; - const nickname = sender?.card || sender?.nickname || String(userId); - this.log.success(`${selfTag}群 ${groupId} | ${nickname}(${userId}): ${idStr} ${content}`); + const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender)) + ? event.sender as JsonObject + : {}; + const nicknameFromEvent = (sender.card as string) || (sender.nickname as string) || ''; + const userPart = nicknameFromEvent + ? `[${nicknameFromEvent}(${userId})]` + : formatUser(identity, groupId, userId); + this.log.success(`${selfTag}群 ${formatGroup(identity, groupId)} | ${userPart}: ${idStr} ${content}`); } else { const userId = toInt(event.user_id); - const sender = event.sender as any; - const nickname = sender?.nickname || String(userId); - this.log.success(`${selfTag}私聊 ${nickname}(${userId}): ${idStr} ${content}`); + const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender)) + ? event.sender as JsonObject + : {}; + const nicknameFromEvent = (sender.nickname as string) || ''; + const userPart = nicknameFromEvent + ? `[${nicknameFromEvent}(${userId})]` + : formatUser(identity, undefined, userId); + this.log.success(`${selfTag}私聊 ${userPart}: ${idStr} ${content}`); } } diff --git a/packages/core/src/utils/event-format.ts b/packages/core/src/utils/event-format.ts new file mode 100644 index 00000000..ffa1aa28 --- /dev/null +++ b/packages/core/src/utils/event-format.ts @@ -0,0 +1,207 @@ +// Identity-aware, one-line readable rendering for log output. +// +// Two layers consume this: +// - bridge/packet-pipeline.ts → notice events (recall / join / poke / …) +// - onebot/instance.ts → received-message log +// +// All formatters are defensive: any field lookup that throws falls +// back to the raw numeric form, so a malformed event or stale +// Identity cache never crashes the logger. Cache misses simply +// degrade to the previous "just print the uin / groupId" output. + +import type { IdentityService } from '../bridge/identity-service'; +import type { QQEventVariant } from '../bridge/events'; +import type { MessageStore } from '../onebot/message-store'; +import type { JsonObject, JsonValue } from '../onebot/types'; + +const MAX_TEXT_PREVIEW = 50; +const MAX_REPLY_BODY_PREVIEW = 30; + +/** "[群名(12345)]" if known, else "12345" (or "0" if missing). */ +export function formatGroup(identity: IdentityService, groupId: number): string { + if (!groupId || groupId <= 0) return String(groupId || 0); + try { + const g = identity.findGroup(groupId); + const name = g?.groupName?.trim(); + return name ? `[${name}(${groupId})]` : String(groupId); + } catch { + return String(groupId); + } +} + +/** + * "[card-or-nick(uin)]" when the uin is in the group-member or friend + * roster; falls back to the bare uin string. When only a uid is known + * (no uin yet) the uid is returned as-is so the line still references + * someone — better than logging "0". + */ +export function formatUser( + identity: IdentityService, + groupId: number | undefined, + uin: number, + uid?: string, +): string { + try { + if (!uin || uin <= 0) return uid ? uid : '0'; + if (groupId !== undefined && groupId > 0) { + const member = identity.findGroupMember(groupId, uin); + const name = member?.card?.trim() || member?.nickname?.trim(); + if (name) return `[${name}(${uin})]`; + } + const friend = identity.findFriend(uin); + const fname = friend?.remark?.trim() || friend?.nickname?.trim(); + if (fname) return `[${fname}(${uin})]`; + return String(uin); + } catch { + return String(uin); + } +} + +/** + * One-line preview of an OneBot-shape message (array of segments or + * raw string). Element rendering matches the existing logReceivedMessage + * vocabulary so this is a drop-in replacement, with a few additions + * (json / xml / markdown / forward / poke / file). + */ +export function formatMessageSegments(message: JsonValue): string { + try { + if (typeof message === 'string') { + return truncate(message, MAX_TEXT_PREVIEW) || '[空消息]'; + } + if (!Array.isArray(message)) return '[空消息]'; + const parts: string[] = []; + for (const seg of message) { + if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue; + const obj = seg as JsonObject; + const type = String(obj.type ?? ''); + const data = (typeof obj.data === 'object' && obj.data !== null && !Array.isArray(obj.data)) + ? obj.data as Record + : {}; + parts.push(renderSegment(type, data)); + } + return parts.join(' ').trim() || '[空消息]'; + } catch { + return '[消息渲染异常]'; + } +} + +function renderSegment(type: string, data: Record): string { + switch (type) { + case 'text': return truncate(String(data.text ?? ''), MAX_TEXT_PREVIEW); + case 'image': return '[图片]'; + case 'face': return '[表情]'; + case 'mface': return data.text ? `[${String(data.text)}]` : '[表情]'; + case 'at': return data.qq === 'all' ? '@全体成员' : `@${data.qq ?? ''}`; + case 'reply': return `[回复:${data.id ?? ''}]`; + case 'record': return '[语音]'; + case 'video': return '[视频]'; + case 'file': return data.file ? `[文件:${truncate(String(data.file), 20)}]` : '[文件]'; + case 'json': return '[JSON]'; + case 'xml': return '[XML]'; + case 'markdown': return '[Markdown]'; + case 'forward': return '[聊天记录]'; + case 'poke': return '[戳一戳]'; + default: return `[${type}]`; + } +} + +function truncate(s: string, max: number): string { + return s.length > max ? `${s.slice(0, max)}...` : s; +} + +/** + * Resolve a `reply` segment's referenced message and return a short + * "[回复 user: body...]" string. On miss (older than store retention, + * never seen, lookup throws) falls back to "[回复:]" so the chain + * reference is at least preserved. + * + * Deliberately one level deep — we don't recurse into the reply's own + * reply. Long chains aren't worth the runtime cost in the hot path, + * and a 1-level peek catches 90% of real-world "what's this referring + * to" questions. + */ +export function formatReply( + messageStore: MessageStore, + identity: IdentityService, + replyId: number, +): string { + try { + if (!replyId) return '[回复:0]'; + const event = messageStore.findEvent(replyId); + if (!event) return `[回复:${replyId}]`; + const isGroup = event.message_type === 'group'; + const uin = toIntOrZero(event.user_id); + const groupId = isGroup ? toIntOrZero(event.group_id) : undefined; + + // Prefer cache; if cache miss, use the sender fields baked into the + // stored event itself (those came from the original receive path + // when the roster was warm). + let userPart = formatUser(identity, groupId, uin); + if (userPart === String(uin) && uin > 0) { + const sender = (typeof event.sender === 'object' && event.sender !== null && !Array.isArray(event.sender)) + ? event.sender as JsonObject + : {}; + const fallback = ((sender.card as string) || (sender.nickname as string) || '').trim(); + if (fallback) userPart = `[${fallback}(${uin})]`; + } + + const body = truncate(formatMessageSegments(event.message as JsonValue), MAX_REPLY_BODY_PREVIEW); + return `[回复 ${userPart}: ${body}]`; + } catch { + return `[回复:${replyId}]`; + } +} + +function toIntOrZero(v: unknown): number { + if (typeof v === 'number' && Number.isFinite(v)) return v; + if (typeof v === 'string') { + const n = Number.parseInt(v, 10); + return Number.isFinite(n) ? n : 0; + } + return 0; +} + +/** + * Readable one-line rendering of a notice-class QQEventVariant. Returns + * null for kinds the OneBot layer's message log already renders + * (group_message / friend_message / temp_message / group_file_upload / + * friend_add — those have richer dedicated paths). + */ +export function formatEvent(identity: IdentityService, event: QQEventVariant): string | null { + try { + switch (event.kind) { + case 'group_message': + case 'friend_message': + case 'temp_message': + case 'group_file_upload': + case 'friend_add': + return null; + case 'group_recall': + return `群撤回 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.authorUin)} 被 ${formatUser(identity, event.groupId, event.operatorUin)} 撤回`; + case 'friend_recall': + return `私聊撤回 ${formatUser(identity, undefined, event.userUin)} 撤回了消息`; + case 'group_member_join': + return `入群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} 加入 ${formatGroup(identity, event.groupId)}`; + case 'group_member_leave': + return `退群 ${formatUser(identity, event.groupId, event.userUin, event.userUid)} ${event.isKick ? '被踢出' : '退出'} ${formatGroup(identity, event.groupId)}`; + case 'group_mute': + return `禁言 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.duration}秒`; + case 'group_admin': + return `管理 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} ${event.set ? '+' : '-'}管理员`; + case 'friend_poke': + return `戳一戳 ${formatUser(identity, undefined, event.userUin)} -> ${formatUser(identity, undefined, event.targetUin)}`; + case 'group_poke': + return `群戳 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.userUin)} -> ${formatUser(identity, event.groupId, event.targetUin)}`; + case 'friend_request': + return `好友请求 ${formatUser(identity, undefined, event.fromUin)}: ${event.message}`; + case 'group_invite': + return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`; + case 'group_essence': + return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`; + default: + return null; + } + } catch { + return null; + } +} diff --git a/packages/core/tests/event-format.test.ts b/packages/core/tests/event-format.test.ts new file mode 100644 index 00000000..fd4400e9 --- /dev/null +++ b/packages/core/tests/event-format.test.ts @@ -0,0 +1,247 @@ +// Tests for utils/event-format.ts. +// +// Each formatter is defensive about cache misses / malformed input — +// these tests cover both the happy paths (resolves names from +// Identity / MessageStore) and the degraded paths (falls back to the +// raw uin / groupId without crashing). + +import { describe, expect, it } from 'vitest'; +import { + formatEvent, + formatGroup, + formatMessageSegments, + formatReply, + formatUser, +} from '../src/utils/event-format'; +import type { QQEventVariant } from '../src/bridge/events'; + +// ─── Test fakes (just the find* surface event-format uses) ─── + +function fakeIdentity(opts: { + groups?: Record; + members?: Record; + friends?: Record; +} = {}): any { + return { + findGroup: (gid: number) => opts.groups?.[gid] ?? null, + findGroupMember: (gid: number, uin: number) => opts.members?.[`${gid}/${uin}`] ?? null, + findFriend: (uin: number) => opts.friends?.[uin] ?? null, + }; +} + +function fakeMessageStore(events: Record>): any { + return { + findEvent: (id: number) => events[id] ?? null, + }; +} + +describe('formatGroup', () => { + it('renders [groupName(id)] when the group is in cache', () => { + const id = fakeIdentity({ groups: { 123: { groupName: 'TestGroup' } } }); + expect(formatGroup(id, 123)).toBe('[TestGroup(123)]'); + }); + + it('falls back to bare id on cache miss', () => { + const id = fakeIdentity(); + expect(formatGroup(id, 123)).toBe('123'); + }); + + it('handles 0 / missing group id without crashing', () => { + const id = fakeIdentity(); + expect(formatGroup(id, 0)).toBe('0'); + }); + + it('falls back to bare id if findGroup throws', () => { + const id = { findGroup: () => { throw new Error('db dead'); } } as any; + expect(formatGroup(id, 123)).toBe('123'); + }); +}); + +describe('formatUser', () => { + it('prefers group-member card over nickname', () => { + const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'Card', nickname: 'Nick' } } }); + expect(formatUser(id, 1, 100)).toBe('[Card(100)]'); + }); + + it('falls back to nickname when card is empty', () => { + const id = fakeIdentity({ members: { '1/100': { uin: 100, card: '', nickname: 'Nick' } } }); + expect(formatUser(id, 1, 100)).toBe('[Nick(100)]'); + }); + + it('falls back to friend list when not a group member', () => { + const id = fakeIdentity({ friends: { 100: { uin: 100, nickname: 'FriendNick' } } }); + expect(formatUser(id, undefined, 100)).toBe('[FriendNick(100)]'); + }); + + it('prefers friend remark over nickname', () => { + const id = fakeIdentity({ friends: { 100: { uin: 100, nickname: 'A', remark: 'B' } } }); + expect(formatUser(id, undefined, 100)).toBe('[B(100)]'); + }); + + it('falls back to uin on full cache miss', () => { + const id = fakeIdentity(); + expect(formatUser(id, 1, 100)).toBe('100'); + }); + + it('falls back to uid when only uid is available', () => { + const id = fakeIdentity(); + expect(formatUser(id, undefined, 0, 'u_abc')).toBe('u_abc'); + }); +}); + +describe('formatMessageSegments', () => { + it('renders text segments and truncates beyond 50 chars', () => { + const long = 'a'.repeat(80); + expect(formatMessageSegments([{ type: 'text', data: { text: long } }])) + .toBe(`${'a'.repeat(50)}...`); + }); + + it('handles known media types and at/reply', () => { + const out = formatMessageSegments([ + { type: 'text', data: { text: 'hi' } }, + { type: 'image', data: {} }, + { type: 'at', data: { qq: 12345 } }, + { type: 'at', data: { qq: 'all' } }, + { type: 'reply', data: { id: 999 } }, + { type: 'face', data: {} }, + { type: 'video', data: {} }, + { type: 'record', data: {} }, + ]); + expect(out).toBe('hi [图片] @12345 @全体成员 [回复:999] [表情] [视频] [语音]'); + }); + + it('renders unknown segment types as [type]', () => { + expect(formatMessageSegments([{ type: 'something_new', data: {} }])) + .toBe('[something_new]'); + }); + + it('renders a string message as text (truncated)', () => { + expect(formatMessageSegments('hello')).toBe('hello'); + expect(formatMessageSegments('a'.repeat(60))).toBe(`${'a'.repeat(50)}...`); + }); + + it('returns [空消息] for empty arrays / non-array / null', () => { + expect(formatMessageSegments([])).toBe('[空消息]'); + expect(formatMessageSegments(null as any)).toBe('[空消息]'); + expect(formatMessageSegments({} as any)).toBe('[空消息]'); + }); +}); + +describe('formatReply', () => { + it('renders the resolved sender + body preview when the original is in the store', () => { + const store = fakeMessageStore({ + 42: { + message_type: 'group', + group_id: 1, + user_id: 100, + sender: { card: 'OrigSender' }, + message: [{ type: 'text', data: { text: '早安' } }], + }, + }); + const id = fakeIdentity({ members: { '1/100': { uin: 100, card: 'OrigSender' } } }); + expect(formatReply(store, id, 42)).toBe('[回复 [OrigSender(100)]: 早安]'); + }); + + it('falls back to [回复:] when the original is missing', () => { + const store = fakeMessageStore({}); + const id = fakeIdentity(); + expect(formatReply(store, id, 9999)).toBe('[回复:9999]'); + }); + + it('uses the sender baked into the stored event when cache misses', () => { + const store = fakeMessageStore({ + 42: { + message_type: 'private', + user_id: 100, + sender: { nickname: 'StoredNick' }, + message: [{ type: 'text', data: { text: 'hi' } }], + }, + }); + const id = fakeIdentity(); // no cache + expect(formatReply(store, id, 42)).toBe('[回复 [StoredNick(100)]: hi]'); + }); + + it('truncates the body preview to 30 chars', () => { + const store = fakeMessageStore({ + 42: { + message_type: 'private', + user_id: 100, + sender: { nickname: 'X' }, + message: [{ type: 'text', data: { text: 'a'.repeat(80) } }], + }, + }); + const id = fakeIdentity(); + const out = formatReply(store, id, 42); + // Inner text gets truncated to 50 by formatMessageSegments, then to 30 here + expect(out).toContain('...'); + expect(out.length).toBeLessThan(80); + }); + + it('returns the fallback when findEvent throws', () => { + const store = { findEvent: () => { throw new Error('store dead'); } } as any; + const id = fakeIdentity(); + expect(formatReply(store, id, 42)).toBe('[回复:42]'); + }); +}); + +describe('formatEvent', () => { + const id = fakeIdentity({ + groups: { 1: { groupName: 'Grp' } }, + members: { + '1/100': { uin: 100, card: 'Alice' }, + '1/200': { uin: 200, card: 'Bob' }, + '1/300': { uin: 300, nickname: 'Carol' }, + }, + friends: { + 500: { uin: 500, nickname: 'FriendA' }, + 600: { uin: 600, nickname: 'FriendB' }, + }, + }); + + it('returns null for kinds rendered elsewhere', () => { + expect(formatEvent(id, { kind: 'group_message' } as QQEventVariant)).toBeNull(); + expect(formatEvent(id, { kind: 'friend_message' } as QQEventVariant)).toBeNull(); + expect(formatEvent(id, { kind: 'temp_message' } as QQEventVariant)).toBeNull(); + }); + + it('renders group_recall with all three name slots', () => { + expect(formatEvent(id, { + kind: 'group_recall', + groupId: 1, authorUin: 100, operatorUin: 200, + } as QQEventVariant)) + .toBe('群撤回 [Grp(1)] | [Alice(100)] 被 [Bob(200)] 撤回'); + }); + + it('renders group_member_join with group name and joiner', () => { + expect(formatEvent(id, { + kind: 'group_member_join', + groupId: 1, userUin: 300, userUid: '', + } as QQEventVariant)) + .toBe('入群 [Carol(300)] 加入 [Grp(1)]'); + }); + + it('renders group_poke with both endpoints', () => { + expect(formatEvent(id, { + kind: 'group_poke', + groupId: 1, userUin: 100, targetUin: 200, + } as QQEventVariant)) + .toBe('群戳 [Grp(1)] | [Alice(100)] -> [Bob(200)]'); + }); + + it('renders friend_poke without group context', () => { + expect(formatEvent(id, { + kind: 'friend_poke', + userUin: 500, targetUin: 600, + } as QQEventVariant)) + .toBe('戳一戳 [FriendA(500)] -> [FriendB(600)]'); + }); + + it('degrades to numeric IDs when nothing is cached', () => { + const empty = fakeIdentity(); + expect(formatEvent(empty, { + kind: 'group_recall', + groupId: 1, authorUin: 100, operatorUin: 200, + } as QQEventVariant)) + .toBe('群撤回 1 | 100 被 200 撤回'); + }); +}); From e04a539b269aa950caaf1e452e36062e4a754a62 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 12:47:34 +0800 Subject: [PATCH 34/51] fix(logger): pass identity to the second printEvent call site The previous commit (257686e) widened printEvent's signature to take IdentityService but only updated the synchronous call at line 97. The async post-refresh dispatch path (line 127, called when a group member join arrives without a resolved uin) still used the old two-arg form, which CI caught as TS2554. Local tsc somehow didn't flag it on the editing machine. Both sites now pass this.deps.identity so the readable rendering applies to both prompt and post-refresh dispatch paths. --- packages/core/src/bridge/packet-pipeline.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/core/src/bridge/packet-pipeline.ts b/packages/core/src/bridge/packet-pipeline.ts index f6df7002..1697a15e 100644 --- a/packages/core/src/bridge/packet-pipeline.ts +++ b/packages/core/src/bridge/packet-pipeline.ts @@ -124,7 +124,7 @@ export class IncomingPacketPipeline { } this.handleSideEffects(event, refreshed); - printEvent(this.eventLog, event); + printEvent(this.eventLog, this.deps.identity, event); this.emit(event); } From 4a49c55775459a2d2b6557365b06991d83029acf Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 13:07:10 +0800 Subject: [PATCH 35/51] fix(hook): refresh pipe snapshot before verifying unload took MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After native unload returns, the verification check if (pipeWatcher.isPipeLive(pid)) { ... unload-failed message ... } read PipeWatcher's cached snapshot, which is updated every 1500ms. On Windows clicking "Unload" in WebUI almost always tripped this: the native unload succeeded and the kernel pipe object was gone, but the watcher's cached "live" state from the previous tick was still fresh, so the session reported "DLL卸载失败:命名管道仍然存在" even though the DLL was successfully unloaded. The user then sees the status flip back to connecting and waits for a real (cached) refresh. PipeWatcher already exposes tickNow() for exactly this situation — the load path doesn't need it because injection's verification runs async via onPipeUp, but unload verifies inline. HookSessionDeps.pipeWatcher gains an optional `tickNow` and unloadInternal awaits it before reading isPipeLive. Existing test mocks that pass only `{ isPipeLive }` keep working (optional chain is a no-op there). New regression test covers the production scenario — stale-true cache flipped to false by tickNow. --- packages/core/src/hook/hook-session.ts | 15 ++++++++++--- packages/core/tests/hook-session.test.ts | 28 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 3 deletions(-) diff --git a/packages/core/src/hook/hook-session.ts b/packages/core/src/hook/hook-session.ts index a8f7f16b..d8c183ec 100644 --- a/packages/core/src/hook/hook-session.ts +++ b/packages/core/src/hook/hook-session.ts @@ -14,8 +14,13 @@ export type HookSessionDeps = { }; makeClient: (pid: number) => QqHookClient; /** Sync fast-path check used by load() to skip re-injection when a - * prior SnowLuma run left a working pipe behind. */ - pipeWatcher: { isPipeLive: (pid: number) => boolean }; + * prior SnowLuma run left a working pipe behind. `tickNow` forces a + * fresh poll — used after unload to dodge the up-to-1500ms cache + * staleness that would otherwise false-flag a successful unload. */ + pipeWatcher: { + isPipeLive: (pid: number) => boolean; + tickNow?: () => Promise; + }; /** Sink for parsed packets. Called with the BridgeManager-shaped * PacketInfo for every packet received while logged in. If omitted, * packets are dropped (useful in unit tests that don't care). */ @@ -254,7 +259,11 @@ export class HookSession extends EventEmitter { this._uin = '0'; // Verify the unload took: if the pipe is still up the DLL is still - // resident. Drop back to 'connecting' and let the watcher reconnect. + // resident. The cached snapshot is up to 1500ms stale and we just + // changed the world, so force a fresh poll first — otherwise even + // a successful unload reads as "pipe still live" until the next + // background tick runs and we'd report a spurious failure. + await this.pipeWatcher.tickNow?.(); if (this.pipeWatcher.isPipeLive(this.pid)) { this._error = 'DLL卸载失败:命名管道仍然存在,watcher将自动重连'; this.setStatus('connecting', this._error); diff --git a/packages/core/tests/hook-session.test.ts b/packages/core/tests/hook-session.test.ts index f6c24c5c..26127d27 100644 --- a/packages/core/tests/hook-session.test.ts +++ b/packages/core/tests/hook-session.test.ts @@ -254,6 +254,34 @@ describe('HookSession — unload', () => { expect(info.status).toBe('connecting'); expect(info.error).toContain('命名管道仍然存在'); }); + + it('forces a fresh tick before verifying so a stale snapshot does not false-flag a successful unload', async () => { + // Reproduces the Windows-WebUI bug: PipeWatcher's cached snapshot is + // up to 1500ms stale, so right after a successful native unload the + // pre-fix code would read isPipeLive() == true and report failure + // even though the DLL is gone. With the fix, tickNow() refreshes + // the snapshot first and verification correctly sees the pipe down. + const pid = 5555; + let pipeLive = true; // initial cached state: pipe is live + const tickNow = vi.fn(async () => { pipeLive = false; }); // OS poll says: gone now + + const session = new HookSession(pid, { + injector: { + inject: vi.fn(() => ({ method: 'loadModuleManual' as const, handle: DUMMY_HANDLE })), + unload: vi.fn(), + }, + makeClient: () => new FakeClient() as unknown as QqHookClient, + pipeWatcher: { isPipeLive: () => pipeLive, tickNow }, + }); + await session.load(); + pipeLive = true; // ensure the pre-check snapshot says "live" + + const info = await session.unload(); + + expect(tickNow).toHaveBeenCalledOnce(); + expect(info.status).toBe('available'); + expect(info.error).toBe(''); + }); }); describe('HookSession — serialization', () => { From 4c513c015dd393e4999fc0632580facafd8c7b6a Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 13:15:05 +0800 Subject: [PATCH 36/51] feat(logger): runtime log level toggle via WebUI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The console / subscriber level was captured at module load (`const MIN_LEVEL = resolveMinLevel()`), so any change to SNOWLUMA_LOG_LEVEL after Node started had no effect — restart was the only way to flip levels, which makes "go to debug for 30s to see what's happening" pretty painful. logger.ts now keeps `currentLevel` mutable and exports setLogLevel() / getLogLevel(). The env var still seeds it on startup; nothing about the boot-time behavior changes. File transport remains unaffected — it always sees debug-and-up. WebUI gets two new endpoints, both behind the existing auth middleware: GET /api/logs/level → { level, levels } POST /api/logs/level body → { level: 'debug' } updates it Logs page picks up a "服务端级别" row of pills next to the existing client-side filter pills, so an operator can flip the console firehose on/off in one click without touching env vars or restarting the bot. The label clarifies that file logging stays at debug regardless. --- packages/core/src/utils/logger.ts | 26 +++++++- packages/core/src/webui/server.ts | 16 ++++- packages/core/tests/logger.test.ts | 49 ++++++++++++++- .../webui/src/components/pages/logs-page.tsx | 59 +++++++++++++++++-- packages/webui/src/lib/api/client.ts | 5 +- packages/webui/src/lib/api/types.ts | 5 ++ packages/webui/src/types.ts | 6 +- 7 files changed, 154 insertions(+), 12 deletions(-) diff --git a/packages/core/src/utils/logger.ts b/packages/core/src/utils/logger.ts index 9b4c7f0b..ce25d0b0 100644 --- a/packages/core/src/utils/logger.ts +++ b/packages/core/src/utils/logger.ts @@ -68,10 +68,32 @@ function resolveMinLevel(): LogLevel { return 'info'; } -const MIN_LEVEL = resolveMinLevel(); +// Mutable — seeded from SNOWLUMA_LOG_LEVEL at module load, but +// setLogLevel() lets WebUI / SDK callers flip it without a restart. +// Only governs console + ring buffer + subscribers; the file +// transport always sees debug-and-up regardless. +let currentLevel: LogLevel = resolveMinLevel(); function shouldLog(level: LogLevel): boolean { - return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[MIN_LEVEL]; + return LEVEL_WEIGHT[level] >= LEVEL_WEIGHT[currentLevel]; +} + +export const LOG_LEVELS: readonly LogLevel[] = ['debug', 'info', 'success', 'warn', 'error']; + +export function getLogLevel(): LogLevel { + return currentLevel; +} + +/** + * Change the console / subscriber level at runtime. Invalid input is + * a no-op (returns false). File transport is unaffected — it always + * sees every level so post-mortems remain useful. + */ +export function setLogLevel(level: string): boolean { + const lower = String(level).toLowerCase(); + if (!LOG_LEVELS.includes(lower as LogLevel)) return false; + currentLevel = lower as LogLevel; + return true; } function useColor(): boolean { diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 0c704a19..70acff33 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -2,7 +2,7 @@ import { serve } from '@hono/node-server'; import { serveStatic } from '@hono/node-server/serve-static'; import { Hono, type Context } from 'hono'; import { describeTrustProxy, makeClientIpResolver, parseTrustProxy } from './client-ip'; -import { createLogger, getRecentLogs, subscribeLogs } from '../utils/logger'; +import { createLogger, getLogLevel, getRecentLogs, LOG_LEVELS, setLogLevel, subscribeLogs } from '../utils/logger'; import { randomBytes } from 'crypto'; import type { OneBotManager } from '../onebot/manager'; import { loadOneBotConfig, saveOneBotConfig } from '../onebot/config'; @@ -340,6 +340,20 @@ export async function initWebUI( return c.json({ list: getRecentLogs(limit) }); }); + app.get('/api/logs/level', (c) => { + return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); + }); + + app.post('/api/logs/level', async (c) => { + const body = await c.req.json().catch(() => null) as { level?: unknown } | null; + const next = typeof body?.level === 'string' ? body.level : ''; + if (!setLogLevel(next)) { + return c.json({ message: `invalid level: ${next}`, levels: [...LOG_LEVELS] }, 400); + } + log.info('console log level set to %s via WebUI', getLogLevel()); + return c.json({ level: getLogLevel(), levels: [...LOG_LEVELS] }); + }); + app.get('/api/logs/stream', (c) => { const stream = new ReadableStream({ start(controller) { diff --git a/packages/core/tests/logger.test.ts b/packages/core/tests/logger.test.ts index 7ac141ea..16342153 100644 --- a/packages/core/tests/logger.test.ts +++ b/packages/core/tests/logger.test.ts @@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import fs from 'node:fs'; import os from 'node:os'; import path from 'node:path'; -import { createLogger, subscribeLogs, type LogEntry } from '../src/utils/logger'; +import { createLogger, getLogLevel, setLogLevel, subscribeLogs, type LogEntry } from '../src/utils/logger'; import { _resetFileTransportForTesting } from '../src/utils/log-file-transport'; let tmpDir: string; @@ -178,3 +178,50 @@ describe('createLogger', () => { expect(entries).toHaveLength(0); }); }); + +describe('setLogLevel / getLogLevel — runtime level toggle', () => { + // Each test restores whatever level was active going in so the suite + // ordering can't bleed state between specs. + let saved: ReturnType; + beforeEach(() => { saved = getLogLevel(); }); + afterEach(() => { setLogLevel(saved); }); + + it('setLogLevel updates getLogLevel for valid input', () => { + expect(setLogLevel('warn')).toBe(true); + expect(getLogLevel()).toBe('warn'); + expect(setLogLevel('debug')).toBe(true); + expect(getLogLevel()).toBe('debug'); + }); + + it('setLogLevel rejects unknown values without mutating state', () => { + setLogLevel('info'); + expect(setLogLevel('nonsense')).toBe(false); + expect(getLogLevel()).toBe('info'); + expect(setLogLevel('')).toBe(false); + expect(setLogLevel('Verbose')).toBe(false); + }); + + it('setLogLevel is case-insensitive', () => { + expect(setLogLevel('WARN')).toBe(true); + expect(getLogLevel()).toBe('warn'); + }); + + it('changes which entries reach the ring buffer / subscribers', () => { + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + const log = createLogger('LevelTest'); + + setLogLevel('warn'); + log.debug('hidden-debug'); + log.info('hidden-info'); + log.warn('visible-warn'); + log.error('visible-error'); + + unsub(); + + const messages = captured + .filter((e) => e.scope === 'LevelTest') + .map((e) => e.message); + expect(messages).toEqual(['visible-warn', 'visible-error']); + }); +}); diff --git a/packages/webui/src/components/pages/logs-page.tsx b/packages/webui/src/components/pages/logs-page.tsx index 36fd5669..6201bc06 100644 --- a/packages/webui/src/components/pages/logs-page.tsx +++ b/packages/webui/src/components/pages/logs-page.tsx @@ -8,10 +8,10 @@ import { Input } from '@/components/ui/input'; import { ScrollArea } from '@/components/ui/scroll-area'; import { ConfirmDialog } from '@/components/confirm-dialog'; import { cn } from '@/lib/utils'; -import type { LogEntry } from '@/types'; +import type { LogEntry, LogLevel } from '@/types'; import { useApi } from '@/lib/api'; -const levelClass: Record = { +const levelClass: Record = { debug: 'text-muted-foreground', info: 'text-primary', success: 'text-success', @@ -19,7 +19,7 @@ const levelClass: Record = { error: 'text-destructive', }; -const LEVELS: LogEntry['level'][] = ['debug', 'info', 'success', 'warn', 'error']; +const LEVELS: LogLevel[] = ['debug', 'info', 'success', 'warn', 'error']; export function LogsPage() { const api = useApi(); @@ -27,8 +27,10 @@ export function LogsPage() { const [streamStatus, setStreamStatus] = useState('连接中'); const [paused, setPaused] = useState(false); const [filter, setFilter] = useState(''); - const [enabledLevels, setEnabledLevels] = useState>(new Set(LEVELS)); + const [enabledLevels, setEnabledLevels] = useState>(new Set(LEVELS)); const [confirmClear, setConfirmClear] = useState(false); + const [serverLevel, setServerLevel] = useState(null); + const [levelBusy, setLevelBusy] = useState(false); const endRef = useRef(null); const viewportRef = useRef(null); @@ -44,6 +46,25 @@ export function LogsPage() { void loadLogs(); }, [loadLogs]); + useEffect(() => { + api.logs.getLevel().then(({ level }) => setServerLevel(level)).catch((err) => { + console.error('getLevel', err); + }); + }, [api]); + + const changeServerLevel = useCallback(async (lv: LogLevel) => { + if (lv === serverLevel || levelBusy) return; + setLevelBusy(true); + try { + const { level } = await api.logs.setLevel(lv); + setServerLevel(level); + } catch (err) { + console.error('setLevel', err); + } finally { + setLevelBusy(false); + } + }, [api, serverLevel, levelBusy]); + useEffect(() => { return api.logs.stream({ onLine: (entry) => { @@ -75,7 +96,7 @@ export function LogsPage() { }); }, [logs, filter, enabledLevels]); - const toggleLevel = (lv: LogEntry['level']) => { + const toggleLevel = (lv: LogLevel) => { setEnabledLevels((prev) => { const next = new Set(prev); if (next.has(lv)) next.delete(lv); @@ -121,7 +142,8 @@ export function LogsPage() {
-
+
+ 视图过滤 {LEVELS.map((lv) => { const active = enabledLevels.has(lv); return ( @@ -142,6 +164,31 @@ export function LogsPage() { })}
+
+ + 服务端级别 + + {LEVELS.map((lv) => { + const active = serverLevel === lv; + return ( + + ); + })} +
+
this.openLogStream(options), + getLevel: () => this.getJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`), + setLevel: (level) => + this.postJson<{ level: LogLevel; levels: LogLevel[] }>(`/api/logs/level`, { level }), }; } diff --git a/packages/webui/src/lib/api/types.ts b/packages/webui/src/lib/api/types.ts index 25b46934..01153200 100644 --- a/packages/webui/src/lib/api/types.ts +++ b/packages/webui/src/lib/api/types.ts @@ -1,6 +1,7 @@ import type { HookProcessInfo, LogEntry, + LogLevel, OneBotConfig, QQInfo, SystemInfo, @@ -69,6 +70,10 @@ export interface ApiClient { list(limit?: number): Promise; /** Subscribe to the SSE log stream. Returns a disposer. */ stream(options: LogsStreamOptions): () => void; + /** Current console / subscriber level. File output is always debug. */ + getLevel(): Promise<{ level: LogLevel; levels: LogLevel[] }>; + /** Change the console / subscriber level at runtime. No restart needed. */ + setLevel(level: LogLevel): Promise<{ level: LogLevel; levels: LogLevel[] }>; }; /** Escape hatch for endpoints not yet wrapped above. */ diff --git a/packages/webui/src/types.ts b/packages/webui/src/types.ts index 7ed9c2c7..ef65d96a 100644 --- a/packages/webui/src/types.ts +++ b/packages/webui/src/types.ts @@ -101,10 +101,14 @@ export interface SystemInfo { }; } +export type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error'; + export interface LogEntry { id: number; time: string; - level: 'debug' | 'info' | 'success' | 'warn' | 'error'; + level: LogLevel; + /** QQ uin, when the source logger was derived via `.child({ uin })`. */ + uin?: number; scope: string; message: string; line: string; From 5524c73eed37a0f59fa6981ffb12f709645a4da9 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 13:18:31 +0800 Subject: [PATCH 37/51] chore(webui): keep search engines out of the admin surface MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Even the login page leaks "there's a SnowLuma admin panel at this IP / hostname" to anyone scanning, and right now that page is publicly indexable. Three overlapping signals so we don't depend on any one being honoured: 1. Hono middleware on every response sends X-Robots-Tag: noindex, nofollow, noarchive, nosnippet, noimageindex Hardest for compliant bots to ignore — it's a header, not content. noimageindex also covers logo.png / avatar/* from showing up in image search. 2. A GET /robots.txt route returns "User-agent: * / Disallow: /" for crawlers that read it before fetching pages. Sits before the auth middleware so no token is required (otherwise the crawler would get 401 here, which it'd then refuse to obey). 3. (plus googlebot / bingbot) in index.html as a fallback for the case where a reverse proxy strips the X-Robots-Tag header. --- packages/core/src/webui/server.ts | 20 ++++++++++++++++++++ packages/webui/index.html | 4 ++++ 2 files changed, 24 insertions(+) diff --git a/packages/core/src/webui/server.ts b/packages/core/src/webui/server.ts index 70acff33..1848eb0a 100644 --- a/packages/core/src/webui/server.ts +++ b/packages/core/src/webui/server.ts @@ -116,6 +116,26 @@ export async function initWebUI( const app = new Hono(); + // ─── Anti-indexing ─────────────────────────────────────────────────────── + // The WebUI is an admin surface that has no business showing up in + // search results — even the login page leaks the existence of a + // SnowLuma instance to anyone scanning the IP. Three overlapping + // signals: a hard X-Robots-Tag on every response, a robots.txt for + // crawlers that read it before pages, and a in the + // SPA shell for the case where a proxy strips headers. + app.use('*', async (c, next) => { + await next(); + c.res.headers.set( + 'X-Robots-Tag', + 'noindex, nofollow, noarchive, nosnippet, noimageindex', + ); + }); + + app.get('/robots.txt', (c) => { + c.res.headers.set('Content-Type', 'text/plain; charset=utf-8'); + return c.body('User-agent: *\nDisallow: /\n'); + }); + // ─── Auth middleware ───────────────────────────────────────────────────── app.use('/api/*', async (c, next) => { const reqPath = c.req.path; diff --git a/packages/webui/index.html b/packages/webui/index.html index b6b77b81..b9498433 100644 --- a/packages/webui/index.html +++ b/packages/webui/index.html @@ -5,6 +5,10 @@ + + + + SnowLuma 控制台 From b94775cb6f77c71d00d48d6e82503d5679bab324 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 13:31:17 +0800 Subject: [PATCH 38/51] chore(release): v1.8.4 --- package.json | 2 +- packages/core/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 49acb6e9..b9bb169e 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.8.3", + "version": "1.8.4", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index dcfbb1bb..92e2e788 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.8.3", + "version": "1.8.4", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index 08f97c34..c09d8bcf 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.8.3", + "version": "1.8.4", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 238c3dcd..9aef3210 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.3", + "version": "1.8.4", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index 7baf9f05..f70bab9c 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.3", + "version": "1.8.4", "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 3245ccc5..e97ce0bd 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.8.3", + "version": "1.8.4", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index b5352ec2..32de0fc1 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.8.3", + "version": "1.8.4", "type": "module", "scripts": { "dev": "vite", From c62f51750a27712c64640c5020dafbcc27488bca Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 13:39:54 +0800 Subject: [PATCH 39/51] fix(oidb): drop the obsolete field 2 from OIDB 0xFE1_2 (user profile) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QQ now rejects fetchUserProfile() with: [oidb] one of uid/openid is invaild The cause: SnowLuma's request schema declared field 2 as a zero-valued uint32 (`field2: 0`) and our encoder doesn't skip 0 varints. Newer QQ NT versions reinterpret field 2 of OIDB 0xFE1_2 as `uid: string` / `openid: string`, so a varint 0 there decodes as an empty/invalid uid → server bounces the whole request. NapCat's equivalent transformer (Oidb.0XFE1_2.ts) emits only `uin` (field 1) and `key[]` (field 3) — nothing in field 2. Match that shape exactly. Effect: warmUpBridgeState's "self info via profile" fallback path now succeeds for accounts that QQ omits from the friend list, so the WebUI shows their nickname instead of leaving it blank. --- packages/core/src/bridge/bridge-contacts.ts | 3 ++- packages/core/src/bridge/proto/oidb-action.ts | 10 +++++++--- 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/packages/core/src/bridge/bridge-contacts.ts b/packages/core/src/bridge/bridge-contacts.ts index 63c2bbaa..23f537f1 100644 --- a/packages/core/src/bridge/bridge-contacts.ts +++ b/packages/core/src/bridge/bridge-contacts.ts @@ -208,9 +208,10 @@ export async function fetchGroupMemberList(bridge: Bridge, groupId: number): Pro export async function fetchUserProfile(bridge: Bridge, uin: number): Promise { const keys = [20002, 27394, 20009, 20031, 101, 103, 102, 20020, 20003, 20026, 105, 27372, 27406, 20037]; + // Only `uin` and `keys` — see OidbUserInfoRequestSchema for why + // sending field 2 makes the server reject the request. const body = { uin, - field2: 0, keys: keys.map(k => ({ key: k })), }; diff --git a/packages/core/src/bridge/proto/oidb-action.ts b/packages/core/src/bridge/proto/oidb-action.ts index b4b28a1a..ec521dff 100644 --- a/packages/core/src/bridge/proto/oidb-action.ts +++ b/packages/core/src/bridge/proto/oidb-action.ts @@ -190,10 +190,14 @@ export const OidbUserInfoKeySchema = { key: { field: 1, type: 'uint32' as const }, } satisfies ProtoSchema; +// Field 2 USED to be `field2: uint32 = 0`, but newer QQ NT versions +// reinterpret field 2 as `uid: string` / `openid: string` and reject +// the request with "one of uid/openid is invaild" when a varint 0 +// shows up there. NapCat's schema (Oidb.0XFE1_2.ts) only emits `uin` +// and `key[]`, so we match that exactly. export const OidbUserInfoRequestSchema = { - uin: { field: 1, type: 'uint32' as const }, - field2: { field: 2, type: 'uint32' as const }, - keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema }, + uin: { field: 1, type: 'uint32' as const }, + keys: { field: 3, type: 'repeated_message' as const, schema: OidbUserInfoKeySchema }, } satisfies ProtoSchema; export const OidbTwoNumberSchema = { From a07521d9dea0891f79ae425e1687b6b5c1adcd53 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 13:48:13 +0800 Subject: [PATCH 40/51] fix(bridge): drop bloated fields from OIDB 0xFE5_2 group-list request closes #42 On accounts with ~200+ groups, fetchGroupList was asking QQ to fill in every config flag (all 32 bools in config1 plus all 8 in config2) even though our response decoder reads only groupName / memberMax / memberCount / customInfo.remark / a handful of named info fields. QQ NT obligingly packs every requested field into the response. At group counts >= ~200 the payload is large enough to blow the named-pipe write buffer on the QQ side; SnowLuma reads EPIPE and the entire session dies during warmup: WARN [Hook] pipe error: PID=23928 err=read EPIPE INFO [OneBot] session closed: UIN=... WARN [OneBot] failed to load groups for UIN ...: qq_hook client closed Issue #42 reporter (airline233) bisected the breakage to two clusters of unused bool flags: - config1.field5003 (a 5xxx-range expansive descriptor) - the whole of config2 (per-group aux info we don't decode) This commit applies exactly their verified safe combination and inlines a comment so nobody flips them back on without context. The decoded response shape (groupName, memberCount, memberMax, remark, etc.) is unchanged. --- packages/core/src/bridge/bridge-contacts.ts | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/packages/core/src/bridge/bridge-contacts.ts b/packages/core/src/bridge/bridge-contacts.ts index 23f537f1..d63b10da 100644 --- a/packages/core/src/bridge/bridge-contacts.ts +++ b/packages/core/src/bridge/bridge-contacts.ts @@ -103,6 +103,19 @@ export async function fetchFriendList(bridge: Bridge): Promise { // --------------------------------------------------------------------------- export async function fetchGroupList(bridge: Bridge): Promise { + // The config flags ask QQ which per-group fields to include in the + // response. Asking for everything looks innocent on small accounts + // but on ~200+ groups it makes the QQ NT process write a payload + // large enough to blow the named-pipe write buffer — we then read + // EPIPE and the whole session dies. See issue #42. + // + // The user-verified safe combination: keep `config1.*` mostly on + // (the response decoder pulls groupOwner / memberMax / memberCount / + // groupName / description / question / announcement from this + // group), but turn off the two costly groups of bools that never + // map back to a decoded field: + // - config1.field5003 (an expansive 5xxx-range descriptor) + // - all of config2 (auxiliary per-group blob the decoder ignores) const allTrue = true; const body = { config: { @@ -114,11 +127,11 @@ export async function fetchGroupList(bridge: Bridge): Promise { question: allTrue, field20: allTrue, field22: allTrue, field23: allTrue, field24: allTrue, field25: allTrue, field26: allTrue, field27: allTrue, field28: allTrue, field29: allTrue, field30: allTrue, field31: allTrue, - field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: allTrue, + field32: allTrue, field5001: allTrue, field5002: allTrue, field5003: false, }, config2: { - field1: allTrue, field2: allTrue, field3: allTrue, field4: allTrue, - field5: allTrue, field6: allTrue, field7: allTrue, field8: allTrue, + field1: false, field2: false, field3: false, field4: false, + field5: false, field6: false, field7: false, field8: false, }, config3: { field5: allTrue, field6: allTrue }, }, From 24056c3de0d271a29d6fd6489bb3015370c63d9c Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 14:06:44 +0800 Subject: [PATCH 41/51] feat(msg-push): decode group message emoji reactions (Event0x2DC subType=16) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QQ has been pushing Event0x2DC subType=16 every time someone tapped an emoji on a message in a group, and we were dropping it silently (only surfacing the PR5 [MsgPush.Unknown] debug line that prompted this issue). Now we decode it into a first-class event and fan it out to OneBot clients. Wire details (cribbed from NapCat's GroupReactNotify transformer): - body.msgContent has a 7-byte magic prefix; strip before decoding. - GroupReactNotify { groupUin(4), field13(13), groupReactionData(44) }. - field13 is a discriminator — same subType is reused for other notify variants, only 35 means "emoji react". Other values now fall through to MsgPush.Unknown so we still spot future variants. - Inside groupReactionData (3-level nested data wrapper, ugh): code emoji id (system face = numeric str, market = code) count usually 1 operatorUid needs identity.findUinByUid to resolve to uin type 1 = add, else = remove target.seq msg_seq of the reacted-to message New event kind `group_msg_emoji_like` flows through the standard pipeline: bridge event → event-bus → converter → OneBot wire. Converter emits the gocqhttp / NapCat extension shape: notice_type: group_msg_emoji_like sub_type: add | remove group_id, user_id, operator_id, message_id, message_seq, likes: [{ emoji_id, count }] message_id is reconstructed via hashMessageIdInt32(msgSeq, groupId, GROUP_MESSAGE_EVENT) so it matches whatever id the bot originally handed out for the message being reacted to, even if it's no longer in the message store. formatEvent also gets a case so the [Event] log reads cleanly: 表情回应 [群名(123)] | [Alice(99999)] +[76] msgSeq=4242 7 new tests cover the happy path, type=2 (remove), field13!=35 (routed to MsgPush.Unknown), prefix-too-short edge, converter shape both for add and remove, and the formatEvent string. --- packages/core/src/bridge/events.ts | 19 +- .../bridge/msg-push/decoders/event-0x2dc.ts | 55 ++++- packages/core/src/bridge/msg-push/enums.ts | 1 + packages/core/src/bridge/proto/notify.ts | 38 ++++ .../core/src/onebot/event-converter/index.ts | 2 + .../src/onebot/event-converter/to-notice.ts | 30 +++ packages/core/src/onebot/event-pipeline.ts | 1 + packages/core/src/utils/event-format.ts | 2 + .../core/tests/group-msg-emoji-like.test.ts | 213 ++++++++++++++++++ 9 files changed, 358 insertions(+), 3 deletions(-) create mode 100644 packages/core/tests/group-msg-emoji-like.test.ts diff --git a/packages/core/src/bridge/events.ts b/packages/core/src/bridge/events.ts index 27e75eb6..e2665791 100644 --- a/packages/core/src/bridge/events.ts +++ b/packages/core/src/bridge/events.ts @@ -230,6 +230,22 @@ export interface FriendAddEvent extends QQEvent { userUin: number; } +export interface GroupMsgEmojiLikeEvent extends QQEvent { + kind: 'group_msg_emoji_like'; + groupId: number; + operatorUin: number; + operatorUid: string; + /** Sequence of the message that was reacted to (server-assigned msg_seq). */ + msgSeq: number; + /** Emoji ID. QQ system faces are short numeric strings; market faces + * are alphanumeric. We keep the wire string verbatim. */ + emojiId: string; + /** Multiplicity of the reaction event. Usually 1. */ + count: number; + /** True when the reaction is being added; false when removed. */ + isAdd: boolean; +} + export type QQEventVariant = | FriendMessage | GroupMessage @@ -246,4 +262,5 @@ export type QQEventVariant = | GroupPokeEvent | GroupEssenceEvent | GroupFileUploadEvent - | FriendAddEvent; + | FriendAddEvent + | GroupMsgEmojiLikeEvent; diff --git a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts index 7b072b83..28efafe7 100644 --- a/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts +++ b/packages/core/src/bridge/msg-push/decoders/event-0x2dc.ts @@ -1,12 +1,14 @@ // Handles Event0x2DC wrapper (732). Internal switch on subType dispatches -// to GroupMute (12) / GroupRecall (17) / GroupGreyTip (20) / GroupEssence (21). +// to GroupMute (12) / GroupMsgEmojiLike (16) / GroupRecall (17) / +// GroupGreyTip (20) / GroupEssence (21). import { protoDecode } from '../../../protobuf/decode'; import { - GroupMuteSchema, NotifyMessageBodySchema, + GroupMuteSchema, NotifyMessageBodySchema, GroupReactNotifySchema, } from '../../proto/notify'; import type { GroupMuteEvent, GroupRecallEvent, GroupPokeEvent, GroupEssenceEvent, + GroupMsgEmojiLikeEvent, QQEventVariant, } from '../../events'; import type { MsgPushDecoder } from '../registry'; @@ -23,6 +25,7 @@ const unknownLog = createLogger('MsgPush.Unknown'); export const decodeEvent0x2DC: MsgPushDecoder = (ctx) => { switch (ctx.head.subType as Event0x2DCSubType) { case Event0x2DCSubType.GroupMuteNotice: return decodeGroupMute(ctx); + case Event0x2DCSubType.GroupMsgEmojiLikeNotice: return decodeGroupMsgEmojiLike(ctx); case Event0x2DCSubType.GroupRecallNotice: return decodeGroupRecall(ctx); case Event0x2DCSubType.GroupGreyTipNotice: return decodeGroupGreyTip(ctx); case Event0x2DCSubType.GroupEssenceNotice: return decodeGroupEssence(ctx); @@ -108,3 +111,51 @@ function decodeGroupEssence(ctx: MsgPushContext): QQEventVariant[] { }; return [ev]; } + +// Magic prefix QQ prepends to the GroupReactNotify payload inside +// body.msgContent for Event0x2DC subType=16. Same value NapCat strips +// (see api/group.ts: `msgContent?.slice(7)`). +const GROUP_REACT_PREFIX_BYTES = 7; +// Discriminator on GroupReactNotify.field13 — same subType is reused +// for other notify variants, only 35 means "emoji react". Anything +// else falls through to MsgPush.Unknown for protocol-drift visibility. +const GROUP_REACT_DISCRIMINATOR = 35; + +function decodeGroupMsgEmojiLike(ctx: MsgPushContext): QQEventVariant[] { + if (ctx.content.length <= GROUP_REACT_PREFIX_BYTES) return []; + const payload = ctx.content.subarray(GROUP_REACT_PREFIX_BYTES); + const notify = protoDecode(payload, GroupReactNotifySchema); + if (!notify) return []; + if ((notify.field13 ?? 0) !== GROUP_REACT_DISCRIMINATOR) { + unknownLog.debug('Event0x2DC subType=16 unhandled field13=%d (expected %d for emoji react)', + notify.field13 ?? 0, GROUP_REACT_DISCRIMINATOR); + return []; + } + const content = notify.groupReactionData?.data?.data?.groupReactionDataContent; + const target = notify.groupReactionData?.data?.data?.groupReactionTarget; + if (!content) return []; + + const groupId = Number(notify.groupUin ?? 0n); + const operatorUid = content.operatorUid ?? ''; + const emojiId = content.code ?? ''; + const count = content.count ?? 1; + // type is QQ's add/remove discriminator: 1 = react added, 2 = react + // removed. Older payloads occasionally omit it; default to "add" + // since most clients can only generate add events. + const isAdd = (content.type ?? 1) === 1; + const msgSeq = Number(target?.seq ?? 0n); + + const ev: GroupMsgEmojiLikeEvent = { + kind: 'group_msg_emoji_like', + time: ctx.head.timestamp, + selfUin: ctx.selfUin, + groupId, + operatorUin: resolveUidToUin(ctx.identity, groupId, operatorUid, ctx.fromUin), + operatorUid, + msgSeq, + emojiId, + count, + isAdd, + }; + return [ev]; +} diff --git a/packages/core/src/bridge/msg-push/enums.ts b/packages/core/src/bridge/msg-push/enums.ts index c94b3875..38561e87 100644 --- a/packages/core/src/bridge/msg-push/enums.ts +++ b/packages/core/src/bridge/msg-push/enums.ts @@ -21,6 +21,7 @@ export enum PkgType { export enum Event0x2DCSubType { GroupMuteNotice = 12, + GroupMsgEmojiLikeNotice = 16, GroupRecallNotice = 17, GroupGreyTipNotice = 20, GroupEssenceNotice = 21, diff --git a/packages/core/src/bridge/proto/notify.ts b/packages/core/src/bridge/proto/notify.ts index 36eb1163..2121ddad 100644 --- a/packages/core/src/bridge/proto/notify.ts +++ b/packages/core/src/bridge/proto/notify.ts @@ -205,3 +205,41 @@ export const NotifyMessageBodySchema = { msgSequence: { field: 37, type: 'uint32' as const }, field39: { field: 39, type: 'uint32' as const }, } satisfies ProtoSchema; + +// ─── Event0x2DC subType=16: GroupMsgEmojiLike ────────────────────────────── +// +// QQ pushes a Group message emoji reaction (someone tapped an emoji on a +// message in a group). The payload nesting matches NapCat's transformer +// (packet/transformer/proto/message/message.ts → GroupReactNotify); the +// outermost message is preceded by a 7-byte prefix that must be stripped +// before decoding (see the call site). + +export const GroupReactionDataInnerDataTargetSchema = { + seq: { field: 1, type: 'uint64' as const }, +} satisfies ProtoSchema; + +export const GroupReactionDataContentSchema = { + code: { field: 1, type: 'string' as const }, + count: { field: 3, type: 'uint32' as const }, + operatorUid: { field: 4, type: 'string' as const }, + type: { field: 5, type: 'uint32' as const }, +} satisfies ProtoSchema; + +export const GroupReactionDataInnerDataSchema = { + groupReactionTarget: { field: 2, type: 'message' as const, schema: GroupReactionDataInnerDataTargetSchema }, + groupReactionDataContent: { field: 3, type: 'message' as const, schema: GroupReactionDataContentSchema }, +} satisfies ProtoSchema; + +export const GroupReactionDataInnerSchema = { + data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerDataSchema }, +} satisfies ProtoSchema; + +export const GroupReactionDataSchema = { + data: { field: 1, type: 'message' as const, schema: GroupReactionDataInnerSchema }, +} satisfies ProtoSchema; + +export const GroupReactNotifySchema = { + groupUin: { field: 4, type: 'uint64' as const }, + field13: { field: 13, type: 'uint32' as const }, + groupReactionData: { field: 44, type: 'message' as const, schema: GroupReactionDataSchema }, +} satisfies ProtoSchema; diff --git a/packages/core/src/onebot/event-converter/index.ts b/packages/core/src/onebot/event-converter/index.ts index 806bb5c1..5b5b6032 100644 --- a/packages/core/src/onebot/event-converter/index.ts +++ b/packages/core/src/onebot/event-converter/index.ts @@ -23,6 +23,7 @@ import { convertGroupFileUpload, convertGroupMemberJoin, convertGroupMemberLeave, + convertGroupMsgEmojiLike, convertGroupMute, convertGroupPoke, convertGroupRecall, @@ -98,6 +99,7 @@ export async function convertEvent( case 'group_essence': return convertGroupEssence(ctx, event); case 'group_file_upload': return convertGroupFileUpload(ctx, event); case 'friend_add': return convertFriendAdd(ctx, event); + case 'group_msg_emoji_like': return convertGroupMsgEmojiLike(ctx, event); // Requests. case 'friend_request': return convertFriendRequest(ctx, event); diff --git a/packages/core/src/onebot/event-converter/to-notice.ts b/packages/core/src/onebot/event-converter/to-notice.ts index 1f4875e0..484d4921 100644 --- a/packages/core/src/onebot/event-converter/to-notice.ts +++ b/packages/core/src/onebot/event-converter/to-notice.ts @@ -21,6 +21,7 @@ type GroupPoke = Extract; type GroupEssence = Extract; type GroupFileUpload = Extract; type FriendAdd = Extract; +type GroupMsgEmojiLike = Extract; export function convertGroupMemberJoin(ctx: ConverterContext, event: GroupMemberJoin): JsonObject { return { @@ -187,3 +188,32 @@ export function convertFriendAdd(ctx: ConverterContext, event: FriendAdd): JsonO user_id: event.userUin, }; } + +/** + * Group message emoji reaction notice. Matches the gocqhttp / NapCat + * extension shape (`notice_type: 'group_msg_emoji_like'`) since OneBot + * v11 standard has no slot for reactions and that's what every + * downstream framework keys off. + */ +export function convertGroupMsgEmojiLike(ctx: ConverterContext, event: GroupMsgEmojiLike): JsonObject { + // Reconstruct the OneBot message_id we originally minted for the + // reacted-to message. hashMessageIdInt32 is deterministic so the ID + // matches whatever the client received at receive-time, even when + // the message has fallen out of our store. + const messageId = applyMessageIdResolver( + ctx.messageIdResolver, true, event.groupId, event.msgSeq, GROUP_MESSAGE_EVENT, + ); + return { + time: event.time, + self_id: ctx.selfId, + post_type: 'notice', + notice_type: 'group_msg_emoji_like', + sub_type: event.isAdd ? 'add' : 'remove', + group_id: event.groupId, + user_id: event.operatorUin, + operator_id: event.operatorUin, + message_id: messageId, + message_seq: event.msgSeq, + likes: [{ emoji_id: event.emojiId, count: event.count }], + }; +} diff --git a/packages/core/src/onebot/event-pipeline.ts b/packages/core/src/onebot/event-pipeline.ts index c0ccb3e2..1df60864 100644 --- a/packages/core/src/onebot/event-pipeline.ts +++ b/packages/core/src/onebot/event-pipeline.ts @@ -73,6 +73,7 @@ const NOTICE_KINDS = [ 'group_essence', 'group_file_upload', 'friend_add', + 'group_msg_emoji_like', ] as const satisfies readonly QQEventVariant['kind'][]; async function convertAndDispatch(ctx: OneBotInstanceContext, event: QQEventVariant): Promise { diff --git a/packages/core/src/utils/event-format.ts b/packages/core/src/utils/event-format.ts index ffa1aa28..243f098a 100644 --- a/packages/core/src/utils/event-format.ts +++ b/packages/core/src/utils/event-format.ts @@ -198,6 +198,8 @@ export function formatEvent(identity: IdentityService, event: QQEventVariant): s return `群邀请 ${formatUser(identity, undefined, event.fromUin)} -> ${formatGroup(identity, event.groupId)}`; case 'group_essence': return `精华 ${formatGroup(identity, event.groupId)} | ${event.set ? '+' : '-'}精华`; + case 'group_msg_emoji_like': + return `表情回应 ${formatGroup(identity, event.groupId)} | ${formatUser(identity, event.groupId, event.operatorUin, event.operatorUid)} ${event.isAdd ? '+' : '-'}[${event.emojiId}] msgSeq=${event.msgSeq}`; default: return null; } diff --git a/packages/core/tests/group-msg-emoji-like.test.ts b/packages/core/tests/group-msg-emoji-like.test.ts new file mode 100644 index 00000000..a986ac1d --- /dev/null +++ b/packages/core/tests/group-msg-emoji-like.test.ts @@ -0,0 +1,213 @@ +// Tests for the Event0x2DC subType=16 (GroupMsgEmojiLike) end-to-end: +// - decoder strips the 7-byte prefix and decodes GroupReactNotify +// - field13==35 yields a GroupMsgEmojiLikeEvent +// - field13!=35 surfaces under MsgPush.Unknown and emits nothing +// - converter shape matches the gocqhttp / NapCat extension layout +// - formatEvent prints something readable in the [Event] log + +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; +import { protoEncode } from '../src/protobuf/decode'; +import { GroupReactNotifySchema } from '../src/bridge/proto/notify'; +import { decodeEvent0x2DC } from '../src/bridge/msg-push/decoders/event-0x2dc'; +import type { MsgPushContext } from '../src/bridge/msg-push/context'; +import { IdentityService } from '../src/bridge/identity-service'; +import type { GroupMsgEmojiLikeEvent, QQEventVariant } from '../src/bridge/events'; +import { convertGroupMsgEmojiLike } from '../src/onebot/event-converter/to-notice'; +import { GROUP_MESSAGE_EVENT, hashMessageIdInt32 } from '../src/onebot/message-id'; +import { formatEvent } from '../src/utils/event-format'; +import { subscribeLogs, type LogEntry } from '../src/utils/logger'; + +const SELF_UIN = '10001'; +const GROUP_ID = 123456789; + +function makeIdentity(): IdentityService { + return IdentityService.memory(SELF_UIN); +} + +/** Build the raw bytes QQ would push into ctx.content for subType=16: + * a 7-byte magic prefix followed by an encoded GroupReactNotify. */ +function buildReactContent(notify: Record): Uint8Array { + const prefix = new Uint8Array([0, 0, 0, 0, 0, 0, 0]); + const body = protoEncode(notify as never, GroupReactNotifySchema); + const out = new Uint8Array(prefix.length + body.length); + out.set(prefix, 0); + out.set(body, prefix.length); + return out; +} + +function makeCtx(content: Uint8Array, identity = makeIdentity()): MsgPushContext { + return { + head: { msgType: 732, subType: 16, sequence: 0, timestamp: 1735000000, msgId: 0 }, + fromUin: 0, + fromUid: '', + selfUin: Number(SELF_UIN), + content, + body: undefined, + responseHead: undefined, + identity, + }; +} + +describe('decodeEvent0x2DC subType=16 — GroupMsgEmojiLike', () => { + it('decodes a field13=35 react add into a GroupMsgEmojiLikeEvent', () => { + const content = buildReactContent({ + groupUin: BigInt(GROUP_ID), + field13: 35, + groupReactionData: { + data: { + data: { + groupReactionTarget: { seq: 4242n }, + groupReactionDataContent: { + code: '76', + count: 1, + operatorUid: 'u_operator_xxx', + type: 1, // add + }, + }, + }, + }, + }); + + const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[]; + expect(event).toBeDefined(); + expect(event.kind).toBe('group_msg_emoji_like'); + expect(event.groupId).toBe(GROUP_ID); + expect(event.operatorUid).toBe('u_operator_xxx'); + expect(event.emojiId).toBe('76'); + expect(event.msgSeq).toBe(4242); + expect(event.count).toBe(1); + expect(event.isAdd).toBe(true); + }); + + it('decodes type=2 as react remove (isAdd=false)', () => { + const content = buildReactContent({ + groupUin: BigInt(GROUP_ID), + field13: 35, + groupReactionData: { + data: { + data: { + groupReactionTarget: { seq: 1n }, + groupReactionDataContent: { + code: '⭐', + count: 1, + operatorUid: 'u_x', + type: 2, + }, + }, + }, + }, + }); + + const [event] = decodeEvent0x2DC(makeCtx(content)) as GroupMsgEmojiLikeEvent[]; + expect(event.isAdd).toBe(false); + expect(event.emojiId).toBe('⭐'); + }); + + it('drops the packet and logs to MsgPush.Unknown when field13 is not 35', () => { + const captured: LogEntry[] = []; + const unsub = subscribeLogs((e) => captured.push(e)); + + const content = buildReactContent({ + groupUin: BigInt(GROUP_ID), + field13: 99, // not 35 + groupReactionData: { + data: { data: { groupReactionDataContent: { code: 'x', operatorUid: 'u_y' } } }, + }, + }); + + const result = decodeEvent0x2DC(makeCtx(content)); + unsub(); + + expect(result).toHaveLength(0); + const unknown = captured.find((e) => + e.scope === 'MsgPush.Unknown' && /field13=99/.test(e.message)); + expect(unknown).toBeDefined(); + }); + + it('returns empty when content is shorter than the prefix length', () => { + const tooShort = new Uint8Array([1, 2, 3]); // < 7 bytes + expect(decodeEvent0x2DC(makeCtx(tooShort))).toEqual([]); + }); +}); + +describe('convertGroupMsgEmojiLike — OneBot notice shape', () => { + const baseEvent: GroupMsgEmojiLikeEvent = { + kind: 'group_msg_emoji_like', + time: 1735000000, + selfUin: 10001, + groupId: 123456789, + operatorUin: 99999, + operatorUid: 'u_x', + msgSeq: 4242, + emojiId: '76', + count: 1, + isAdd: true, + }; + + // Real production wiring puts a hashMessageIdInt32-based resolver + // on the ctx; mirror that so message_id is the same value the + // bot would have minted for the original message. + const ctx = { + selfId: 10001, + imageUrlResolver: null, + mediaUrlResolver: null, + messageIdResolver: (_isGroup: boolean, sessionId: number, sequence: number, eventName: string) => + hashMessageIdInt32(sequence, sessionId, eventName), + mediaSegmentSink: null, + } as never; + + it('produces a group_msg_emoji_like notice with sub_type=add and resolved message_id', () => { + const out = convertGroupMsgEmojiLike(ctx, baseEvent); + expect(out.post_type).toBe('notice'); + expect(out.notice_type).toBe('group_msg_emoji_like'); + expect(out.sub_type).toBe('add'); + expect(out.group_id).toBe(123456789); + expect(out.user_id).toBe(99999); + expect(out.operator_id).toBe(99999); + expect(out.message_seq).toBe(4242); + expect(out.message_id).toBe(hashMessageIdInt32(4242, 123456789, GROUP_MESSAGE_EVENT)); + expect(out.likes).toEqual([{ emoji_id: '76', count: 1 }]); + }); + + it('flips sub_type to remove when isAdd is false', () => { + const out = convertGroupMsgEmojiLike(ctx, { ...baseEvent, isAdd: false }); + expect(out.sub_type).toBe('remove'); + }); +}); + +describe('formatEvent — group_msg_emoji_like', () => { + let savedLevel: string | undefined; + beforeEach(() => { savedLevel = process.env.SNOWLUMA_LOG_LEVEL; }); + afterEach(() => { + if (savedLevel === undefined) delete process.env.SNOWLUMA_LOG_LEVEL; + else process.env.SNOWLUMA_LOG_LEVEL = savedLevel; + }); + + it('renders a one-line summary with group, operator and emoji id', () => { + const identity = IdentityService.memory(SELF_UIN); + identity.rememberGroups([{ + groupId: GROUP_ID, groupName: 'TestGroup', remark: '', + memberCount: 1, memberMax: 500, members: new Map(), + }]); + identity.rememberGroupMembers(GROUP_ID, [{ + uin: 99999, uid: 'u_x', nickname: 'Alice', card: '', + role: 'member', level: 0, title: '', + joinTime: 0, lastSentTime: 0, shutUpTime: 0, + }]); + + const event: QQEventVariant = { + kind: 'group_msg_emoji_like', + time: 0, selfUin: Number(SELF_UIN), + groupId: GROUP_ID, + operatorUin: 99999, operatorUid: 'u_x', + msgSeq: 100, emojiId: '76', count: 1, isAdd: true, + }; + + const line = formatEvent(identity, event); + expect(line).toBeDefined(); + expect(line).toContain('TestGroup'); + expect(line).toContain('Alice'); + expect(line).toContain('[76]'); + expect(line).toContain('msgSeq=100'); + }); +}); From a46043317551af9d79f8e06a9664ed8f95693e69 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 14:29:52 +0800 Subject: [PATCH 42/51] refactor(webui): redesign per-UIN config page into sidebar + tabs + modal MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The original page stacked four expanded network sections vertically with inline editing, so the first view drowned in every field across every adapter at once. Restructured to a sidebar + tabs + modal layout: - Account sidebar collapses to a 56px avatar column with name/UIN tooltips; expanded it keeps the original 260px nickname + UIN layout. - Right pane swaps the stacked sections for a 5-tab strip (通用设置 / HTTP API / HTTP 客户端 / WS 服务端 / WS 客户端) with a per-tab badge count. - Each network tab is a list of summary cards: name + projected key info (host:port/path, url · role, etc.) + format/report/token badges + inline enable toggle + edit/delete buttons. No live-typed fields. - Create and edit both route through a single NodeEditDialog with kind-specific field strips; cancel truly discards the draft. - Per-kind metadata (title, summary projector, defaultEntry factory) lives in config/defaults.ts so adding a new adapter kind only needs one descriptor entry. Behavior preserved end-to-end: same per-UIN config payload, same useOneBotInstanceConfig hook, same dirty-switch confirm flow, same save endpoint. --- .../src/components/config/account-sidebar.tsx | 114 +++ .../webui/src/components/config/defaults.ts | 159 +++ .../config/general-settings-tab.tsx | 31 + .../components/config/node-edit-dialog.tsx | 407 ++++++++ .../components/config/node-summary-card.tsx | 130 +++ .../src/components/pages/config-page.tsx | 963 ++++++------------ 6 files changed, 1159 insertions(+), 645 deletions(-) create mode 100644 packages/webui/src/components/config/account-sidebar.tsx create mode 100644 packages/webui/src/components/config/defaults.ts create mode 100644 packages/webui/src/components/config/general-settings-tab.tsx create mode 100644 packages/webui/src/components/config/node-edit-dialog.tsx create mode 100644 packages/webui/src/components/config/node-summary-card.tsx diff --git a/packages/webui/src/components/config/account-sidebar.tsx b/packages/webui/src/components/config/account-sidebar.tsx new file mode 100644 index 00000000..6d0bfb47 --- /dev/null +++ b/packages/webui/src/components/config/account-sidebar.tsx @@ -0,0 +1,114 @@ +// Account selector strip. Collapsing to a 56px avatar-only column keeps +// the right-side editor breathing on smaller screens; expanded it shows +// nickname + UIN like the original. Selection routes through +// `requestSwitchUin` so the dirty-modify guard still gates the switch. + +import { motion } from 'motion/react'; +import { ChevronLeft, ChevronRight } from 'lucide-react'; +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; +import { Button } from '@/components/ui/button'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; +import { cn } from '@/lib/utils'; +import type { QQInfo } from '@/types'; + +function qqAvatarUrl(uin: string) { + return `/avatar/${encodeURIComponent(uin)}`; +} + +interface AccountSidebarProps { + accounts: QQInfo[]; + selectedUin: string | null; + onSelect: (uin: string) => void; + collapsed: boolean; + onToggleCollapsed: () => void; +} + +export function AccountSidebar({ + accounts, + selectedUin, + onSelect, + collapsed, + onToggleCollapsed, +}: AccountSidebarProps) { + return ( + +
+ {!collapsed && 在线连接} + +
+ + {accounts.length === 0 ? ( +

+ {collapsed ? '—' : '暂无在线会话'} +

+ ) : ( + + +
+ {accounts.map((q) => { + const isActive = selectedUin === q.uin; + const button = ( + onSelect(q.uin)} + className={cn( + 'flex items-center gap-2.5 rounded-lg border text-left transition-colors cursor-pointer', + collapsed ? 'justify-center p-1.5' : 'px-2.5 py-2', + isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40', + )} + > + + + {(q.nickname || q.uin).slice(0, 2)} + + {!collapsed && ( +
+
+ {q.nickname || q.uin} +
+
+ {q.uin} +
+
+ )} +
+ ); + return collapsed ? ( + + {button} + +
+ {q.nickname || q.uin} + {q.uin} +
+
+
+ ) : ( + button + ); + })} +
+
+
+ )} +
+ ); +} diff --git a/packages/webui/src/components/config/defaults.ts b/packages/webui/src/components/config/defaults.ts new file mode 100644 index 00000000..1c71ce6a --- /dev/null +++ b/packages/webui/src/components/config/defaults.ts @@ -0,0 +1,159 @@ +// Per-network-kind metadata: localized title, summary projector for the +// list view, and factory for "create new" defaults. Centralised here so the +// page / list / dialog all agree on naming and shape and a new adapter +// kind only needs one entry in NETWORK_TABS to wire end-to-end. + +import type { + HttpClientNetwork, + HttpServerNetwork, + MessageFormat, + NetworkKind, + OneBotNetworks, + WsClientNetwork, + WsRole, + WsServerNetwork, +} from '@/types'; + +export type TabKey = 'general' | NetworkKind; + +export interface NetworkTabDescriptor { + key: K; + /** Tab label and dialog title prefix. */ + title: string; + /** Short subtitle shown under the tab when active. */ + description: string; + /** Singular noun for "新建 / 编辑 X". */ + noun: string; + /** Project the adapter into a short list-card summary string. */ + summarize: (item: OneBotNetworks[K][number]) => string; + /** Factory producing a fresh adapter with a unique suffix in its name. */ + defaultEntry: (suffix: number) => OneBotNetworks[K][number]; +} + +function genToken(): string { + const bytes = new Uint8Array(32); + globalThis.crypto.getRandomValues(bytes); + return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join(''); +} + +const httpServersTab: NetworkTabDescriptor<'httpServers'> = { + key: 'httpServers', + title: 'HTTP API', + description: '本地监听 HTTP 端口,OneBot 客户端发起请求', + noun: 'HTTP API 服务', + summarize: (it: HttpServerNetwork) => { + const host = it.host?.trim() || '0.0.0.0'; + const path = (it.path?.trim() || '/').replace(/^\/?/, '/'); + return `${host}:${it.port}${path}`; + }, + defaultEntry: (suffix): HttpServerNetwork => ({ + name: `http-${suffix}`, + host: '0.0.0.0', + port: 3000, + path: '/', + accessToken: genToken(), + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +const httpClientsTab: NetworkTabDescriptor<'httpClients'> = { + key: 'httpClients', + title: 'HTTP 客户端', + description: '主动向远端 URL POST 推送事件', + noun: 'HTTP 推送客户端', + summarize: (it: HttpClientNetwork) => it.url || '(未设置 URL)', + defaultEntry: (suffix): HttpClientNetwork => ({ + name: `httppost-${suffix}`, + url: 'http://127.0.0.1:5700', + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +const wsServersTab: NetworkTabDescriptor<'wsServers'> = { + key: 'wsServers', + title: 'WS 服务端', + description: '本地监听 WebSocket 端口,客户端建立持久连接', + noun: 'WebSocket 服务', + summarize: (it: WsServerNetwork) => { + const host = it.host?.trim() || '0.0.0.0'; + const path = (it.path?.trim() || '/').replace(/^\/?/, '/'); + const role = it.role ?? 'Universal'; + return `${host}:${it.port}${path} · ${role}`; + }, + defaultEntry: (suffix): WsServerNetwork => ({ + name: `ws-${suffix}`, + host: '0.0.0.0', + port: 3001, + path: '/', + role: 'Universal' as WsRole, + accessToken: genToken(), + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +const wsClientsTab: NetworkTabDescriptor<'wsClients'> = { + key: 'wsClients', + title: 'WS 客户端', + description: '主动连接到外部 WebSocket 服务器(reverse-ws)', + noun: 'WebSocket 反向客户端', + summarize: (it: WsClientNetwork) => { + const role = it.role ?? 'Universal'; + return `${it.url || '(未设置 URL)'} · ${role}`; + }, + defaultEntry: (suffix): WsClientNetwork => ({ + name: `wsclient-${suffix}`, + url: 'ws://127.0.0.1:8080/ws', + role: 'Universal' as WsRole, + reconnectIntervalMs: 5000, + messageFormat: 'array', + reportSelfMessage: false, + }), +}; + +/** + * Order here drives both the tab strip order and the dialog/page wiring. + * Each entry stays strictly typed on its kind so callers get the narrow + * adapter shape (no NetworkBase widening). + */ +export const NETWORK_TABS = { + httpServers: httpServersTab, + httpClients: httpClientsTab, + wsServers: wsServersTab, + wsClients: wsClientsTab, +} satisfies { [K in NetworkKind]: NetworkTabDescriptor }; + +export const NETWORK_TAB_ORDER: NetworkKind[] = [ + 'httpServers', + 'httpClients', + 'wsServers', + 'wsClients', +]; + +export const ALL_TABS: TabKey[] = ['general', ...NETWORK_TAB_ORDER]; + +/** + * Find the smallest suffix N (starting at list.length + 1) such that + * `factory(N).name` doesn't collide with any existing adapter. Used by + * the page to seed a fresh-default adapter when the user clicks "create". + */ +export function nextUniqueSuffix( + networks: { name: string }[], + factory: (suffix: number) => { name: string }, +): number { + const used = new Set(networks.map((n) => n.name)); + let suffix = networks.length + 1; + while (used.has(factory(suffix).name)) suffix += 1; + return suffix; +} + +// Re-exported for callers that just need to type a generic adapter. +export interface AdapterCommon { + name: string; + enabled?: boolean; + accessToken?: string; + messageFormat: MessageFormat; + reportSelfMessage: boolean; +} diff --git a/packages/webui/src/components/config/general-settings-tab.tsx b/packages/webui/src/components/config/general-settings-tab.tsx new file mode 100644 index 00000000..3ed5a3cc --- /dev/null +++ b/packages/webui/src/components/config/general-settings-tab.tsx @@ -0,0 +1,31 @@ +// "通用设置" tab — fields that apply to the whole OneBotInstance rather +// than any specific adapter. Currently just the music-sign service URL, +// but the layout has room for additional cross-cutting toggles. + +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import type { OneBotConfig } from '@/types'; + +interface GeneralSettingsTabProps { + config: OneBotConfig; + onChange: (next: OneBotConfig) => void; +} + +export function GeneralSettingsTab({ config, onChange }: GeneralSettingsTabProps) { + return ( +
+
+ + onChange({ ...config, musicSignUrl: e.target.value || undefined })} + /> +

+ 用于音乐分享卡片签名。未配置时音乐相关消息段会回落为普通文本。 +

+
+
+ ); +} diff --git a/packages/webui/src/components/config/node-edit-dialog.tsx b/packages/webui/src/components/config/node-edit-dialog.tsx new file mode 100644 index 00000000..b1ca652b --- /dev/null +++ b/packages/webui/src/components/config/node-edit-dialog.tsx @@ -0,0 +1,407 @@ +// Modal editor used for both "create" and "edit". Holds a local draft +// copy of the adapter until the user clicks save (so cancel really does +// throw away changes). Validation is minimal — blank-name and dup-name +// disable the save button; everything else is best-effort coercion. + +import { useState } from 'react'; +import { Button } from '@/components/ui/button'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogFooter, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { cn } from '@/lib/utils'; +import type { + HttpClientNetwork, + HttpServerNetwork, + MessageFormat, + NetworkKind, + OneBotNetworks, + WsClientNetwork, + WsRole, + WsServerNetwork, +} from '@/types'; +import { NETWORK_TABS } from './defaults'; + +type AnyAdapter = OneBotNetworks[K][number]; + +interface NodeEditDialogProps { + open: boolean; + onOpenChange: (open: boolean) => void; + kind: K; + /** Initial draft state — caller seeds it with `defaultEntry` for create + * or the existing item for edit. */ + initial: AnyAdapter; + /** True when editing an existing adapter (drives title + button copy). */ + isEdit: boolean; + /** Names of every other adapter in the same list, for duplicate check. */ + otherNames: string[]; + onSubmit: (item: AnyAdapter) => void; +} + +export function NodeEditDialog(props: NodeEditDialogProps) { + const { open, onOpenChange, kind, initial, isEdit, otherNames, onSubmit } = props; + const tab = NETWORK_TABS[kind]; + + // Local draft. The parent unmounts this component on close so each + // open gets a fresh `initial` via useState's lazy init — no effect-based + // resync needed, which keeps the lifecycle linear. + const [draft, setDraft] = useState>(initial); + + const trimmedName = draft.name?.trim() ?? ''; + const blankName = trimmedName.length === 0; + const duplicateName = !blankName && otherNames.includes(trimmedName); + + const canSave = !blankName && !duplicateName; + + const patch = (changes: Partial>) => setDraft({ ...draft, ...changes } as AnyAdapter); + + return ( + + + + {isEdit ? `编辑 ${tab.noun}` : `新建 ${tab.noun}`} + {tab.description} + + +
+ patch({ name: v } as Partial>)} + error={blankName ? '请填写名称' : duplicateName ? '名称与其它节点重复' : undefined} + /> + + + + patch({ accessToken: v || undefined } as Partial>)} + /> + +
+ patch({ messageFormat: v } as Partial>)} + /> + patch({ reportSelfMessage: v === 'on' } as Partial>)} + /> +
+ +
+
+ +

+ 关闭后保存即可保留配置但不启动该节点 +

+
+ + patch({ enabled: v ? undefined : false } as Partial>) + } + ariaLabel="启用" + /> +
+
+ + + + + +
+
+ ); +} + +// ─────────────── kind-specific field strips ─────────────── + +interface KindFieldsProps { + kind: K; + draft: AnyAdapter; + patch: (changes: Partial>) => void; +} + +function KindFields({ kind, draft, patch }: KindFieldsProps) { + // Per-branch narrowing — TS can't follow the generic relationship so + // each arm casts once. Field components receive specific shapes. + if (kind === 'httpServers') { + const it = draft as HttpServerNetwork; + const set = patch as (c: Partial) => void; + return ( +
+ set({ host: v || undefined })} + /> + set({ port: Number(v) || 0 })} + /> + set({ path: v || undefined })} + /> +
+ ); + } + if (kind === 'httpClients') { + const it = draft as HttpClientNetwork; + const set = patch as (c: Partial) => void; + return ( +
+ set({ url: v })} + /> + set({ timeoutMs: Number(v) || undefined })} + /> +
+ ); + } + if (kind === 'wsServers') { + const it = draft as WsServerNetwork; + const set = patch as (c: Partial) => void; + return ( + <> +
+ set({ host: v || undefined })} + /> + set({ port: Number(v) || 0 })} + /> + set({ path: v || undefined })} + /> +
+ set({ role: v })} + /> + + ); + } + if (kind === 'wsClients') { + const it = draft as WsClientNetwork; + const set = patch as (c: Partial) => void; + return ( + <> + set({ url: v })} + /> +
+ set({ role: v })} + /> + set({ reconnectIntervalMs: Number(v) || undefined })} + /> +
+ + ); + } + return null; +} + +// ─────────────── shared form bits ─────────────── + +interface FieldProps { + label: string; + value: string | number | undefined; + onChange: (v: string) => void; + placeholder?: string; + type?: 'text' | 'number' | 'url'; + error?: string; +} + +function Field({ label, value, onChange, placeholder, type = 'text', error }: FieldProps) { + return ( +
+ + onChange(e.target.value)} + placeholder={placeholder} + className={cn(error && 'border-destructive focus-visible:ring-destructive/40')} + /> + {error &&

{error}

} +
+ ); +} + +interface SegmentedOption { + value: T; + label: string; +} + +function SegmentedField({ + label, + value, + options, + onChange, +}: { + label: string; + value: T; + options: ReadonlyArray>; + onChange: (v: T) => void; +}) { + return ( +
+ +
+ {options.map((opt) => { + const active = value === opt.value; + return ( + + ); + })} +
+
+ ); +} + +function SelectField({ + label, + value, + options, + onChange, +}: { + label: string; + value: T; + options: ReadonlyArray>; + onChange: (v: T) => void; +}) { + return ( +
+ + +
+ ); +} + +interface ToggleSwitchProps { + value: boolean; + onChange: (v: boolean) => void; + ariaLabel: string; +} + +function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) { + return ( + + ); +} + +const FORMAT_OPTIONS: ReadonlyArray> = [ + { value: 'array', label: '数组' }, + { value: 'string', label: 'CQ 码' }, +]; + +const REPORT_OPTIONS: ReadonlyArray> = [ + { value: 'on', label: '开启' }, + { value: 'off', label: '关闭' }, +]; + +const WS_ROLE_OPTIONS: ReadonlyArray> = [ + { value: 'Universal', label: 'Universal' }, + { value: 'Event', label: 'Event' }, + { value: 'Api', label: 'Api' }, +]; diff --git a/packages/webui/src/components/config/node-summary-card.tsx b/packages/webui/src/components/config/node-summary-card.tsx new file mode 100644 index 00000000..f2e3fae7 --- /dev/null +++ b/packages/webui/src/components/config/node-summary-card.tsx @@ -0,0 +1,130 @@ +// One row in the per-kind list view. Shows just enough to identify the +// adapter at a glance (name + projected summary + token state + the two +// flags) plus the inline enable toggle. Real editing always goes through +// the dialog — there are no live-typed inputs here. + +import { motion } from 'motion/react'; +import { Pencil, Trash2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { cn } from '@/lib/utils'; +import type { AdapterCommon } from './defaults'; + +interface NodeSummaryCardProps { + item: T; + summary: string; + duplicateName: boolean; + onToggleEnabled: (next: boolean) => void; + onEdit: () => void; + onDelete: () => void; +} + +export function NodeSummaryCard({ + item, + summary, + duplicateName, + onToggleEnabled, + onEdit, + onDelete, +}: NodeSummaryCardProps) { + const enabled = item.enabled !== false; + const blankName = !item.name?.trim(); + + return ( + +
+
+ + {item.name || '(未命名)'} + + {duplicateName && ( + 名称重复 + )} + {!enabled && ( + 已停用 + )} +
+
{summary}
+
+ + {item.messageFormat === 'string' ? 'CQ 码' : '数组'} + + + {item.reportSelfMessage ? '上报自身' : '不上报自身'} + + {item.accessToken ? ( + + 已设 Token + + ) : ( + + 无 Token + + )} +
+
+ +
+ + + +
+
+ ); +} + +interface ToggleSwitchProps { + value: boolean; + onChange: (v: boolean) => void; + ariaLabel: string; +} + +function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) { + return ( + + ); +} diff --git a/packages/webui/src/components/pages/config-page.tsx b/packages/webui/src/components/pages/config-page.tsx index 4154be6c..a9954fac 100644 --- a/packages/webui/src/components/pages/config-page.tsx +++ b/packages/webui/src/components/pages/config-page.tsx @@ -1,93 +1,42 @@ -import { useState } from 'react'; +// OneBot per-UIN configuration page. +// +// Layout: collapsible left sidebar for account selection + tabbed right +// pane (通用 / 4 network kinds). Each network tab is a list view of +// summary cards with inline enable/disable; create + edit both go +// through `NodeEditDialog`. The dirty-modify guard from the original +// hook is preserved end-to-end — switching accounts or kinds doesn't +// drop unsaved changes silently. + +import { useMemo, useState } from 'react'; import { motion } from 'motion/react'; -import { MousePointerClick, Plus, Save, Trash2 } from 'lucide-react'; +import { MousePointerClick, Plus, Save } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { ScrollArea } from '@/components/ui/scroll-area'; -import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; -import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; +import { Badge } from '@/components/ui/badge'; import { ConfirmDialog } from '@/components/confirm-dialog'; import { cn } from '@/lib/utils'; import type { - MessageFormat, NetworkKind, OneBotConfig, OneBotNetworks, - WsRole, } from '@/types'; import { useOneBotInstanceConfig } from '@/hooks/use-onebot-instance-config'; import { useAppState } from '@/contexts/AppStateContext'; +import { AccountSidebar } from '@/components/config/account-sidebar'; +import { GeneralSettingsTab } from '@/components/config/general-settings-tab'; +import { NodeSummaryCard } from '@/components/config/node-summary-card'; +import { NodeEditDialog } from '@/components/config/node-edit-dialog'; +import { + ALL_TABS, + NETWORK_TABS, + nextUniqueSuffix, + type TabKey, +} from '@/components/config/defaults'; -function qqAvatarUrl(uin: string) { - return `/avatar/${encodeURIComponent(uin)}`; -} - -function generateAccessToken(): string { - const bytes = new Uint8Array(32); - globalThis.crypto.getRandomValues(bytes); - return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''); -} - -function Field({ - label, - value, - onChange, - placeholder, - type = 'text', - className, -}: { - label: string; - value: string | number | undefined; - onChange: (v: string) => void; - placeholder?: string; - type?: 'text' | 'number' | 'url'; - className?: string; -}) { - return ( -
- - onChange(e.target.value)} - placeholder={placeholder} - /> -
- ); -} - -interface SectionProps { - title: string; - description?: string; - onAdd?: () => void; - children: React.ReactNode; - count?: number; -} - -function Section({ title, description, onAdd, children, count }: SectionProps) { - return ( - - -
-
- {title} - {typeof count === 'number' && {count}} -
- {description &&

{description}

} -
- {onAdd && ( - - )} -
- {children} -
- ); -} +type DialogState = + | { open: false } + | { open: true; kind: NetworkKind; index: number | null; seed: OneBotNetworks[NetworkKind][number] }; +// index: null → create with `seed`, otherwise edit the item at that position. export function ConfigPage() { const { qqList, selectedUin, setSelectedUin } = useAppState(); @@ -105,322 +54,137 @@ export function ConfigPage() { selectedUin, onSelectedUinChange: setSelectedUin, }); - const [confirmSave, setConfirmSave] = useState(false); - const update = (next: OneBotConfig) => setConfig(next); - const pendingSwitchAccount = pendingSwitchUin - ? qqList.find((q) => q.uin === pendingSwitchUin) ?? null - : null; + const [activeTab, setActiveTab] = useState('general'); + const [sidebarCollapsed, setSidebarCollapsed] = useState(false); + 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 + // wiring needed beyond the dialog's own open/close. + const [dialog, setDialog] = useState({ open: false }); + + const pendingSwitchAccount = useMemo( + () => (pendingSwitchUin ? qqList.find((q) => q.uin === pendingSwitchUin) ?? null : null), + [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 { + if (!config) return; + setConfig({ ...config, networks: { ...config.networks, [kind]: 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]); + } + + 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); + } + + 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); + } + + 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); + } + + const openCreate = (kind: NetworkKind) => { + if (!config) return; + const tab = NETWORK_TABS[kind]; + const list = config.networks[kind]; + const suffix = nextUniqueSuffix(list, tab.defaultEntry); + setDialog({ open: true, kind, index: null, seed: tab.defaultEntry(suffix) }); + }; + + const openEdit = (kind: NetworkKind, index: number) => { + if (!config) return; + const item = config.networks[kind][index]; + if (!item) return; + setDialog({ open: true, kind, index, seed: item }); + }; return ( -
- {/* Account list */} - - - 在线连接 - - - {qqList.length === 0 ? ( -

暂无在线会话

- ) : ( - -
- {qqList.map((q) => { - const isActive = selectedUin === q.uin; - return ( - requestSwitchUin(q.uin)} - className={cn( - 'flex items-center gap-2.5 rounded-lg border px-2.5 py-2 text-left transition-colors cursor-pointer', - isActive ? 'border-primary/30 bg-primary/10' : 'border-transparent hover:bg-accent/40' - )} - > - - - {(q.nickname || q.uin).slice(0, 2)} - -
-
- {q.nickname} -
-
{q.uin}
-
-
- ); - })} -
-
- )} -
-
+
+ setSidebarCollapsed((v) => !v)} + /> - {/* Editor */} -
+
{!selectedUin ? ( -
- -

请在左栏选择会话以配置通信节点

-
+ ) : !config ? ( -
- - - -
+ ) : (
- {/* Header */} -
-
-

OneBot 协议端点

- UIN {selectedUin} -
-
- {saveStatus && ( - - {saveStatus} - - )} - {dirty && !saveStatus && ( - - 未保存 - - )} - -
-
+ setConfirmSave(true)} + activeTab={activeTab} + onCreate={ + activeTab !== 'general' ? () => openCreate(activeTab as NetworkKind) : undefined + } + /> -
- update({ ...config, musicSignUrl: v || undefined })} + + + {activeTab === 'general' ? ( + + ) : ( + openCreate(activeTab)} + onEdit={(idx) => openEdit(activeTab, idx)} + onDelete={(idx) => handleDelete(activeTab, idx)} + onToggleEnabled={(idx, v) => handleToggleEnabled(activeTab, idx, v)} /> -
- - {/* HTTP Servers */} - updateNetworks(config, update, 'httpServers', arr)} - renderFields={(item, patch) => ( - <> - patch({ host: v || undefined })} - className="sm:w-40" - /> - patch({ port: Number(v) || 0 })} - className="sm:w-28" - /> - patch({ path: v || undefined })} - className="sm:w-32" - /> - patch({ accessToken: v || undefined })} - className="flex-1" - /> - - )} - defaultEntry={(suffix) => ({ - name: `http-${suffix}`, - host: '0.0.0.0', - port: 3000, - path: '/', - accessToken: generateAccessToken(), - messageFormat: 'array', - reportSelfMessage: false, - })} - /> - - {/* HTTP Clients (POST push) */} - updateNetworks(config, update, 'httpClients', arr)} - renderFields={(item, patch) => ( - <> - patch({ url: v })} - className="flex-1" - /> - patch({ accessToken: v || undefined })} - className="sm:w-56" - /> - patch({ timeoutMs: Number(v) || undefined })} - className="sm:w-32" - /> - - )} - defaultEntry={(suffix) => ({ - name: `httppost-${suffix}`, - url: 'http://127.0.0.1:5700', - messageFormat: 'array', - reportSelfMessage: false, - })} - /> - - {/* WebSocket Servers */} - updateNetworks(config, update, 'wsServers', arr)} - renderFields={(item, patch) => ( - <> - patch({ host: v || undefined })} - className="sm:w-40" - /> - patch({ port: Number(v) || 0 })} - className="sm:w-28" - /> - patch({ path: v || undefined })} - className="sm:w-32" - /> - patch({ role: v })} - className="sm:w-32" - /> - patch({ accessToken: v || undefined })} - className="flex-1" - /> - - )} - defaultEntry={(suffix) => ({ - name: `ws-${suffix}`, - host: '0.0.0.0', - port: 3001, - path: '/', - role: 'Universal' as WsRole, - accessToken: generateAccessToken(), - messageFormat: 'array', - reportSelfMessage: false, - })} - /> - - {/* WebSocket Clients (reverse) */} - updateNetworks(config, update, 'wsClients', arr)} - renderFields={(item, patch) => ( - <> - patch({ url: v })} - className="flex-1" - /> - patch({ role: v })} - className="sm:w-32" - /> - patch({ reconnectIntervalMs: Number(v) || undefined })} - className="sm:w-36" - /> - patch({ accessToken: v || undefined })} - className="sm:w-56" - /> - - )} - defaultEntry={(suffix) => ({ - name: `wsclient-${suffix}`, - url: 'ws://127.0.0.1:8080/ws', - role: 'Universal' as WsRole, - reconnectIntervalMs: 5000, - messageFormat: 'array', - reportSelfMessage: false, - })} - /> + )}
)}
+ {/* Single dialog covers create + edit across all 4 kinds. */} + {dialog.open && config && ( + !open && setDialog({ open: false })} + kind={dialog.kind} + initial={dialog.seed} + isEdit={dialog.index != null} + otherNames={otherNames(config.networks, dialog.kind, dialog.index)} + onSubmit={(item) => { + if (dialog.index == null) handleCreate(dialog.kind, item); + else handleEdit(dialog.kind, dialog.index, item); + }} + /> + )} + {label}
- ); +// ─────────────── header ─────────────── + +interface HeaderBarProps { + selectedUin: string; + dirty: boolean; + saveStatus: string; + onSave: () => void; + activeTab: TabKey; + onCreate?: () => void; } -interface ToggleFieldProps { - label: string; - description?: string; - value: boolean; - onChange: (v: boolean) => void; -} - -function ToggleField({ label, description, value, onChange }: ToggleFieldProps) { +function HeaderBar({ selectedUin, dirty, saveStatus, onSave, activeTab, onCreate }: HeaderBarProps) { return ( -
-
- - {description && ( -

{description}

- )} +
+
+

OneBot 协议端点

+ + UIN {selectedUin} +
- + {dirty && !saveStatus && ( + + 未保存 + + )} + {onCreate && ( + + )} + +
); } -interface SegmentedOption { - value: T; - label: string; +// ─────────────── tab strip ─────────────── + +interface TabStripProps { + activeTab: TabKey; + onChange: (key: TabKey) => void; + counts: Record; } -function SegmentedField({ - label, - value, - options, - onChange, - className, -}: { - label: string; - value: T; - options: ReadonlyArray>; - onChange: (v: T) => void; - className?: string; -}) { +function TabStrip({ activeTab, onChange, counts }: TabStripProps) { return ( -
- -
- {options.map((opt) => { - const active = value === opt.value; +
+ {ALL_TABS.map((key) => { + const label = key === 'general' ? '通用设置' : NETWORK_TABS[key].title; + const count = key === 'general' ? null : counts[key]; + const active = activeTab === key; + return ( + + ); + })} +
+ ); +} + +function countMap(networks: OneBotNetworks): Record { + return { + httpServers: networks.httpServers.length, + httpClients: networks.httpClients.length, + wsServers: networks.wsServers.length, + wsClients: networks.wsClients.length, + }; +} + +// ─────────────── network tab body ─────────────── + +interface NetworkTabViewProps { + kind: NetworkKind; + config: OneBotConfig; + onCreateClick: () => void; + onEdit: (index: number) => void; + onDelete: (index: number) => void; + onToggleEnabled: (index: number, enabled: boolean) => void; +} + +function NetworkTabView({ + kind, + config, + onCreateClick, + onEdit, + onDelete, + onToggleEnabled, +}: NetworkTabViewProps) { + const tab = NETWORK_TABS[kind]; + const list = config.networks[kind]; + // `summarize` is typed per K in NETWORK_TABS; the union here forces a + // widening cast at the call site rather than ladder-of-ifs per tab. + const summarize = tab.summarize as (it: typeof list[number]) => string; + + if (list.length === 0) { + return ( +
+

暂无 {tab.title} 节点

+ +
+ ); + } + + return ( +
+

{tab.description}

+
+ {list.map((item, idx) => { + const others = list.filter((_, i) => i !== idx).map((n) => n.name); + const duplicate = !!item.name && others.includes(item.name); return ( - + onToggleEnabled(idx, v)} + onEdit={() => onEdit(idx)} + onDelete={() => onDelete(idx)} + /> ); })}
@@ -543,211 +388,39 @@ function SegmentedField({ ); } -function SelectField({ - label, - value, - options, - onChange, - className, -}: { - label: string; - value: T; - options: ReadonlyArray>; - onChange: (v: T) => void; - className?: string; -}) { +// ─────────────── empty + loading ─────────────── + +function EmptyState() { return ( -
- - +
+ +

请在左栏选择会话以配置通信节点

); } -const ADAPTER_FORMAT_OPTIONS: ReadonlyArray> = [ - { value: 'array', label: '数组' }, - { value: 'string', label: 'CQ 码' }, -]; - -const ADAPTER_REPORT_OPTIONS: ReadonlyArray> = [ - { value: 'on', label: '开启' }, - { value: 'off', label: '关闭' }, -]; - -const WS_ROLE_OPTIONS: ReadonlyArray> = [ - { value: 'Universal', label: 'Universal' }, - { value: 'Event', label: 'Event' }, - { value: 'Api', label: 'Api' }, -]; - -interface BaseAdapter { - name: string; - enabled?: boolean; - accessToken?: string; - messageFormat: MessageFormat; - reportSelfMessage: boolean; -} - -interface NetworkSectionProps { - title: string; - description?: string; - kind: NetworkKind; - networks: T[]; - onChange: (next: T[]) => void; - renderFields: (item: T, patch: (changes: Partial) => void) => React.ReactNode; - defaultEntry: (suffix: number) => T; -} - -function NetworkSection({ - title, - description, - networks, - onChange, - renderFields, - defaultEntry, -}: NetworkSectionProps) { - const handleAdd = () => { - const used = new Set(networks.map((n) => n.name)); - let suffix = networks.length + 1; - let entry = defaultEntry(suffix); - while (used.has(entry.name)) { - suffix += 1; - entry = defaultEntry(suffix); - } - onChange([...networks, entry]); - }; - - const patchAt = (idx: number, changes: Partial) => { - onChange(networks.map((it, i) => (i === idx ? { ...it, ...changes } : it))); - }; - - const removeAt = (idx: number) => { - onChange(networks.filter((_, i) => i !== idx)); - }; - +function LoadingSkeleton() { return ( -
- {networks.length === 0 ? ( - - ) : ( - networks.map((item, idx) => ( - i !== idx).map((n) => n.name)} - onPatch={(changes) => patchAt(idx, changes)} - onRemove={() => removeAt(idx)} - renderFields={renderFields} - /> - )) - )} -
+
+ + + + +
); } -interface AdapterRowProps { - item: T; - otherNames: string[]; - onPatch: (changes: Partial) => void; - onRemove: () => void; - renderFields: (item: T, patch: (changes: Partial) => void) => React.ReactNode; -} +// ─────────────── helpers ─────────────── -function AdapterRow({ - item, - otherNames, - onPatch, - onRemove, - renderFields, -}: AdapterRowProps) { - const enabled = item.enabled !== false; - const duplicateName = !!item.name && otherNames.includes(item.name); - const blankName = !item.name?.trim(); - - const formatValue: MessageFormat = item.messageFormat ?? 'array'; - const reportValue: 'on' | 'off' = item.reportSelfMessage ? 'on' : 'off'; - - return ( - -
- onPatch({ name: v } as Partial)} - className="sm:w-44" - /> - onPatch({ enabled: v ? undefined : false } as Partial)} - /> - -
- {(blankName || duplicateName) && ( -

- {blankName ? '请填写名称' : '名称与其它适配器重复'} -

- )} - -
{renderFields(item, onPatch)}
- -
- onPatch({ messageFormat: v } as Partial)} - /> - - onPatch({ - reportSelfMessage: v === 'on', - } as Partial) - } - /> -
-
- ); -} - -function updateNetworks( - config: OneBotConfig, - update: (next: OneBotConfig) => void, +/** Names of every adapter except the one currently being edited. */ +function otherNames( + networks: OneBotNetworks, kind: K, - next: OneBotNetworks[K], -): void { - update({ - ...config, - networks: { ...config.networks, [kind]: next }, - }); + excludeIndex: number | null, +): string[] { + const list = networks[kind]; + return list + .filter((_, i) => i !== excludeIndex) + .map((n) => n.name) + .filter((s): s is string => typeof s === 'string' && s.length > 0); } From 7a2de230bfdd45fe54cd8e3e074479dd76232fdd Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 14:31:08 +0800 Subject: [PATCH 43/51] fix(webui): pass aria-checked as a string literal on switch buttons A11y checkers (axe-core / jsx-a11y) flag the boolean form because the ARIA spec defines aria-checked as the enum "true" | "false" | "mixed", not a boolean. React serialized the boolean to the right wire value at runtime, but the inspection layer keys off the JSX expression's static type. Switching to the explicit ternary silences both. --- packages/webui/src/components/config/node-edit-dialog.tsx | 2 +- packages/webui/src/components/config/node-summary-card.tsx | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/webui/src/components/config/node-edit-dialog.tsx b/packages/webui/src/components/config/node-edit-dialog.tsx index b1ca652b..ac6b0b63 100644 --- a/packages/webui/src/components/config/node-edit-dialog.tsx +++ b/packages/webui/src/components/config/node-edit-dialog.tsx @@ -372,7 +372,7 @@ function ToggleSwitch({ value, onChange, ariaLabel }: ToggleSwitchProps) { + +
+
+ ); +} + interface SegmentedOption { value: T; label: string; From 562fd4f7f9c271796604777c3bead43d2dd81289 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 14:58:58 +0800 Subject: [PATCH 46/51] fix(oidb): set envelope reserved=1 on OIDB 0xFE1_2 (user / stranger) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Follow-up to c62f517. Dropping the obsolete field 2 from the body was necessary but insufficient: newer QQ NT still rejects the request with [oidb] one of uid/openid is invaild The actual trigger is the OIDB envelope-level `reserved` flag. Lagrange.Core's FetchStrangerByUin sets `Reserved = 1`, our call sent `Reserved = 0`. The server uses that bit to pick its validation path: - reserved=1 → UIN-form variant: server translates body.uin to the internal uid itself - reserved=0 → UID-form variant: server expects a uid/openid string in the body and rejects when it can't find one Our request body has only `uin` + `keys`, so the UID-form path was always going to fail. Setting `isUid: true` (which is the existing flag that flips envelope `reserved` to 1; the parameter name is historical and misleading) puts the call onto the correct branch. Applied to both call sites that target OidbSvcTrpcTcp.0xfe1_2: - fetchUserProfile (bridge-contacts.ts) — fixes the "failed to load self profile for UIN N" warmup warning. - getStrangerStatus (actions/extras.ts) — same OIDB cmd; would have failed identically if exercised against newer QQ NT. Also updated the `isUid` JSDoc on OidbCall to spell out the actual semantic (UIN-form variant marker, not "this call uses UID-keyed data") since the name will keep tripping people otherwise. --- packages/core/src/bridge/actions/extras.ts | 3 +++ packages/core/src/bridge/bridge-contacts.ts | 8 +++++++- packages/core/src/bridge/bridge-oidb.ts | 14 ++++++++++---- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/packages/core/src/bridge/actions/extras.ts b/packages/core/src/bridge/actions/extras.ts index 38a082a0..3aca81ae 100644 --- a/packages/core/src/bridge/actions/extras.ts +++ b/packages/core/src/bridge/actions/extras.ts @@ -66,6 +66,9 @@ export async function getStrangerStatus(bridge: Bridge, uin: number): Promise ({ key: k })), }; + // Set OIDB envelope `reserved = 1` (the `isUid: true` flag — the + // name is historical, the wire semantic is "this is the UIN-form + // variant of the call"). Without it newer QQ NT versions take the + // UID-form validation path, find neither uid nor openid in the body + // and bounce the request with `[oidb] one of uid/openid is invaild`. + // Matches Lagrange.Core's FetchStrangerByUin (Reserved = 1). const resp = await runOidb(bridge, { cmd: 'OidbSvcTrpcTcp.0xfe1_2', oidbCmd: 0xFE1, subCmd: 2, - request: { schema: OidbUserInfoRequestSchema, value: body }, + request: { schema: OidbUserInfoRequestSchema, value: body, isUid: true }, response: { schema: OidbUserInfoResponseSchema }, }); diff --git a/packages/core/src/bridge/bridge-oidb.ts b/packages/core/src/bridge/bridge-oidb.ts index ac7d78c2..23e71579 100644 --- a/packages/core/src/bridge/bridge-oidb.ts +++ b/packages/core/src/bridge/bridge-oidb.ts @@ -20,10 +20,16 @@ export interface OidbCall { schema: ProtoSchema; value: any; /** - * Sets the OIDB envelope `reserved` field to 1 when true. A handful - * of commands (group/friend list, rkey download) operate on - * UID-keyed data and require this flag — the wire format is - * otherwise identical. + * Sets the OIDB envelope `reserved` field to 1 when true. + * + * The name is historical and misleading: empirically (see Lagrange + * FetchStrangerByUin vs FetchStrangerByUid, fetchGroupList, our own + * highway uploads) the `reserved = 1` flag indicates the UIN-form + * variant of an OIDB call — it tells newer QQ NT to translate the + * UIN in the body to an internal UID rather than running the + * UID-form validator that expects a uid/openid string in the body. + * + * Omit (default false) for genuinely UID-keyed calls. */ isUid?: boolean; }; From b99f5c0bf17cb0f7093e31471cebe22b1f867180 Mon Sep 17 00:00:00 2001 From: stla <130404897+Stlara-F@users.noreply.github.com> Date: Mon, 18 May 2026 07:03:45 +0000 Subject: [PATCH 47/51] fix(request-actions): match group add/invite flags by UID and add regression tests --- .../src/onebot/modules/request-actions.ts | 11 ++- .../core/tests/onebot/request-actions.test.ts | 67 +++++++++++++++++++ 2 files changed, 77 insertions(+), 1 deletion(-) create mode 100644 packages/core/tests/onebot/request-actions.test.ts diff --git a/packages/core/src/onebot/modules/request-actions.ts b/packages/core/src/onebot/modules/request-actions.ts index e2bf9784..9dcdb8b9 100644 --- a/packages/core/src/onebot/modules/request-actions.ts +++ b/packages/core/src/onebot/modules/request-actions.ts @@ -9,11 +9,20 @@ export async function handleGroupAddRequest( // flag format: "add:groupId:uid" or "invite:groupId:uid" (from event-converter) const parts = flag.split(':'); if (parts.length < 3) throw new Error('invalid group request flag'); + const requestType = parts[0]; const groupId = parseInt(parts[1], 10); + const targetUid = parts.slice(2).join(':'); if (!groupId) throw new Error('invalid group_id in flag'); + if (!targetUid) throw new Error('invalid request target in flag'); const requests = await bridge.fetchGroupRequests(); - const matching = requests.find(r => r.groupId === groupId); + const matching = requests.find((r) => { + if (r.groupId !== groupId) return false; + if (requestType === 'add') return r.targetUid === targetUid; + if (requestType === 'invite') return r.invitorUid === targetUid; + return false; + }) || requests.find(r => r.groupId === groupId); + if (!matching) { throw new Error('matching group request not found'); } diff --git a/packages/core/tests/onebot/request-actions.test.ts b/packages/core/tests/onebot/request-actions.test.ts new file mode 100644 index 00000000..6e51dcf5 --- /dev/null +++ b/packages/core/tests/onebot/request-actions.test.ts @@ -0,0 +1,67 @@ +import { describe, expect, it, vi } from 'vitest'; +import { handleGroupAddRequest } from '../../src/onebot/modules/request-actions'; +import type { BridgeInterface } from '../../src/bridge/bridge-interface'; +import type { GroupRequestInfo } from '../../src/bridge/qq-info'; + +function fakeBridge(overrides: Partial = {}): BridgeInterface { + return new Proxy(overrides as BridgeInterface, { + get(target, prop) { + if (prop in target) return (target as any)[prop]; + throw new Error(`fakeBridge: '${String(prop)}' was not stubbed`); + }, + }); +} + +function fakeRequest(overrides: Partial = {}): GroupRequestInfo { + return { + groupId: 999, + groupName: 'g', + targetUid: 'u_t', + targetUin: 5555, + targetName: 'target', + invitorUid: 'u_i', + invitorUin: 7777, + invitorName: 'inviter', + operatorUid: 'u_o', + operatorUin: 8888, + operatorName: 'op', + sequence: 42, + state: 1, + eventType: 7, + comment: 'pls', + filtered: false, + ...overrides, + }; +} + +describe('onebot/modules/request-actions / handleGroupAddRequest', () => { + it('matches add requests by groupId and targetUid', async () => { + const setGroupAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async () => [ + fakeRequest({ groupId: 999, targetUid: 'u_t', sequence: 42, eventType: 7, filtered: false }), + ]), + setGroupAddRequest: setGroupAddRequest as any, + }); + + await handleGroupAddRequest(bridge, 'add:999:u_t', true, 'ok'); + + expect(setGroupAddRequest).toHaveBeenCalledOnce(); + expect(setGroupAddRequest).toHaveBeenCalledWith(999, 42, 7, true, 'ok', false); + }); + + it('matches invite requests by groupId and invitorUid', async () => { + const setGroupAddRequest = vi.fn(async () => {}); + const bridge = fakeBridge({ + fetchGroupRequests: vi.fn(async () => [ + fakeRequest({ groupId: 999, invitorUid: 'u_i', sequence: 97, eventType: 8, filtered: false }), + ]), + setGroupAddRequest: setGroupAddRequest as any, + }); + + await handleGroupAddRequest(bridge, 'invite:999:u_i', false, 'no'); + + expect(setGroupAddRequest).toHaveBeenCalledOnce(); + expect(setGroupAddRequest).toHaveBeenCalledWith(999, 97, 8, false, 'no', false); + }); +}); From 941e60dea5a3c977310f7f55716798e84ab82d9f Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 15:03:45 +0800 Subject: [PATCH 48/51] chore(release): v1.8.5 --- package.json | 2 +- packages/core/package.json | 2 +- packages/runtime/package.json | 2 +- packages/sdk/package.json | 2 +- packages/ui/package.json | 2 +- packages/websocket/package.json | 2 +- packages/webui/package.json | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index b9bb169e..3029715d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "snowluma-monorepo", - "version": "1.8.4", + "version": "1.8.5", "description": "SnowLuma monorepo workspace (pnpm)", "private": true, "type": "module", diff --git a/packages/core/package.json b/packages/core/package.json index 92e2e788..c832ad06 100644 --- a/packages/core/package.json +++ b/packages/core/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/core", - "version": "1.8.4", + "version": "1.8.5", "description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon", "private": true, "type": "module", diff --git a/packages/runtime/package.json b/packages/runtime/package.json index c09d8bcf..ac3a169a 100644 --- a/packages/runtime/package.json +++ b/packages/runtime/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/runtime", - "version": "1.8.4", + "version": "1.8.5", "private": true, "type": "module", "main": "index.mjs", diff --git a/packages/sdk/package.json b/packages/sdk/package.json index 9aef3210..7462553c 100644 --- a/packages/sdk/package.json +++ b/packages/sdk/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.4", + "version": "1.8.5", "description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports", "keywords": [ "snowluma", diff --git a/packages/ui/package.json b/packages/ui/package.json index f70bab9c..62f6a6f7 100644 --- a/packages/ui/package.json +++ b/packages/ui/package.json @@ -4,7 +4,7 @@ "name": "MotricSeven", "email": "motricseven@gmail.com" }, - "version": "1.8.4", + "version": "1.8.5", "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 e97ce0bd..ed3c0963 100644 --- a/packages/websocket/package.json +++ b/packages/websocket/package.json @@ -1,6 +1,6 @@ { "name": "@snowluma/websocket", - "version": "1.8.4", + "version": "1.8.5", "private": true, "type": "module", "main": "./src/index.ts", diff --git a/packages/webui/package.json b/packages/webui/package.json index 32de0fc1..17b798aa 100644 --- a/packages/webui/package.json +++ b/packages/webui/package.json @@ -1,7 +1,7 @@ { "name": "webui", "private": true, - "version": "1.8.4", + "version": "1.8.5", "type": "module", "scripts": { "dev": "vite", From 4d7302a13f537aadc34e0c68ba7c3389e0192a25 Mon Sep 17 00:00:00 2001 From: DrSmoothl <1787882683@qq.com> Date: Mon, 18 May 2026 18:01:57 +0800 Subject: [PATCH 49/51] chore(github): add issue templates for bug reports and feature requests Adds structured YAML issue forms (bug + feature) and a config that disables blank issues and links to the QQ group / Telegram channels already in README. --- .github/ISSUE_TEMPLATE/bug_report.yml | 119 +++++++++++++++++++++ .github/ISSUE_TEMPLATE/config.yml | 11 ++ .github/ISSUE_TEMPLATE/feature_request.yml | 76 +++++++++++++ 3 files changed, 206 insertions(+) create mode 100644 .github/ISSUE_TEMPLATE/bug_report.yml create mode 100644 .github/ISSUE_TEMPLATE/config.yml create mode 100644 .github/ISSUE_TEMPLATE/feature_request.yml diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml new file mode 100644 index 00000000..80b0d277 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -0,0 +1,119 @@ +name: Bug 反馈 +description: 报告一个可复现的问题 +title: "[Bug] " +labels: ["bug"] +body: + - type: markdown + attributes: + value: | + 感谢花时间反馈 Bug。请尽量填全以下信息,方便我们定位问题。 + 在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有相同问题。 + + - type: checkboxes + id: preflight + attributes: + label: 提交前检查 + options: + - label: 我已搜索过 Issues,确认没有重复的反馈 + required: true + - label: 我使用的是 [最新 Release](https://github.com/SnowLuma/SnowLuma/releases) 或当前 `dev` 分支构建 + required: true + + - type: input + id: snowluma-version + attributes: + label: SnowLuma 版本 + description: 启动日志首行或 `package.json` 里的版本号 + placeholder: "例如 1.8.5" + validations: + required: true + + - type: dropdown + id: adapter + attributes: + label: 出问题的适配器 + description: 可多选 + multiple: true + options: + - WebSocket Server + - WebSocket Client + - HTTP Server + - HTTP Post + - WebUI + - Bridge / Core(协议层) + - 其他 / 不确定 + validations: + required: true + + - type: input + id: os + attributes: + label: 操作系统 + placeholder: "例如 Windows 11 23H2 / macOS 14.5 / Ubuntu 22.04" + validations: + required: true + + - type: input + id: node-version + attributes: + label: Node.js 版本 + description: '`node -v` 的输出。如果使用预构建包可填"预构建包"' + placeholder: "例如 v20.11.0 或 预构建包" + validations: + required: true + + - type: input + id: qq-version + attributes: + label: QQ 客户端版本 + description: QQ NT 客户端的版本号 + placeholder: "例如 9.9.15-29722" + + - type: textarea + id: description + attributes: + label: 问题描述 + description: 简要说明发生了什么 + validations: + required: true + + - type: textarea + id: reproduce + attributes: + label: 复现步骤 + description: 详细列出如何触发这个问题 + placeholder: | + 1. 启动 SnowLuma 并登录账号 ... + 2. 通过 HTTP Server 调用 `send_group_msg` ... + 3. 观察到 ... + validations: + required: true + + - type: textarea + id: expected + attributes: + label: 期望行为 + validations: + required: true + + - type: textarea + id: actual + attributes: + label: 实际行为 + validations: + required: true + + - type: textarea + id: logs + attributes: + label: 相关日志 / 错误堆栈 + description: | + 粘贴控制台日志、SSE 实时日志或错误堆栈。 + 请注意脱敏:移除 access token、账号密码、私聊内容等敏感信息。 + render: shell + + - type: textarea + id: extra + attributes: + label: 补充信息 + description: 配置片段(脱敏后)、截图、相关 Issue / PR 链接等 diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 00000000..cb45a4d5 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,11 @@ +blank_issues_enabled: false +contact_links: + - name: QQ 群 + url: https://qm.qq.com/q/g3UMLpWALe + about: 日常使用问题、快速交流可以先来 QQ 群 + - name: Telegram + url: https://t.me/napcatqq + about: 海外用户交流频道 + - name: Releases + url: https://github.com/SnowLuma/SnowLuma/releases + about: 在反馈 Bug 前,请先确认已使用最新发布版本 diff --git a/.github/ISSUE_TEMPLATE/feature_request.yml b/.github/ISSUE_TEMPLATE/feature_request.yml new file mode 100644 index 00000000..6b4b027c --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.yml @@ -0,0 +1,76 @@ +name: 功能请求 +description: 提议一个新功能或对现有功能的增强 +title: "[Feature] " +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: | + 感谢您的建议。在提交前,请先在 [Issues](https://github.com/SnowLuma/SnowLuma/issues?q=is%3Aissue) 中搜索是否已有类似提案。 + + - type: checkboxes + id: preflight + attributes: + label: 提交前检查 + options: + - label: 我已搜索过 Issues,确认没有重复的提案 + required: true + + - type: dropdown + id: scope + attributes: + label: 涉及范围 + multiple: true + options: + - OneBot 协议 / 消息段 + - WebSocket Server / Client 适配器 + - HTTP Server / Post 适配器 + - WebUI 管理面板 + - SDK (`@snowluma/sdk`) + - UI 组件 (`@snowluma/ui`) + - Bridge / Core(协议层) + - 构建 / 发布流程 + - 文档 + - 其他 + validations: + required: true + + - type: textarea + id: problem + attributes: + label: 需求场景 / 当前痛点 + description: 这个功能要解决什么问题?目前是如何变通处理的? + validations: + required: true + + - type: textarea + id: proposal + attributes: + label: 期望方案 + description: 您希望它如何工作?如果是 API 改动,建议给出示例输入 / 输出 + validations: + required: true + + - type: textarea + id: alternatives + attributes: + label: 已考虑的替代方案 + description: 还想过哪些其他实现路径,为什么放弃 + + - type: textarea + id: references + attributes: + label: 参考链接 + description: 例如 OneBot 规范条目、其他实现的对应特性、相关 Issue / PR + placeholder: | + - OneBot v11 规范: https://github.com/botuniverse/onebot-11/... + - 相关讨论: #xxx + + - type: checkboxes + id: willingness + attributes: + label: 您是否愿意提交 PR 来实现这个功能? + options: + - label: 愿意,且需要维护者讨论方案后再动手 + - label: 愿意,已有大致实现思路 + - label: 暂时只提建议 From 9f9db8d16feeeb032b0c4fb2d7fd32393146651b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Mon, 18 May 2026 19:31:42 +0800 Subject: [PATCH 50/51] feat: Add @snowluma/protobuf package Introduce a new @snowluma/protobuf package (v0.0.4) that provides a lightweight protobuf-ts wrapper (NapProto/NapProtoMsg) with type helpers, ProtoField factory, and encode/decode utilities. Adds package.json, tsconfig.json, and the implementation at src/NapProto.ts. pnpm-lock.yaml was updated to include the @protobuf-ts/runtime dependency resolution. --- packages/protobuf/package.json | 14 +++ packages/protobuf/src/NapProto.ts | 202 ++++++++++++++++++++++++++++++ packages/protobuf/tsconfig.json | 5 + pnpm-lock.yaml | 11 ++ 4 files changed, 232 insertions(+) create mode 100644 packages/protobuf/package.json create mode 100644 packages/protobuf/src/NapProto.ts create mode 100644 packages/protobuf/tsconfig.json diff --git a/packages/protobuf/package.json b/packages/protobuf/package.json new file mode 100644 index 00000000..df67a597 --- /dev/null +++ b/packages/protobuf/package.json @@ -0,0 +1,14 @@ +{ + "name": "@snowluma/protobuf", + "type": "module", + "version": "0.0.4", + "description": "A lightweight, elegant, and efficient protobuf-ts solution.From NapNeko/NapCatQQ", + "main": "./src/NapProto.ts", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "prepack": "tsc" + }, + "dependencies": { + "@protobuf-ts/runtime": "^2.9.4" + } +} diff --git a/packages/protobuf/src/NapProto.ts b/packages/protobuf/src/NapProto.ts new file mode 100644 index 00000000..09e47c3a --- /dev/null +++ b/packages/protobuf/src/NapProto.ts @@ -0,0 +1,202 @@ +// @ts-nocheck +import { MessageType, PartialMessage, RepeatType, ScalarType } from '@protobuf-ts/runtime'; +import { PartialFieldInfo } from '@protobuf-ts/runtime/build/types/reflection-info'; + +export type LowerCamelCase = CamelCaseHelper; + +export type CamelCaseHelper< + S extends string, + CapNext extends boolean, + IsFirstChar extends boolean +> = S extends `${infer F}${infer R}` + ? F extends '_' + ? CamelCaseHelper + : F extends `${number}` + ? `${F}${CamelCaseHelper}` + : CapNext extends true + ? `${Uppercase}${CamelCaseHelper}` + : IsFirstChar extends true + ? `${Lowercase}${CamelCaseHelper}` + : `${F}${CamelCaseHelper}` + : ''; + +export type ScalarTypeToTsType = T extends + | ScalarType.DOUBLE + | ScalarType.FLOAT + | ScalarType.INT32 + | ScalarType.FIXED32 + | ScalarType.UINT32 + | ScalarType.SFIXED32 + | ScalarType.SINT32 + ? number + : T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64 + ? bigint + : T extends ScalarType.BOOL + ? boolean + : T extends ScalarType.STRING + ? string + : T extends ScalarType.BYTES + ? Uint8Array + : never; + +export interface BaseProtoFieldType { + kind: 'scalar' | 'message'; + no: number; + type: T; + optional: O; + repeat: R; +} + +export interface ScalarProtoFieldType + extends BaseProtoFieldType { + kind: 'scalar'; +} + +export interface MessageProtoFieldType< + T extends () => ProtoMessageType, + O extends boolean, + R extends O extends true ? false : boolean +> extends BaseProtoFieldType { + kind: 'message'; +} + +export type ProtoFieldType = + | ScalarProtoFieldType + | MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>; + +export type ProtoMessageType = { + [key: string]: ProtoFieldType; +}; + +export function ProtoField< + T extends ScalarType, + O extends boolean = false, + R extends O extends true ? false : boolean = false +> (no: number, type: T, optional?: O, repeat?: R): ScalarProtoFieldType; +export function ProtoField< + T extends () => ProtoMessageType, + O extends boolean = false, + R extends O extends true ? false : boolean = false +> (no: number, type: T, optional?: O, repeat?: R): MessageProtoFieldType; +export function ProtoField ( + no: number, + type: ScalarType | (() => ProtoMessageType), + optional?: boolean, + repeat?: boolean +): ProtoFieldType { + if (typeof type === 'function') { + return { kind: 'message', no, type, optional: optional ?? false, repeat: repeat ?? false }; + } else { + return { kind: 'scalar', no, type, optional: optional ?? false, repeat: repeat ?? false }; + } +} + +export type ProtoFieldReturnType = + NonNullable extends ScalarProtoFieldType + ? ScalarTypeToTsType + : T extends NonNullable> + ? NonNullable, E>> + : never; + +export type RequiredFieldsBaseType = { + [K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase]: T[K] extends { + repeat: true; + } + ? ProtoFieldReturnType[] + : ProtoFieldReturnType; +}; + +export type OptionalFieldsBaseType = { + [K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase : never]?: T[K] extends { + repeat: true; + } + ? ProtoFieldReturnType[] + : ProtoFieldReturnType; +}; + +export type RequiredFieldsType = E extends true + ? Partial> + : RequiredFieldsBaseType; + +export type OptionalFieldsType = E extends true + ? Partial> + : OptionalFieldsBaseType; + +export type NapProtoStructType = RequiredFieldsType & OptionalFieldsType; + +export type NapProtoEncodeStructType = NapProtoStructType; + +export type NapProtoDecodeStructType = NapProtoStructType; + +class NapProtoRealMsg { + private readonly _field: PartialFieldInfo[]; + private readonly _proto_msg: MessageType>; + private static cache = new WeakMap>(); + + private constructor (fields: T) { + this._field = Object.keys(fields).map((key) => { + const field = fields[key]; + if (field.kind === 'scalar') { + const repeatType = field.repeat + ? [ScalarType.STRING, ScalarType.BYTES].includes(field.type) + ? RepeatType.UNPACKED + : RepeatType.PACKED + : RepeatType.NO; + return { + no: field.no, + name: key, + kind: 'scalar', + T: field.type, + opt: field.optional, + repeat: repeatType, + }; + } else if (field.kind === 'message') { + return { + no: field.no, + name: key, + kind: 'message', + repeat: field.repeat ? RepeatType.PACKED : RepeatType.NO, + T: () => NapProtoRealMsg.getInstance(field.type())._proto_msg, + }; + } else { + throw new Error(`Unknown field kind: ${field.kind}`); + } + }) as PartialFieldInfo[]; + this._proto_msg = new MessageType>('nya', this._field); + } + + static getInstance (fields: T): NapProtoRealMsg { + let instance = this.cache.get(fields); + if (!instance) { + instance = new NapProtoRealMsg(fields); + this.cache.set(fields, instance); + } + return instance; + } + + encode (data: NapProtoEncodeStructType): Uint8Array { + return this._proto_msg.toBinary(this._proto_msg.create(data as PartialMessage>)); + } + + decode (data: Uint8Array): NapProtoDecodeStructType { + return this._proto_msg.fromBinary(data) as NapProtoDecodeStructType; + } +} + +export class NapProtoMsg { + private realMsg: NapProtoRealMsg; + + constructor (fields: T) { + this.realMsg = NapProtoRealMsg.getInstance(fields); + } + + encode (data: NapProtoEncodeStructType): Uint8Array { + return this.realMsg.encode(data); + } + + decode (data: Uint8Array): NapProtoDecodeStructType { + return this.realMsg.decode(data); + } +} + +export { ScalarType } from '@protobuf-ts/runtime'; diff --git a/packages/protobuf/tsconfig.json b/packages/protobuf/tsconfig.json new file mode 100644 index 00000000..cd0e5b46 --- /dev/null +++ b/packages/protobuf/tsconfig.json @@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "include": ["src/**/*"], + "exclude": ["node_modules"] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index be5db7cb..3d3a1829 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,6 +64,12 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(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/protobuf: + dependencies: + '@protobuf-ts/runtime': + specifier: ^2.9.4 + version: 2.11.1 + packages/runtime: {} packages/sdk: @@ -680,6 +686,9 @@ packages: resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} engines: {node: '>= 10.0.0'} + '@protobuf-ts/runtime@2.11.1': + resolution: {integrity: sha512-KuDaT1IfHkugM2pyz+FwiY80ejWrkH1pAtOBOZFuR6SXEFTsnb/jiQWQ1rCIrcKx2BtyxnxW6BWwsVSA/Ie+WQ==} + '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -3019,6 +3028,8 @@ snapshots: '@parcel/watcher-win32-x64': 2.5.6 optional: true + '@protobuf-ts/runtime@2.11.1': {} + '@radix-ui/number@1.1.1': {} '@radix-ui/primitive@1.1.3': {} From df691c4e8fb61adfb61297bfd8de28a48d65211e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=89=8B=E7=93=9C=E4=B8=80=E5=8D=81=E9=9B=AA?= Date: Mon, 18 May 2026 20:43:32 +0800 Subject: [PATCH 51/51] Revert "feat: Add @snowluma/protobuf package" This reverts commit 9f9db8d16feeeb032b0c4fb2d7fd32393146651b. --- packages/protobuf/package.json | 14 --- packages/protobuf/src/NapProto.ts | 202 ------------------------------ packages/protobuf/tsconfig.json | 5 - pnpm-lock.yaml | 11 -- 4 files changed, 232 deletions(-) delete mode 100644 packages/protobuf/package.json delete mode 100644 packages/protobuf/src/NapProto.ts delete mode 100644 packages/protobuf/tsconfig.json diff --git a/packages/protobuf/package.json b/packages/protobuf/package.json deleted file mode 100644 index df67a597..00000000 --- a/packages/protobuf/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "@snowluma/protobuf", - "type": "module", - "version": "0.0.4", - "description": "A lightweight, elegant, and efficient protobuf-ts solution.From NapNeko/NapCatQQ", - "main": "./src/NapProto.ts", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "prepack": "tsc" - }, - "dependencies": { - "@protobuf-ts/runtime": "^2.9.4" - } -} diff --git a/packages/protobuf/src/NapProto.ts b/packages/protobuf/src/NapProto.ts deleted file mode 100644 index 09e47c3a..00000000 --- a/packages/protobuf/src/NapProto.ts +++ /dev/null @@ -1,202 +0,0 @@ -// @ts-nocheck -import { MessageType, PartialMessage, RepeatType, ScalarType } from '@protobuf-ts/runtime'; -import { PartialFieldInfo } from '@protobuf-ts/runtime/build/types/reflection-info'; - -export type LowerCamelCase = CamelCaseHelper; - -export type CamelCaseHelper< - S extends string, - CapNext extends boolean, - IsFirstChar extends boolean -> = S extends `${infer F}${infer R}` - ? F extends '_' - ? CamelCaseHelper - : F extends `${number}` - ? `${F}${CamelCaseHelper}` - : CapNext extends true - ? `${Uppercase}${CamelCaseHelper}` - : IsFirstChar extends true - ? `${Lowercase}${CamelCaseHelper}` - : `${F}${CamelCaseHelper}` - : ''; - -export type ScalarTypeToTsType = T extends - | ScalarType.DOUBLE - | ScalarType.FLOAT - | ScalarType.INT32 - | ScalarType.FIXED32 - | ScalarType.UINT32 - | ScalarType.SFIXED32 - | ScalarType.SINT32 - ? number - : T extends ScalarType.INT64 | ScalarType.UINT64 | ScalarType.FIXED64 | ScalarType.SFIXED64 | ScalarType.SINT64 - ? bigint - : T extends ScalarType.BOOL - ? boolean - : T extends ScalarType.STRING - ? string - : T extends ScalarType.BYTES - ? Uint8Array - : never; - -export interface BaseProtoFieldType { - kind: 'scalar' | 'message'; - no: number; - type: T; - optional: O; - repeat: R; -} - -export interface ScalarProtoFieldType - extends BaseProtoFieldType { - kind: 'scalar'; -} - -export interface MessageProtoFieldType< - T extends () => ProtoMessageType, - O extends boolean, - R extends O extends true ? false : boolean -> extends BaseProtoFieldType { - kind: 'message'; -} - -export type ProtoFieldType = - | ScalarProtoFieldType - | MessageProtoFieldType<() => ProtoMessageType, boolean, boolean>; - -export type ProtoMessageType = { - [key: string]: ProtoFieldType; -}; - -export function ProtoField< - T extends ScalarType, - O extends boolean = false, - R extends O extends true ? false : boolean = false -> (no: number, type: T, optional?: O, repeat?: R): ScalarProtoFieldType; -export function ProtoField< - T extends () => ProtoMessageType, - O extends boolean = false, - R extends O extends true ? false : boolean = false -> (no: number, type: T, optional?: O, repeat?: R): MessageProtoFieldType; -export function ProtoField ( - no: number, - type: ScalarType | (() => ProtoMessageType), - optional?: boolean, - repeat?: boolean -): ProtoFieldType { - if (typeof type === 'function') { - return { kind: 'message', no, type, optional: optional ?? false, repeat: repeat ?? false }; - } else { - return { kind: 'scalar', no, type, optional: optional ?? false, repeat: repeat ?? false }; - } -} - -export type ProtoFieldReturnType = - NonNullable extends ScalarProtoFieldType - ? ScalarTypeToTsType - : T extends NonNullable> - ? NonNullable, E>> - : never; - -export type RequiredFieldsBaseType = { - [K in keyof T as T[K] extends { optional: true; } ? never : LowerCamelCase]: T[K] extends { - repeat: true; - } - ? ProtoFieldReturnType[] - : ProtoFieldReturnType; -}; - -export type OptionalFieldsBaseType = { - [K in keyof T as T[K] extends { optional: true; } ? LowerCamelCase : never]?: T[K] extends { - repeat: true; - } - ? ProtoFieldReturnType[] - : ProtoFieldReturnType; -}; - -export type RequiredFieldsType = E extends true - ? Partial> - : RequiredFieldsBaseType; - -export type OptionalFieldsType = E extends true - ? Partial> - : OptionalFieldsBaseType; - -export type NapProtoStructType = RequiredFieldsType & OptionalFieldsType; - -export type NapProtoEncodeStructType = NapProtoStructType; - -export type NapProtoDecodeStructType = NapProtoStructType; - -class NapProtoRealMsg { - private readonly _field: PartialFieldInfo[]; - private readonly _proto_msg: MessageType>; - private static cache = new WeakMap>(); - - private constructor (fields: T) { - this._field = Object.keys(fields).map((key) => { - const field = fields[key]; - if (field.kind === 'scalar') { - const repeatType = field.repeat - ? [ScalarType.STRING, ScalarType.BYTES].includes(field.type) - ? RepeatType.UNPACKED - : RepeatType.PACKED - : RepeatType.NO; - return { - no: field.no, - name: key, - kind: 'scalar', - T: field.type, - opt: field.optional, - repeat: repeatType, - }; - } else if (field.kind === 'message') { - return { - no: field.no, - name: key, - kind: 'message', - repeat: field.repeat ? RepeatType.PACKED : RepeatType.NO, - T: () => NapProtoRealMsg.getInstance(field.type())._proto_msg, - }; - } else { - throw new Error(`Unknown field kind: ${field.kind}`); - } - }) as PartialFieldInfo[]; - this._proto_msg = new MessageType>('nya', this._field); - } - - static getInstance (fields: T): NapProtoRealMsg { - let instance = this.cache.get(fields); - if (!instance) { - instance = new NapProtoRealMsg(fields); - this.cache.set(fields, instance); - } - return instance; - } - - encode (data: NapProtoEncodeStructType): Uint8Array { - return this._proto_msg.toBinary(this._proto_msg.create(data as PartialMessage>)); - } - - decode (data: Uint8Array): NapProtoDecodeStructType { - return this._proto_msg.fromBinary(data) as NapProtoDecodeStructType; - } -} - -export class NapProtoMsg { - private realMsg: NapProtoRealMsg; - - constructor (fields: T) { - this.realMsg = NapProtoRealMsg.getInstance(fields); - } - - encode (data: NapProtoEncodeStructType): Uint8Array { - return this.realMsg.encode(data); - } - - decode (data: Uint8Array): NapProtoDecodeStructType { - return this.realMsg.decode(data); - } -} - -export { ScalarType } from '@protobuf-ts/runtime'; diff --git a/packages/protobuf/tsconfig.json b/packages/protobuf/tsconfig.json deleted file mode 100644 index cd0e5b46..00000000 --- a/packages/protobuf/tsconfig.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "extends": "../../tsconfig.base.json", - "include": ["src/**/*"], - "exclude": ["node_modules"] -} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3d3a1829..be5db7cb 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -64,12 +64,6 @@ importers: specifier: ^4.1.4 version: 4.1.4(@types/node@24.12.2)(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/protobuf: - dependencies: - '@protobuf-ts/runtime': - specifier: ^2.9.4 - version: 2.11.1 - packages/runtime: {} packages/sdk: @@ -686,9 +680,6 @@ packages: resolution: {integrity: sha512-tmmZ3lQxAe/k/+rNnXQRawJ4NjxO2hqiOLTHvWchtGZULp4RyFeh6aU4XdOYBFe2KE1oShQTv4AblOs2iOrNnQ==} engines: {node: '>= 10.0.0'} - '@protobuf-ts/runtime@2.11.1': - resolution: {integrity: sha512-KuDaT1IfHkugM2pyz+FwiY80ejWrkH1pAtOBOZFuR6SXEFTsnb/jiQWQ1rCIrcKx2BtyxnxW6BWwsVSA/Ie+WQ==} - '@radix-ui/number@1.1.1': resolution: {integrity: sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g==} @@ -3028,8 +3019,6 @@ snapshots: '@parcel/watcher-win32-x64': 2.5.6 optional: true - '@protobuf-ts/runtime@2.11.1': {} - '@radix-ui/number@1.1.1': {} '@radix-ui/primitive@1.1.3': {}