Compare commits

...

17 Commits

Author SHA1 Message Date
snowluma-bot[bot]
231d60411b Merge pull request #48 from SnowLuma/dev
chore: promote dev → main (b94775c)
2026-05-18 05:31:37 +00:00
DrSmoothl
b94775cb6f chore(release): v1.8.4 2026-05-18 13:31:17 +08:00
DrSmoothl
5524c73eed chore(webui): keep search engines out of the admin surface
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. <meta name="robots"> (plus googlebot / bingbot) in index.html
   as a fallback for the case where a reverse proxy strips the
   X-Robots-Tag header.
2026-05-18 13:18:31 +08:00
DrSmoothl
4c513c015d feat(logger): runtime log level toggle via WebUI
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.
2026-05-18 13:15:05 +08:00
DrSmoothl
4a49c55775 fix(hook): refresh pipe snapshot before verifying unload took
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.
2026-05-18 13:07:10 +08:00
DrSmoothl
e04a539b26 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.
2026-05-18 12:47:34 +08:00
DrSmoothl
257686eac6 feat(logger): identity-aware readable event rendering
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.
2026-05-18 12:32:18 +08:00
DrSmoothl
84e746c278 chore(observability): defensive depth pass
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).
2026-05-18 01:36:12 +08:00
DrSmoothl
7ec479bb88 feat(logger): protocol-layer observability for highway and msg-push
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.
2026-05-18 01:29:06 +08:00
DrSmoothl
1ba45e2659 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.
2026-05-18 01:19:30 +08:00
DrSmoothl
1d66693cc3 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/<uin>/
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.
2026-05-18 00:57:46 +08:00
DrSmoothl
93b9b03667 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/<uin>/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.
2026-05-18 00:50:15 +08:00
DrSmoothl
51f46e15fd 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.
2026-05-18 00:44:30 +08:00
snowluma-bot[bot]
bee1e67c60 Merge pull request #46 from SnowLuma/dev
chore: promote dev → main (c6f4d5c)
2026-05-17 16:11:03 +00:00
DrSmoothl
c6f4d5c5a2 chore(release): v1.8.3 2026-05-18 00:10:43 +08:00
DrSmoothl
82b52a3b2d update README 2026-05-18 00:10:12 +08:00
DrSmoothl
360fe8bd49 fix(forward): carry image/video in private merged forward
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.
2026-05-17 23:47:12 +08:00
50 changed files with 2239 additions and 211 deletions

132
README.md
View File

@@ -1,22 +1,130 @@
# ❄️ SnowLuma
> Next Remote Protocol Framework.
<h1 align="center">❄️ SnowLuma</h1>
<p align="center">
<i>Next Remote Protocol Framework.</i>
</p>
## 关于项目
项目处于开发初期,仅支持部分功能,高速迭代中,随时可能出现破坏性更新。
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases"><img alt="Release" src="https://img.shields.io/github/v/release/SnowLuma/SnowLuma?label=release&style=flat-square"></a>
<a href="https://github.com/SnowLuma/SnowLuma/actions"><img alt="Build" src="https://img.shields.io/github/actions/workflow/status/SnowLuma/SnowLuma/release.yml?branch=main&style=flat-square&label=build"></a>
<a href="https://www.npmjs.com/package/@snowluma/sdk"><img alt="@snowluma/sdk" src="https://img.shields.io/npm/v/%40snowluma%2Fsdk?style=flat-square&label=%40snowluma%2Fsdk&color=cb3837"></a>
<a href="https://www.npmjs.com/package/@snowluma/ui"><img alt="@snowluma/ui" src="https://img.shields.io/npm/v/%40snowluma%2Fui?style=flat-square&label=%40snowluma%2Fui&color=cb3837"></a>
<a href="https://github.com/SnowLuma/SnowLuma/stargazers"><img alt="Stars" src="https://img.shields.io/github/stars/SnowLuma/SnowLuma?style=flat-square"></a>
</p>
<p align="center">
<a href="https://github.com/SnowLuma/SnowLuma/releases">Releases</a> ·
<a href="https://github.com/SnowLuma/SnowLuma/issues">Issues</a> ·
<a href="https://qm.qq.com/q/g3UMLpWALe">QQ 群</a> ·
<a href="https://t.me/napcatqq">Telegram</a>
</p>
---
## 简介
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["协议层<br/><sub>packet pipeline · cmd 分派</sub>"]
C["Bridge 层<br/><sub>会话调度 · 花名册缓存 · 消息发送</sub>"]
D["OneBot 层<br/><sub>Event Converter · Action Handler</sub>"]
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技术。
<a href="https://github.com/SnowLuma/SnowLuma/graphs/contributors">
<img src="https://contrib.rocks/image?repo=SnowLuma/SnowLuma" alt="Contributors" />
</a>
## 加入我们
[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
## Star 趋势
[SnowLuma-TG](https://t.me/napcatqq)
<a href="https://star-history.com/#SnowLuma/SnowLuma&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=SnowLuma/SnowLuma&type=Date" />
</picture>
</a>
## 社区
- QQ 群:[SnowLuma-QQ](https://qm.qq.com/q/g3UMLpWALe)
- Telegram:[SnowLuma-TG](https://t.me/napcatqq)
- 问题反馈:[GitHub Issues](https://github.com/SnowLuma/SnowLuma/issues)

View File

@@ -1,6 +1,6 @@
{
"name": "snowluma-monorepo",
"version": "1.8.2",
"version": "1.8.4",
"description": "SnowLuma monorepo workspace (pnpm)",
"private": true,
"type": "module",

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/core",
"version": "1.8.2",
"version": "1.8.4",
"description": "SnowLuma core - NTQQ packet sniffer with Node.js native addon",
"private": true,
"type": "module",

View File

@@ -29,14 +29,21 @@ async function buildForwardPushBody(
bridge: Bridge,
node: ForwardNodePayload,
groupId?: number,
userUid?: string,
): Promise<Record<string, unknown>> {
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<string> {
export async function uploadForwardNodes(
bridge: Bridge,
nodes: ForwardNodePayload[],
groupId?: number,
userId?: number,
): Promise<string> {
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: [
{

View File

@@ -92,7 +92,7 @@ export interface BridgeInterface {
fetchGroupFileCount(groupId: number): Promise<{ fileCount: number; maxCount: number }>;
// ─── Forward ───
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string>;
uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string>;
fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]>;
// ─── Message ops ───

View File

@@ -454,7 +454,7 @@ export class Bridge implements BridgeInterface {
async fetchPrivatePttUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivatePttUrlByNode_(this, node); }
async fetchGroupVideoUrlByNode(groupId: number, node: MediaIndexNode): Promise<string> { return fetchGroupVideoUrlByNode_(this, groupId, node); }
async fetchPrivateVideoUrlByNode(node: MediaIndexNode): Promise<string> { return fetchPrivateVideoUrlByNode_(this, node); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId); }
async uploadForwardNodes(nodes: ForwardNodePayload[], groupId?: number, userId?: number): Promise<string> { return uploadForwardNodes_(this, nodes, groupId, userId); }
async fetchForwardNodes(resId: string): Promise<ForwardNodePayload[]> { return fetchForwardNodes_(this, resId); }
async deleteGroupFile(groupId: number, fileId: string): Promise<void> { return deleteGroupFile_(this, groupId, fileId); }
async moveGroupFile(groupId: number, fileId: string, parentDirectory: string, targetDirectory: string): Promise<void> { return moveGroupFile_(this, groupId, fileId, parentDirectory, targetDirectory); }

View File

@@ -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<Uint8Array> {
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',

View File

@@ -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<any> {
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<any> {
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<any> {
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;

View File

@@ -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<PttPay
const silk = await encodeSilk(inputPath, tempDir);
if (silk.converted) {
cleanups.push(() => { 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<Uint8Array> {
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',

View File

@@ -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<Uint8Array> {
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[] = [
{

View File

@@ -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));
}
}
}

View File

@@ -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 [];
};

View File

@@ -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 [];
};

View File

@@ -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) {

View File

@@ -20,10 +20,23 @@ 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';
import { formatEvent } from '../utils/event-format';
const log = createLogger('Bridge');
const eventLog = createLogger('Event');
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<QQEventVariant, { kind: 'group_member_join' | 'group_member_leave' }>;
@@ -43,8 +56,18 @@ export interface PacketPipelineDeps {
export class IncomingPacketPipeline {
private cmdHandlers_ = new Map<string, CmdParser[]>();
private memberRefreshTasks_ = new Map<number, Promise<void>>();
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) ?? [];
@@ -65,15 +88,18 @@ 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(event);
printEvent(this.eventLog, this.deps.identity, 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 +119,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, this.deps.identity, event);
this.emit(event);
}
@@ -166,9 +192,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);
@@ -226,50 +252,16 @@ export class IncomingPacketPipeline {
}
}
function formatEventUser(uin: number, uid?: string): string {
if (uin > 0) return String(uin);
return uid || '未知用户';
}
function printEvent(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':
eventLog.warn('群撤回 %d | %d 被 %d 撤回', event.groupId, event.authorUin, event.operatorUin);
break;
case 'friend_recall':
eventLog.warn('私聊撤回 %d 撤回了消息', event.userUin);
break;
case 'group_member_join':
eventLog.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);
break;
case 'group_mute':
eventLog.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 ? '+' : '-');
break;
case 'friend_poke':
eventLog.info('戳一戳 %d -> %d', event.userUin, event.targetUin);
break;
case 'group_poke':
eventLog.info('群戳 %d | %d -> %d', event.groupId, event.userUin, event.targetUin);
break;
case 'friend_request':
eventLog.warn('好友请求 %d: %s', event.fromUin, event.message);
break;
case 'group_invite':
eventLog.warn('群邀请 %d -> 群%d', event.fromUin, event.groupId);
break;
case 'group_essence':
eventLog.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);
}
}

View File

@@ -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;
}
}

View File

@@ -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<string, string>, 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 [];
}
}

View File

@@ -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;
}
}

View File

@@ -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<void>;
};
/** 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);

View File

@@ -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);
});

View File

@@ -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<import('./types').ApiRespon
export class ApiHandler {
private readonly handlers = new Map<string, ActionHandler>();
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<import('./types').ApiResponse> {
const handler = this.handlers.get(action);
if (!handler) {
this.log.debug('unknown action %s', action);
return failedResponse(RETCODE.UNKNOWN_ACTION, 'unknown action');
}
// Entry log goes to file always (debug); console only when level is
// dialed down to debug. Caller-perspective summary lets the operator
// grep "what did the bot get asked to do" without scraping wire logs.
this.log.debug('%s params=%s', action, summarizeParams(params));
try {
return await handler(params);
} catch (error) {
// Action failures are almost always param-shape problems coming
// from the OneBot client; warn (not error) is the right level so
// the log file stays a useful signal of real internal faults.
this.log.warn('%s failed: %s\n%s',
action,
error instanceof Error ? error.message : String(error),
error instanceof Error ? (error.stack ?? '') : '');
const message = error instanceof Error ? error.message : 'internal error';
return failedResponse(RETCODE.INTERNAL_ERROR, message);
}

View File

@@ -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,
@@ -19,9 +19,10 @@ import {
HttpPostAdapter,
type NetworkAdapterContext,
} from './network';
import { createLogger } from '../utils/logger';
import { createLogger, type Logger } from '../utils/logger';
import { formatGroup, formatMessageSegments, formatReply, formatUser } from '../utils/event-format';
const log = createLogger('Event');
const moduleLog = createLogger('Event');
export class OneBotInstance {
readonly uin: string;
@@ -40,12 +41,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'));
@@ -85,10 +91,12 @@ 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();
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);
@@ -99,7 +107,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 {
@@ -107,7 +117,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();
}
@@ -136,8 +148,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 {
@@ -206,7 +222,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);
@@ -224,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
// ("[回复 <user>: <body>...]" instead of "[回复:1234567890]").
const renderedParts: string[] = [];
const message = event.message;
if (Array.isArray(message)) {
for (const seg of message) {
if (typeof seg !== 'object' || seg === null || Array.isArray(seg)) continue;
const type = String(seg.type ?? '');
const data: Record<string, unknown> = (
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<string, unknown>
: {};
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);
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);
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}`);
}
}

View File

@@ -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<string, unknown>, 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({

View File

@@ -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);

View File

@@ -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<HttpClientNetwork> {
private options: EventReportOptions;
private signature_: string;
private readonly log: Logger;
constructor(name: string, config: HttpClientNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
this.signature_ = bindingSignature(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
@@ -74,7 +77,9 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
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<void> {
@@ -106,11 +111,11 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
}
}
} 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 +126,7 @@ export class HttpPostAdapter extends IOneBotNetworkAdapter<HttpClientNetwork> {
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));
}
}
}

View File

@@ -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<HttpServerNetwork> {
private server: Server | null = null;
private readonly log: Logger;
constructor(name: string, config: HttpServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
// HTTP server never receives events — `isActive` purely tracks the
@@ -81,7 +88,7 @@ export class HttpServerAdapter extends IOneBotNetworkAdapter<HttpServerNetwork>
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<HttpServerNetwork>
);
});
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');

View File

@@ -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<WsClientNetwork> {
@@ -26,11 +26,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
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,12 +114,14 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
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);
});
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', () => {
@@ -126,7 +131,7 @@ export class WsClientAdapter extends IOneBotNetworkAdapter<WsClientNetwork> {
});
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));
});
}

View File

@@ -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<WsServerNetwork> {
private wss: WebSocketServer | null = null;
private connections = new Map<WebSocket, ForwardConn>();
private options: EventReportOptions;
private readonly log: Logger;
constructor(name: string, config: WsServerNetwork, ctx: NetworkAdapterContext) {
super(name, config, ctx);
this.options = resolveReportOptions(config);
const uinNum = Number.parseInt(ctx.uin, 10);
this.log = Number.isFinite(uinNum) && uinNum > 0 ? moduleLog.child({ uin: uinNum }) : moduleLog;
}
override get isActive(): boolean {
@@ -114,7 +117,7 @@ export class WsServerAdapter extends IOneBotNetworkAdapter<WsServerNetwork> {
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<WsServerNetwork> {
});
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<WsServerNetwork> {
});
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') {

View File

@@ -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<string, unknown>
: {};
parts.push(renderSegment(type, data));
}
return parts.join(' ').trim() || '[空消息]';
} catch {
return '[消息渲染异常]';
}
}
function renderSegment(type: string, data: Record<string, unknown>): 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 "[回复:<id>]" 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;
}
}

View File

@@ -0,0 +1,295 @@
// File transport for the SnowLuma logger.
//
// Writes plain text (ANSI stripped) to:
// <SNOWLUMA_LOG_DIR>/snowluma-YYYY-MM-DD.log (shared, all UINs)
// <SNOWLUMA_LOG_DIR>/<uin>/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 on each day rollover.
//
// 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';
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;
// 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-\x08\x0B-\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;
}
/**
* 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 file: OpenFile | null = null;
constructor(
private readonly dir: string,
private readonly maxBytes: number,
private readonly retainDays: number,
) {
try {
fs.mkdirSync(dir, { recursive: true });
} catch (err) {
this.disabled = true;
// eslint-disable-next-line no-console
console.error(
`[logger] failed to create log dir ${dir}: ${err instanceof Error ? err.message : String(err)}`,
);
return;
}
this.cleanup();
}
get isDisabled(): boolean {
return this.disabled;
}
get currentPath(): string | null {
return this.file?.path ?? null;
}
write(data: string, bytes: number): void {
if (this.disabled) return;
const today = todayString();
this.ensureForToday(today);
if (!this.file) return;
if (this.file.bytes + bytes > this.maxBytes && this.file.bytes > 0) {
this.rotateBySize();
if (!this.file) return;
}
this.file.stream.write(data);
this.file.bytes += bytes;
}
close(): Promise<void> {
const f = this.file;
this.file = null;
if (!f) return Promise.resolve();
return new Promise((resolve) => {
try {
f.stream.end(() => resolve());
} catch {
resolve();
}
});
}
private ensureForToday(today: string): void {
if (this.file && this.file.date === today) return;
if (this.file) {
try {
this.file.stream.end();
} catch {
/* ignore */
}
this.file = null;
this.cleanup();
}
// 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.file = this.openFile(today, idx);
}
private rotateBySize(): void {
if (!this.file) return;
const date = this.file.date;
try {
this.file.stream.end();
} catch {
/* ignore */
}
let next = this.file.splitIndex + 1;
while (fs.existsSync(this.pathFor(date, next))) next++;
this.file = 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]!;
if (dateOf(dateStr).getTime() < cutoff) {
try {
fs.unlinkSync(path.join(this.dir, name));
} catch {
/* ignore */
}
}
}
}
}
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<number, FileWriter>();
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<void> {
const closes: Promise<void>[] = [];
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 {
if (!singleton) singleton = new FileTransport();
return singleton;
}
/** Reset state between tests. Closes all active file handles. */
export async function _resetFileTransportForTesting(): Promise<void> {
if (singleton) await singleton.close();
singleton = null;
}

View File

@@ -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<string, unknown>)) {
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(' ');
}

View File

@@ -1,4 +1,5 @@
import { format } from 'util';
import { getFileTransport } from './log-file-transport';
type LogLevel = 'debug' | 'info' | 'success' | 'warn' | 'error';
@@ -7,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<string, unknown>;
}
// 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<LogLevel, number> = {
debug: 10,
info: 20,
@@ -55,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 {
@@ -78,43 +113,72 @@ 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 {
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 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,
};
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. 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-\x08\x0B-\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. UIN routes the
// line to its per-account sub-file in addition to the shared one.
getFileTransport().write(line, options.uin);
}
/**
* 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<void> {
return getFileTransport().close();
}
export function getRecentLogs(limit = 300): LogEntry[] {
@@ -135,15 +199,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 });
}

View File

@@ -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';
@@ -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 <meta robots> 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;
@@ -340,6 +360,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) {

View File

@@ -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<string, number> = {};
for (let i = 0; i < 30; i++) params[`field_with_some_padding_${i}`] = i;
const out = summarizeParams(params);
expect(out.length).toBeLessThan(220);
expect(out.endsWith('...')).toBe(true);
});
it('handles null / undefined inputs gracefully', () => {
expect(summarizeParams(null)).toBe('{}');
expect(summarizeParams(undefined)).toBe('{}');
});
});
describe('ApiHandler dispatch logging', () => {
it('emits a debug entry under [Bridge.Action] when an action is called', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('echo', async () => ({ status: 'ok', retcode: 0, data: null }));
await handler.handle('echo', { group_id: 67890, message: [1, 2, 3] });
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry).toBeDefined();
expect(entry!.uin).toBe(12345);
expect(entry!.message).toContain('echo');
expect(entry!.message).toContain('group_id=67890');
expect(entry!.message).toContain('message=[len=3]');
});
it('emits a warn line with the error stack when the handler throws', async () => {
const handler = new ApiHandler(emptyContext(), 12345);
handler.registerAction('boom', async () => {
throw new Error('kapow');
});
const result = await handler.handle('boom', {});
expect(result.status).toBe('failed');
const warn = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'warn');
expect(warn).toBeDefined();
expect(warn!.message).toContain('boom');
expect(warn!.message).toContain('kapow');
// stack contains the test file path; just check that something stack-shaped is appended
expect(warn!.message).toMatch(/at\s+/);
});
it('logs unknown actions at debug level', async () => {
const handler = new ApiHandler(emptyContext(), 99);
await handler.handle('not_a_real_action', {});
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.message.includes('unknown action'));
expect(entry).toBeDefined();
expect(entry!.level).toBe('debug');
});
it('falls back to the module-level logger (no uin slot) when uin is omitted', async () => {
const handler = new ApiHandler(emptyContext());
handler.registerAction('ping', async () => ({ status: 'ok', retcode: 0, data: null }));
await handler.handle('ping', {});
const entry = captured.find((e) => e.scope === 'Bridge.Action' && e.level === 'debug');
expect(entry).toBeDefined();
expect(entry!.uin).toBeUndefined();
});
});

View File

@@ -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<number, { groupName: string }>;
members?: Record<string, { uin: number; card?: string; nickname?: string }>;
friends?: Record<number, { uin: number; nickname?: string; remark?: string }>;
} = {}): 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<number, Record<string, unknown>>): 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 [回复:<id>] 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 撤回');
});
});

View File

@@ -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', () => {

View File

@@ -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<string, string | undefined> = {};
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): 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$/);
});
});

View File

@@ -0,0 +1,227 @@
// 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, getLogLevel, setLogLevel, 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<string, string | undefined> = {};
function setEnv(env: Partial<Record<(typeof ENV_KEYS)[number], string | undefined>>): 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);
});
});
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<typeof getLogLevel>;
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']);
});
});

View File

@@ -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<string, unknown>,
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');
});
});

View File

@@ -12,6 +12,18 @@ 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=<tmp>.
//
// Run at debug level so tests asserting on debug-level log entries
// (e.g. action dispatch entry lines) actually see them via the
// ring buffer / subscribers, which sit behind the console-level gate.
env: {
SNOWLUMA_LOG_FILE: '0',
SNOWLUMA_LOG_LEVEL: 'debug'
}
}
});

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/runtime",
"version": "1.8.2",
"version": "1.8.4",
"private": true,
"type": "module",
"main": "index.mjs",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.8.2",
"version": "1.8.4",
"description": "TypeScript SDK for SnowLuma OneBot HTTP and WebSocket transports",
"keywords": [
"snowluma",

View File

@@ -4,7 +4,7 @@
"name": "MotricSeven",
"email": "motricseven@gmail.com"
},
"version": "1.8.2",
"version": "1.8.4",
"description": "Shared SnowLuma UI primitives — Tailwind 4 theme tokens + shadcn-style atomic components",
"keywords": [
"snowluma",

View File

@@ -1,6 +1,6 @@
{
"name": "@snowluma/websocket",
"version": "1.8.2",
"version": "1.8.4",
"private": true,
"type": "module",
"main": "./src/index.ts",

View File

@@ -5,6 +5,10 @@
<link rel="icon" type="image/png" href="/logo.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0ea5e9" />
<!-- WebUI is an admin surface; tell every compliant crawler to skip it. -->
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="googlebot" content="noindex, nofollow, noarchive, nosnippet" />
<meta name="bingbot" content="noindex, nofollow, noarchive, nosnippet" />
<title>SnowLuma 控制台</title>
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />

View File

@@ -1,7 +1,7 @@
{
"name": "webui",
"private": true,
"version": "1.8.2",
"version": "1.8.4",
"type": "module",
"scripts": {
"dev": "vite",

View File

@@ -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<LogEntry['level'], string> = {
const levelClass: Record<LogLevel, string> = {
debug: 'text-muted-foreground',
info: 'text-primary',
success: 'text-success',
@@ -19,7 +19,7 @@ const levelClass: Record<LogEntry['level'], string> = {
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<Set<LogEntry['level']>>(new Set(LEVELS));
const [enabledLevels, setEnabledLevels] = useState<Set<LogLevel>>(new Set(LEVELS));
const [confirmClear, setConfirmClear] = useState(false);
const [serverLevel, setServerLevel] = useState<LogLevel | null>(null);
const [levelBusy, setLevelBusy] = useState(false);
const endRef = useRef<HTMLDivElement | null>(null);
const viewportRef = useRef<HTMLDivElement | null>(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() {
</div>
</CardHeader>
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
<div className="flex flex-wrap items-center gap-1 px-5 pb-2">
<span className="mr-2 text-[11px] text-muted-foreground/80">视图过滤</span>
{LEVELS.map((lv) => {
const active = enabledLevels.has(lv);
return (
@@ -142,6 +164,31 @@ export function LogsPage() {
})}
</div>
<div className="flex flex-wrap items-center gap-1 px-5 pb-3">
<span className="mr-2 text-[11px] text-muted-foreground/80" title="文件落盘始终为 debug,此处仅控制控制台 / 实时流的级别">
服务端级别
</span>
{LEVELS.map((lv) => {
const active = serverLevel === lv;
return (
<button
key={lv}
type="button"
onClick={() => void changeServerLevel(lv)}
disabled={levelBusy || serverLevel === null}
className={cn(
'rounded-full border px-2.5 py-0.5 text-[11px] font-medium transition-colors cursor-pointer disabled:cursor-not-allowed disabled:opacity-50',
active
? cn('border-primary', levelClass[lv], 'bg-primary/10')
: 'border-border text-muted-foreground/70 hover:text-foreground'
)}
>
{lv.toUpperCase()}
</button>
);
})}
</div>
<CardContent className="flex min-h-0 flex-1 flex-col pt-0">
<div className="flex min-h-0 flex-1 flex-col rounded-lg border bg-muted/30">
<ScrollArea

View File

@@ -1,4 +1,4 @@
import type { HookProcessInfo, LogEntry, QQInfo, SystemInfo } from '@/types';
import type { HookProcessInfo, LogEntry, LogLevel, QQInfo, SystemInfo } from '@/types';
import type { PasswordRule } from '@/components/pages/change-password-page';
import { normalizeOneBotConfig } from '@/lib/onebot-config';
import {
@@ -84,6 +84,9 @@ class HttpApiClient implements ApiClient {
return data.list ?? [];
},
stream: (options) => 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 }),
};
}

View File

@@ -1,6 +1,7 @@
import type {
HookProcessInfo,
LogEntry,
LogLevel,
OneBotConfig,
QQInfo,
SystemInfo,
@@ -69,6 +70,10 @@ export interface ApiClient {
list(limit?: number): Promise<LogEntry[]>;
/** 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. */

View File

@@ -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;