qq-bot-roost 1.1.18 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -8,9 +8,9 @@
8
8
 
9
9
  <img src="https://img.shields.io/badge/Node.js-22.13%2B-339933?logo=node.js&logoColor=white" alt="Node.js 22.13+">
10
10
  <img src="https://img.shields.io/badge/dependencies-0-brightgreen" alt="零依赖">
11
- <img src="https://img.shields.io/badge/tests-1539%20passed-brightgreen" alt="测试 1539 项">
11
+ <img src="https://img.shields.io/badge/tests-1605%20passed-brightgreen" alt="测试 1605 项">
12
12
  <img src="https://img.shields.io/badge/plugins-JS%20%7C%20Python%20%7C%20Go%20%7C%20any-blue" alt="多语言插件">
13
- <img src="https://img.shields.io/badge/version-1.1.18-blueviolet" alt="版本 1.1.18">
13
+ <img src="https://img.shields.io/badge/version-1.2.0-blueviolet" alt="版本 1.2.0">
14
14
  <img src="https://img.shields.io/badge/license-AGPL--3.0--only-blue" alt="AGPL-3.0-only">
15
15
  <a href="https://github.com/roost-qq/qq-bot-roost/actions"><img src="https://img.shields.io/github/actions/workflow/status/roost-qq/qq-bot-roost/ci.yml?branch=master" alt="CI"></a>
16
16
 
@@ -35,6 +35,10 @@ Node 22 内置的 `WebSocket` 是客户端,服务端要 `ws`,所以只有启
35
35
  照常跑**,外接页提示「装一下就能用」。2026-11-12 确认按可选依赖走。
36
36
 
37
37
  每只鸟一个端口,默认 `6800 + sha1(botId) % 100`(OneBot 是 6700–6799,不重叠)。
38
+ Windows 打开 Hyper-V / WSL 时 6501–7100 常被整段列为系统保留端口,自动端口在
39
+ 6800–6899 全绑不上(报 `EACCES` 而不是 `EADDRINUSE`)时会退到备用段 `18300–18319`;
40
+ 面板上显式填了端口就只在那个端口附近顺延,不跨到备用段。无论哪种,实际监听端口都以
41
+ `GET /api/host` 返回的 `state.port` 为准。
38
42
 
39
43
  | 入口 | 作用 |
40
44
  |---|---|
@@ -251,9 +255,9 @@ data: {"at":1731400000000}
251
255
  | | `plugin.data.*` / `plugin.groups.*` | read ~ manage | 插件存档、按群开关 |
252
256
  | | `plugin.market` / `plugin.versions` / `plugin.updates` | read | 市场、本地版本、可更新 |
253
257
  | | `plugin.install/remove/update/update.all/rescan/load/unload/forget` | manage | 插件全生命周期 |
254
- | 扩展联动 | `ext.list` | read | 列出 DSH 已装扩展暴露的动作 |
258
+ | 扩展联动 | `ext.list` | read | 列出 DSH 已装扩展暴露的动作与命令 |
255
259
  | | `ext.call` | message | 调一个扩展动作(SSE 请求 + RPC 回执) |
256
- | | `ext.register` / `ext.call.reply` | message | DSH 上报清单 / 回传结果(内部) |
260
+ | | `ext.register` / `ext.call.reply` / `ext.command.reply` | message | DSH 上报清单 / 回传动作结果 / 回传命令结果(内部) |
257
261
  | 配置 | `config.get` | read | 脱敏后的机器人配置 |
258
262
  | | `config.set` | manage | 改运行时设置(见下) |
259
263
 
@@ -426,7 +430,9 @@ data: {"at":1731400000000}
426
430
  ## 5. 生命周期与安全
427
431
 
428
432
  - `enabled: false` 时不监听,不占端口
429
- - 缺 token / 非回环未授权 / 端口起不来 → `state = error`,**不影响机器人本体**
433
+ - 缺 token / 非回环未授权 / 端口起不来 → `state = error`,**不影响机器人本体**;
434
+ `EACCES`(系统保留端口)与 `EADDRINUSE`(被占)会给出不同的下一步提示,
435
+ 面板不再把任何错误都说成「缺依赖」
430
436
  - 面板连点保存会并发 start/stop,用串行队列挡住(OneBot 踩过端口漂移的坑)
431
437
  - 事件是**旁路推送**,本版不拦插件管线。ai-chat 中间层移除后 dsh-roost
432
438
  直连这个协议,不再有第二条回话链路;`exclusive` 语义留到后续版本
@@ -476,3 +482,71 @@ data: {"at":1731400000000}
476
482
  - DSH 侧对外同样提供 `GET /v1/roost.capabilities` 与 `POST /v1/roost.call`:
477
483
  扩展可经宿主代理调用只读能力、框架插件的 `tool.*` 与 `msg.send`,
478
484
  框架地址与令牌不出宿主,写/管理面不开放。
485
+
486
+ ## 8. 聊天命令:外接客户端也能在框架侧注册命令(1.2.0 起)
487
+
488
+ 插件想「用户在群里发一条指令就执行」,必须进框架的命令表——外接客户端
489
+ (dsh-roost 本体)和它装的扩展都在进程外,以前拿不到这条路。现在
490
+ `ext.register` 除了 `extensions[].actions`,还能上报 `commands`:
491
+
492
+ ```jsonc
493
+ {
494
+ "extensions": [{
495
+ "id": "bili",
496
+ "name": "B 站",
497
+ "actions": [{ "id": "login", "label": "扫码登录" }],
498
+ "commands": [{
499
+ "name": "bili", // 命令名,字母/数字/中文,≤16
500
+ "aliases": ["哔哩"], // 可选,≤4 个;只可直呼,不进菜单
501
+ "desc": "B 站投稿管理",
502
+ "usage": "/bili [登录|投稿]",
503
+ "admin": false, // ≥ 管理员(主人也算)
504
+ "globalAdmin": false, // 另需「全局」作用域
505
+ "ownerOnly": true // 只有主人
506
+ }]
507
+ }],
508
+ "host": { // 宿主本体;命令归内部 id ext:<name>
509
+ "name": "dsh", // 自报名:显示用,也做重名改名的前缀
510
+ "commands": [{ "name": "model", "desc": "查看/切换模型", "admin": true }]
511
+ }
512
+ }
513
+ ```
514
+
515
+ ```
516
+ 用户发 /model list
517
+ │
518
+ ├─ 框架命令表命中(内部 id ext:<自报名> / ext:<扩展id>,权限按 admin/ownerOnly 判)
519
+ │
520
+ ├─ SSE 事件 ext.command.request {requestId, target, extId, name, msg} ──► dsh-roost
521
+ │ │
522
+ │ dsh-roost 执行完 RPC ext.command.reply
523
+ ◄──────── {requestId, ok, reply?} ────────────────────────────────────┘
524
+ │
525
+ └─ reply 有正文 → 框架 msg.reply 代发(带引用、受限频与被动窗口管)
526
+ 没有正文 → 认为客户端自己发过了,框架不补话
527
+ ```
528
+
529
+ 约定:
530
+
531
+ - **重名自动加前缀**。与内核或已装插件冲突时改注册成
532
+ `<自报名第一段>-<命令名>`(`/model` → `/dsh-model`),菜单里那条的
533
+ `desc` 会写明「原名 /model,与已有命令重名」。`ext.register` 回执带
534
+ `renamed: [{from, to, plugin}]`,客户端记日志即可;改了还撞才进
535
+ `rejected: [{name, plugin, reason}]`。不冲突的命令保持原名。
536
+ - **每次上报都是整组重建**:先按伪插件 id 清掉旧命令再装新的,扩展卸载、
537
+ 改命令名、重连都不会留僵尸命令;协议停止 / 断线时整组摘掉。
538
+ - 命令跟着连接走,所以客户端没连上时这些命令根本不在表里,不会出现
539
+ 「点了没人接」。
540
+ - **命令不进 AI**:命中命令表的消息不会再推给外接协议层,模型看不到
541
+ `/help 插件` 这种指令(以前会被当成用户说的一句话,还会写进记忆);
542
+ 命令表里没有的 `/xyz` 仍按普通消息走,不会被吞。
543
+ - **它是「协议」不是「插件」**:宿主本体的命令在 `/help 协议` 单独一栏,
544
+ 栏标题用连接方自报的 `host.name`,不占 `/help 插件` 的位置。内部 id 是
545
+ `ext:<name>`(如 `ext:dsh`)与 `ext:<扩展id>`(如 `ext:bili`),只用于
546
+ 隔离与清理,不展示给用户;`ext:` 在 Windows 目录名里非法,不会和真插件撞。
547
+ - 命令一共最多 60 条(含宿主与全部扩展);单条 `reply` 正文截断到 2000 字。
548
+ - 权限只有三档且**从严到宽**判:`ownerOnly` → `admin` → `globalAdmin`,
549
+ 客户端不能靠上报参数放宽框架已有的限制。
550
+ - 老框架不认这些字段:忽略即可,命令不生效但其余联动不受影响;
551
+ 老客户端不传 `commands` 时框架行为与之前完全一致。
552
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "qq-bot-roost",
3
- "version": "1.1.18",
3
+ "version": "1.2.0",
4
4
  "type": "module",
5
5
  "description": "栖 Roost:零依赖的 QQ 官方机器人框架,填 AppID/AppSecret 即连,插件可写任意语言",
6
6
  "license": "AGPL-3.0-only",
@@ -30,9 +30,9 @@
30
30
  "mock": "node src/main.js --mock",
31
31
  "check": "node src/main.js --check",
32
32
  "release:prepare": "node scripts/release-prepare.mjs",
33
- "test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/market-hash-dual.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/message-fields.mjs && node --test test/mention-routing.mjs && node --test test/people-list.mjs && node --test test/ledger-people.mjs && node --test test/ledger-search.mjs && node --test test/ledger-text.mjs && node --test test/ledger-media.mjs && node --test test/ledger-page.mjs && node --test test/people-search.mjs && node --test test/host-ledger.mjs && node --test test/sync-beta-tag.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/transport-regressions.mjs && node --test test/check-mode.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-keep.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/inbound-forward.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/healthz-identity.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/gateway-interaction-ack.mjs && node --test test/gate-silence.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs && node --test test/url-guard.mjs && node --test test/plugin-update.mjs && node --test test/deps-mirror.mjs && node --test test/faces.mjs && node --test test/md-image.mjs && node --test test/media-time.mjs && node --test test/market-source.mjs && node --test test/hashdir-sums.mjs",
33
+ "test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/market-hash-dual.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/message-fields.mjs && node --test test/mention-routing.mjs && node --test test/people-list.mjs && node --test test/ledger-people.mjs && node --test test/ledger-search.mjs && node --test test/ledger-text.mjs && node --test test/ledger-media.mjs && node --test test/ledger-page.mjs && node --test test/people-search.mjs && node --test test/host-ledger.mjs && node --test test/sync-beta-tag.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/transport-regressions.mjs && node --test test/check-mode.mjs && node --test test/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-keep.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/inbound-forward.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/ext-commands.mjs && node --test test/web-token-echo.mjs && node --test test/healthz-identity.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/gateway-interaction-ack.mjs && node --test test/gate-silence.mjs && node --test test/config-reset.test.mjs && node --test test/auth-login.mjs && node --test test/key-strength.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs && node --test test/url-guard.mjs && node --test test/plugin-update.mjs && node --test test/deps-mirror.mjs && node --test test/faces.mjs && node --test test/md-image.mjs && node --test test/media-time.mjs && node --test test/market-source.mjs && node --test test/hashdir-sums.mjs && node --test test/bot-runtime-init.mjs",
34
34
  "test:e2e": "node test/e2e.mjs",
35
- "test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/market-hash-dual.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/message-fields.mjs && node --test test/mention-routing.mjs && node --test test/people-list.mjs && node --test test/ledger-people.mjs && node --test test/ledger-search.mjs && node --test test/ledger-text.mjs && node --test test/ledger-media.mjs && node --test test/ledger-page.mjs && node --test test/people-search.mjs && node --test test/host-ledger.mjs && node --test test/sync-beta-tag.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/transport-regressions.mjs && node --test test/check-mode.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-keep.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/inbound-forward.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/web-token-echo.mjs && node --test test/healthz-identity.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/gate-silence.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs && node --test test/url-guard.mjs && node --test test/plugin-update.mjs && node --test test/deps-mirror.mjs && node --test test/faces.mjs && node --test test/md-image.mjs && node --test test/market-source.mjs && node --test test/hashdir-sums.mjs",
35
+ "test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node test/npm-registry.mjs && node test/deps-external.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/market-cache.mjs && node --test test/market-kind.mjs && node --test test/market-hash-dual.mjs && node --test test/instance-proc.mjs && node --test test/proxy.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.mjs && node --test test/message-fields.mjs && node --test test/mention-routing.mjs && node --test test/people-list.mjs && node --test test/ledger-people.mjs && node --test test/ledger-search.mjs && node --test test/ledger-text.mjs && node --test test/ledger-media.mjs && node --test test/ledger-page.mjs && node --test test/people-search.mjs && node --test test/host-ledger.mjs && node --test test/sync-beta-tag.mjs && node --test test/identity.mjs && node --test test/identity-commands.mjs && node --test test/mail.mjs && node --test test/ledger-outbound.mjs && node --test test/api-record.mjs && node --test test/transport-regressions.mjs && node --test test/check-mode.mjs && node --test test/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs && node --test test/ext-deps-migrate.mjs && node --test test/onebot-keep.mjs && node --test test/onebot-deps.mjs && node --test test/onebot-config.mjs && node --test test/onebot-segments.mjs && node --test test/onebot-outbound-at.mjs && node --test test/onebot-translate.mjs && node --test test/onebot-voice.mjs && node --test test/onebot-loopback.mjs && node --test test/inbound-forward.mjs && node --test test/host-protocol.mjs && node --test test/host-config.mjs && node --test test/host-tool-methods.mjs && node --test test/host-ext-bridge.mjs && node --test test/ext-commands.mjs && node --test test/web-token-echo.mjs && node --test test/healthz-identity.mjs && node --test test/group-manage.mjs && node --test test/wakeup-payload.mjs && node --test test/typing.mjs && node --test test/media-convert.mjs && node --test test/gate-silence.mjs && node --test test/config-reset.test.mjs && node --test test/auth-login.mjs && node --test test/key-strength.mjs && node --test test/host-dev.mjs && node --test test/dev-browser.mjs && node --test test/dev-cooldown.mjs && node --test test/onebot-profile.mjs && node --test test/dev-remember.mjs && node --test test/dev-scope.mjs && node --test test/dev-renew.mjs && node --test test/dev-ticket.mjs && node --test test/nickname.mjs && node --test test/url-guard.mjs && node --test test/plugin-update.mjs && node --test test/deps-mirror.mjs && node --test test/faces.mjs && node --test test/md-image.mjs && node --test test/market-source.mjs && node --test test/hashdir-sums.mjs && node --test test/bot-runtime-init.mjs",
36
36
  "check:secrets": "node scripts/check-secrets.mjs",
37
37
  "create": "node scripts/create-plugin.mjs",
38
38
  "test:plugin": "node scripts/test-plugin.mjs",
@@ -54,6 +54,7 @@
54
54
  "docs",
55
55
  "config/*.example.json",
56
56
  "README.md",
57
- "LICENSE"
57
+ "LICENSE",
58
+ "start.bat"
58
59
  ]
59
60
  }
package/src/bot.js CHANGED
@@ -1,3 +1,4 @@
1
+ import path from 'node:path';
1
2
  import { createLogger, attachLogFile, detachLogFile } from './logger.js';
2
3
  import { TokenManager } from './token.js';
3
4
  import { QQApi } from './api.js';
@@ -7,6 +8,7 @@ import { PluginManager } from './plugin/loader.js';
7
8
  import { orderListeners, skipBecauseClaimed } from './plugin/dispatch.js';
8
9
  import { GroupStore } from './groups.js';
9
10
  import { RoleStore, LEVEL, NO_PERM, levelName, parseLevel, parseScope, scopeOf } from './roles.js';
11
+ import { commandDenyReason, needsPermissionCheck } from './command-perm.js';
10
12
  import { Outbound } from './outbound.js';
11
13
  import { SessionManager } from './session.js';
12
14
  import { createDefaultPipeline } from './pipeline.js';
@@ -27,6 +29,30 @@ import { onebotAllowsCore } from './onebot/keep.js';
27
29
  import { HostBridge } from './host/index.js';
28
30
  import { isOfficialDuplicate, shouldForwardInbound } from './host/inbound-forward.js';
29
31
 
32
+ /**
33
+ * 账本图片存储:**随 `cfg.ledger.saveImages` 一起开关**。
34
+ *
35
+ * 单独抽成函数,是为了让单测能直接钉住这个分支。它有段惨痛历史:这里曾经写成
36
+ * `path.join(...)` 却忘了 `import path`,而它又藏在 `saveImages === true` 后面、
37
+ * 默认配置永远走不到——于是「开了图片留档」的用户每次启动都 ReferenceError 崩在
38
+ * init 中途,默认配置的用户一切正常,测试也全绿,线上只能靠手工启动才看到堆栈。
39
+ *
40
+ * @param {object} cfg 机器人配置
41
+ * @param {string} dataDir 该机器人的数据目录(`data/bots/<id>`)
42
+ * @returns {object|null} 关着时返回 null,调用方不必再判空
43
+ */
44
+ export function createBotMediaStore(cfg, dataDir) {
45
+ if (cfg?.ledger?.saveImages !== true) return null;
46
+ return createMediaStore({
47
+ dir: path.join(dataDir, 'ledger-media'),
48
+ /**
49
+ * 上限夹在 64KB–50MB:小于 64KB 连表情都存不下,
50
+ * 大于 50MB 一张图就能把磁盘吃穿,都不该让配置里写出来。
51
+ */
52
+ maxBytes: Math.max(64, Math.min(Number(cfg.ledger?.imageMaxKb ?? 2048) || 2048, 51200)) * 1024,
53
+ });
54
+ }
55
+
30
56
  /**
31
57
  * 一个机器人的完整运行时。
32
58
  *
@@ -326,24 +352,18 @@ export class BotRuntime {
326
352
  * 账本图片存储。**随 `ledger.saveImages` 一起开关**:
327
353
  * 关着的时候连 store 都不建,`saveMedia()` 直接返回空数组,
328
354
  * 收消息路径上一个分支都不多走。
355
+ *
356
+ * **只在构造时建一次,之后唯一的数据源是 `ledger.mediaStore`**:
357
+ * 面板上的开关改的是它(`web/server.js` 的 `PUT /api/ledger/images`)。
358
+ * 这里再留一份 `this.mediaStore` 快照就是第二个真相——曾经用它做入站
359
+ * 判定,结果「面板打开留档、群里发图却没缩略图」,要重启才生效。
329
360
  */
330
- this.mediaStore = cfg.ledger?.saveImages === true
331
- ? createMediaStore({
332
- dir: path.join(this.paths.data, 'ledger-media'),
333
- /**
334
- * 上限夹在 64KB–50MB:小于 64KB 连表情都存不下,
335
- * 大于 50MB 一张图就能把磁盘吃穿,都不该让配置里写出来。
336
- */
337
- maxBytes: Math.max(64, Math.min(Number(cfg.ledger?.imageMaxKb ?? 2048) || 2048, 51200)) * 1024,
338
- })
339
- : null;
340
-
341
361
  this.ledger = createLedger({
342
362
  file: this.paths.events,
343
363
  botId: this.id,
344
364
  enabled: cfg.ledger?.enabled !== false,
345
365
  retentionDays: cfg.ledger?.retentionDays ?? 0,
346
- mediaStore: this.mediaStore,
366
+ mediaStore: createBotMediaStore(cfg, this.paths.data),
347
367
  });
348
368
 
349
369
  /**
@@ -1037,6 +1057,30 @@ export class BotRuntime {
1037
1057
  }
1038
1058
  }
1039
1059
 
1060
+ /**
1061
+ * 入站图片留档(`ledger.saveImages` 开着时才真的下载)。
1062
+ *
1063
+ * **不在这里判断开关**:开关的唯一数据源是 `ledger.mediaStore`,面板
1064
+ * 打开/关掉它立刻生效(`saveMedia()` 内部按当前 store 决定干不干活)。
1065
+ * 过去这里读的是构造期快照,于是「面板打开留档、群里发图却没缩略图」,
1066
+ * 而同样是留档的出站发图却立刻有——同一个开关两种表现。
1067
+ *
1068
+ * **调用方不要 await**:一张图几 MB,下载几秒,串在分发链路上会让整个群
1069
+ * 等她。`saveMedia()` 内部逐个下载、失败跳过,存完自己回填 `media` 列;
1070
+ * 这期间面板看到的是「这条没有图」,一秒后刷新就有了。
1071
+ *
1072
+ * @param {{id:string}} rec `append()` 的返回值
1073
+ * @param {object} msg 入站消息(只要有 `attachments`)
1074
+ * @returns {Promise<Array<object>>} 存下来的条目;没图 / 没开工时是空数组
1075
+ */
1076
+ saveInboundMedia(rec, msg) {
1077
+ const imgs = (Array.isArray(msg?.attachments) ? msg.attachments : [])
1078
+ .filter((a) => a?.type === 'image' && a?.url)
1079
+ .map((a) => ({ url: a.url, ct: a.contentType, w: a.width, h: a.height }));
1080
+ if (!imgs.length || !rec) return Promise.resolve([]);
1081
+ return this.ledger.saveMedia(rec, imgs).catch(() => []);
1082
+ }
1083
+
1040
1084
  /**
1041
1085
  * 这个方法和单机器人时的逻辑一致,只是绑到了某个实例上。
1042
1086
  * 所有事件都会转交给插件,未知事件也不例外。
@@ -1176,20 +1220,7 @@ export class BotRuntime {
1176
1220
  if (rec) {
1177
1221
  msg.eventId = rec.id;
1178
1222
  msg.eventSeq = rec.seq;
1179
- /**
1180
- * 图片留档(`ledger.saveImages` 开启时才有 store)。
1181
- *
1182
- * **一定不能 await**:一张图几 MB,下载几秒,串在这里会让整个群的
1183
- * 消息分发跟着等。`saveMedia` 内部逐个下载、失败跳过,
1184
- * 存完自己回填 `media` 列;这期间面板看到的是「这条没有图」,
1185
- * 一秒后再刷新就有了。
1186
- */
1187
- if (this.mediaStore) {
1188
- const imgs = (Array.isArray(msg.attachments) ? msg.attachments : [])
1189
- .filter((a) => a?.type === 'image' && a?.url)
1190
- .map((a) => ({ url: a.url, ct: a.contentType, w: a.width, h: a.height }));
1191
- if (imgs.length) this.ledger.saveMedia(rec, imgs).catch(() => {});
1192
- }
1223
+ this.saveInboundMedia(rec, msg);
1193
1224
  }
1194
1225
 
1195
1226
  // 收到私聊 = 好友关系存在的强证据。不置 c2cPush:他能发不等于他允许机器人主动推
@@ -1247,6 +1278,12 @@ export class BotRuntime {
1247
1278
  silent: msg.silent,
1248
1279
  forwardSilent,
1249
1280
  duplicate,
1281
+ /**
1282
+ * 命中命令表的命令由框架自己处理,别再交给协议层:
1283
+ * 否则 dsh-roost 会把「/help 插件」当成用户说的一句话喂给模型。
1284
+ * 只认命令表里有的名字,`/xyz` 这类未知命令仍按普通消息走。
1285
+ */
1286
+ isCommand: Boolean(msg.isCommand && registry.commands.has(msg.command)),
1250
1287
  })) {
1251
1288
  this.onebot?.onMessage(msg);
1252
1289
  /** 宿主协议:传完整 msg(原生结构),它自己挑字段 */
@@ -1375,24 +1412,19 @@ export class BotRuntime {
1375
1412
  return;
1376
1413
  }
1377
1414
  const scope = scopeOf(msg);
1378
- if (commandEntry.admin || commandEntry.globalAdmin) {
1415
+ if (needsPermissionCheck(commandEntry)) {
1379
1416
  const lv = await roles.effective(scope, msg.userId, { owners: cfg.owners });
1380
- if (commandEntry.admin && lv > LEVEL.admin) {
1381
- return msg
1382
- .reply(
1383
- `需要管理员权限才能用这个命令(你当前是${levelName(lv)})。\n` +
1384
- `发 ${cfg.commandPrefix || '/'}admin me 查看自己的权限。`,
1385
- )
1386
- .catch(() => {});
1387
- }
1388
- if (commandEntry.globalAdmin) {
1389
- const gl = cfg.owners.includes(msg.userId)
1417
+ /**
1418
+ * 全局等级只在 globalAdmin 命令上才查:它要多一次 IO,
1419
+ * 而绝大多数命令只看本群等级。
1420
+ */
1421
+ const globalLv = commandEntry.globalAdmin
1422
+ ? cfg.owners.includes(msg.userId)
1390
1423
  ? LEVEL.owner
1391
- : await roles.levelIn('global', msg.userId);
1392
- if (gl > LEVEL.admin) {
1393
- return msg.reply('这个命令影响全局,需要「全局管理员」权限。').catch(() => {});
1394
- }
1395
- }
1424
+ : await roles.levelIn('global', msg.userId)
1425
+ : null;
1426
+ const deny = commandDenyReason(commandEntry, { lv, globalLv, prefix: cfg.commandPrefix || '/' });
1427
+ if (deny) return msg.reply(deny).catch(() => {});
1396
1428
  }
1397
1429
  const required = (commandEntry.pattern?.match(/<[^>]+>/g) ?? []).length;
1398
1430
  if (msg.args.length < required) {
@@ -1690,7 +1722,14 @@ function groupProfileOf(info) {
1690
1722
  * @returns {boolean}
1691
1723
  */
1692
1724
  export function pluginAllowedIn(spec, chatId, pluginId) {
1693
- if (!pluginId || pluginId === '__core') return true;
1725
+ /**
1726
+ * 内核 `__core`、以及外接协议连接方(`ext:dsh`、`ext:<扩展id>`)都要放行。
1727
+ *
1728
+ * 前者放行是因为群里没了 `/help` 用户就没法自救;后者是命令**跟着连接走**的,
1729
+ * 客户端没连上时根本不在命令表里,再用分群插件开关判一次只会让人以为命令失灵。
1730
+ * 它们也不在插件面板的启用列表里,`/disable` 拿不到它们。
1731
+ */
1732
+ if (!pluginId || pluginId === '__core' || pluginId.startsWith('ext:')) return true;
1694
1733
  const own = spec?.groups?.[chatId];
1695
1734
  if (!own) return true; // 这个会话没单独配,跟着全局
1696
1735
  const mode = own.mode ?? 'include';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * 命令权限判定
3
+ * ============
4
+ *
5
+ * 从 `bot.js` 里抽出来的纯函数:那里是消息流水线,构造一次 Bot 要拉 API、
6
+ * 插件、账号一堆东西,测一条权限规则不值当。判定逻辑单独放这儿,改规则
7
+ * 只改一处,测试也只跑一个文件。
8
+ *
9
+ * 三档,从严到宽:
10
+ * ownerOnly 只有主人(`LEVEL.owner`)
11
+ * admin ≥ 管理员(主人也算)
12
+ * globalAdmin 另需「全局」作用域权限(群管理员不算)
13
+ *
14
+ * 为什么 ownerOnly 必须是最先判:一个命令同时声明 ownerOnly + admin 时,
15
+ * 语义应该是「只有主人」,不能被 admin 那一档放宽成「管理员也行」。
16
+ */
17
+
18
+ import { LEVEL, levelName } from './roles.js';
19
+
20
+ /**
21
+ * 判断某身份能否用这条命令。
22
+ *
23
+ * @param {object} entry 命令表条目(读 ownerOnly / admin / globalAdmin)
24
+ * @param {object} who
25
+ * @param {number} who.lv 当前作用域有效等级(越小越高)
26
+ * @param {number|null} [who.globalLv] 全局作用域等级;只有 globalAdmin 命令才会被查
27
+ * @param {string} [who.prefix] 命令前缀,用于提示文案
28
+ * @returns {string} 拒绝理由;空串表示放行
29
+ */
30
+ export function commandDenyReason(entry, { lv, globalLv = null, prefix = '/' } = {}) {
31
+ if (entry?.ownerOnly && lv > LEVEL.owner) return '这个命令只有机器人主人能用。';
32
+ if (entry?.admin && lv > LEVEL.admin) {
33
+ return (
34
+ `需要管理员权限才能用这个命令(你当前是${levelName(lv)})。\n` +
35
+ `发 ${prefix}admin me 查看自己的权限。`
36
+ );
37
+ }
38
+ if (entry?.globalAdmin && globalLv !== null && globalLv > LEVEL.admin) {
39
+ return '这个命令影响全局,需要「全局管理员」权限。';
40
+ }
41
+ return '';
42
+ }
43
+
44
+ /** 这条命令是否需要查权限(不用查就别白跑一次 roles.effective) */
45
+ export function needsPermissionCheck(entry) {
46
+ return Boolean(entry?.ownerOnly || entry?.admin || entry?.globalAdmin);
47
+ }
@@ -0,0 +1,186 @@
1
+ /**
2
+ * 恢复框架默认设置(**只动设置,不动数据**)
3
+ * ==========================================
4
+ *
5
+ * 给 dsh-roost 面板的「问题反馈 → 恢复默认设置」调用。为什么不直接让插件
6
+ * 改配置文件:框架是有自己内存的进程,`config/bot.json` 改了以后要由
7
+ * `services/config-watch.js` 热加载;绕开框架写文件等于让两个进程抢同一份
8
+ * 状态(面板刚保存的值会被另一头覆盖)。所以正路是框架自己提供接口。
9
+ *
10
+ * 「恢复默认」不是「把所有键 PUT 一遍」:`/api/config` 是合并语义,插件升级
11
+ * 遗留的旧键会永远留在文件里。这里按 `GLOBAL_DEFAULTS` / `BOT_DEFAULTS`
12
+ * **删了重建**,才真的干净。
13
+ *
14
+ * 必须保留的东西(否则恢复完当场失联 / 丢凭证):
15
+ * - 全局:`webui.accessKey`(面板密钥,dsh-roost 调框架 API 也靠它)、
16
+ * `webui.loginPassword`(人登录面板的密码,与 accessKey 是两把钥匙)、
17
+ * `webui.host` / `webui.port`(运行中的进程不会因改端口重新 bind)、
18
+ * `network.giteeToken`(Gitee 镜像令牌)、`notifications.smtp`(整段 SMTP 配置:
19
+ * `checkConfig()` 要求 host / port / from 齐全,`user` + `pass` 才组成认证,
20
+ * 只保 pass 等于留半套——重新填一遍不比重新申请授权码容易)。
21
+ * - 每只鸟:`appId` / `appSecret`(QQ 凭证)、`owners`(主人,绑定要真机扫码)、
22
+ * `onebot.token` / `host.token`(两个协议端口各自的对端令牌)。
23
+ *
24
+ * 「恢复默认设置」只对**配置项**生效:令牌 / 授权码是用户去别处申请才拿得到的,
25
+ * 重置一次就清空等于逼人重配一遍,而且返回文案还写着「凭证保留」,属于欺骗。
26
+ * 这些键一概要保住;`enabled` / `host` / `port` 这类开关仍回默认,用户按需要重开。
27
+ *
28
+ * 全部是纯函数 + 可注入 IO,测试不需要碰真实配置目录。
29
+ */
30
+ import { readFileSync } from 'node:fs';
31
+ import { join } from 'node:path';
32
+
33
+ import { GLOBAL_DEFAULTS, BOT_DEFAULTS, saveGlobalConfig, saveBotConfig } from './config.js';
34
+ import { DIRS, PATHS, listBotIds } from './paths.js';
35
+
36
+ /** 前端必须带这个确认词;误点 / 老脚本裸调一律拒绝 */
37
+ export const RESET_CONFIRM = 'RESET';
38
+
39
+ /**
40
+ * 全局保留路径:连接引导 + 凭证 + 用户自己配的 SMTP 通道。
41
+ *
42
+ * SMTP 按**字段白名单**保留而不是整段复制:`checkConfig()` 要求 host / port / from
43
+ * 齐全,认证还要 user + pass,少一个就发不出信;但 enabled(恢复默认后不该偷偷
44
+ * 继续发邮件)与 timeoutMs / dailyLimit 这类高级限频属于「设置」,必须回默认。
45
+ * 逐字段搬还能顺手淘汰旧版遗留键(如 smtpPass / password)——整段复制会把它们
46
+ * 原样带回来,违背「删了重建才干净」的初衷。
47
+ */
48
+ export const GLOBAL_KEEP_PATHS = [
49
+ ['webui', 'accessKey'],
50
+ ['webui', 'loginPassword'],
51
+ ['webui', 'host'],
52
+ ['webui', 'port'],
53
+ ['network', 'giteeToken'],
54
+ ['notifications', 'smtp', 'host'],
55
+ ['notifications', 'smtp', 'port'],
56
+ ['notifications', 'smtp', 'security'],
57
+ ['notifications', 'smtp', 'user'],
58
+ ['notifications', 'smtp', 'pass'],
59
+ ['notifications', 'smtp', 'from'],
60
+ ['notifications', 'smtp', 'fromName'],
61
+ ['notifications', 'smtp', 'ownerEmail'],
62
+ ];
63
+
64
+ /** 每只鸟保留路径:凭证 / 主人 / 协议令牌;它们的 enabled、host、port 仍回默认 */
65
+ export const BOT_KEEP_PATHS = [
66
+ ['appId'],
67
+ ['appSecret'],
68
+ ['owners'],
69
+ ['onebot', 'token'],
70
+ ['host', 'token'],
71
+ ];
72
+
73
+ /**
74
+ * 兼容旧名:老调用方传的是单层 key 列表,语义仍是「只保这三个顶层键」。
75
+ * 不能从 BOT_KEEP_PATHS 派生——那样会把 `onebot` / `host` 整个对象(含开关与端口)
76
+ * 一起保留,和「只保令牌」的目标相反。
77
+ */
78
+ export const BOT_KEEP_KEYS = ['appId', 'appSecret', 'owners'];
79
+
80
+ function getAt(root, path) {
81
+ return path.reduce((v, k) => (v && typeof v === 'object' ? v[k] : undefined), root);
82
+ }
83
+
84
+ function setAt(root, path, value) {
85
+ let node = root;
86
+ for (const k of path.slice(0, -1)) {
87
+ if (!node[k] || typeof node[k] !== 'object' || Array.isArray(node[k])) node[k] = {};
88
+ node = node[k];
89
+ }
90
+ node[path.at(-1)] = value;
91
+ }
92
+
93
+ /**
94
+ * 重置全局配置:以默认值重建,只把保留路径的值搬回来。
95
+ * `structuredClone` 是必须的——`BOT_DEFAULTS` / `GLOBAL_DEFAULTS` 里的嵌套对象
96
+ * 是共享引用,直接改会污染后续所有机器人(框架里踩过一次)。
97
+ */
98
+ export function resetGlobalKeeping(current = {}, keep = GLOBAL_KEEP_PATHS) {
99
+ const next = structuredClone(GLOBAL_DEFAULTS);
100
+ for (const p of keep) {
101
+ const v = getAt(current, p);
102
+ if (v !== undefined) setAt(next, p, structuredClone(v));
103
+ }
104
+ /** 老配置用过 `webui.token`,兼容搬过来,别让恢复默认变成「密钥消失」 */
105
+ if (!next.webui?.accessKey && current?.webui?.token) next.webui.accessKey = current.webui.token;
106
+ return next;
107
+ }
108
+
109
+ /** 默认参数写成路径数组;兼容老调用方传进来的单层 key 列表(字符串) */
110
+ const asPath = (k) => (Array.isArray(k) ? k : [k]);
111
+
112
+ /** 重置单只鸟:保留凭证 / 主人 / 协议令牌,其余回到 BOT_DEFAULTS */
113
+ export function resetBotKeeping(current = {}, id = '', keep = BOT_KEEP_PATHS) {
114
+ const next = structuredClone(BOT_DEFAULTS);
115
+ next.id = String(id || '');
116
+ for (const item of keep) {
117
+ const p = asPath(item);
118
+ const v = getAt(current, p);
119
+ if (v !== undefined) setAt(next, p, structuredClone(v));
120
+ }
121
+ if (!next.name) next.name = next.id;
122
+ return next;
123
+ }
124
+
125
+ /** 读 JSON 失败当空对象:坏配置不该让整个恢复动作失败 */
126
+ function readJsonSafe(file) {
127
+ try {
128
+ const v = JSON.parse(readFileSync(file, 'utf8'));
129
+ return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
130
+ } catch {
131
+ return {};
132
+ }
133
+ }
134
+
135
+ /** 默认 IO:抽出来是为了单测能喂假读写,不碰开发机上的真配置 */
136
+ const defaultIo = {
137
+ readGlobal: () => readJsonSafe(PATHS.globalConfig),
138
+ readBot: (id) => readJsonSafe(join(DIRS.botsConfig, `${id}.json`)),
139
+ saveGlobal: (cfg) => saveGlobalConfig(cfg),
140
+ saveBot: (id, cfg) => saveBotConfig(id, cfg),
141
+ listBots: () => listBotIds(),
142
+ };
143
+
144
+ /**
145
+ * 执行恢复。逐只鸟独立处理:某一只配置坏了不能挡住其它鸟恢复。
146
+ * @returns {{ok:boolean, reason?:string, bots:string[], errors:string[], message:string}}
147
+ */
148
+ export async function resetFrameworkConfigs({ confirm, io = defaultIo } = {}) {
149
+ if (confirm !== RESET_CONFIRM) {
150
+ return { ok: false, reason: 'confirm', bots: [], errors: [], message: '需要确认词 RESET' };
151
+ }
152
+
153
+ const errors = [];
154
+ const bots = [];
155
+ let ids = [];
156
+ try {
157
+ ids = await io.listBots();
158
+ } catch (e) {
159
+ errors.push(`列机器人失败:${e?.message || e}`);
160
+ }
161
+
162
+ for (const id of ids) {
163
+ try {
164
+ await io.saveBot(id, resetBotKeeping(await io.readBot(id), id));
165
+ bots.push(id);
166
+ } catch (e) {
167
+ errors.push(`${id}:${e?.message || e}`);
168
+ }
169
+ }
170
+
171
+ try {
172
+ await io.saveGlobal(resetGlobalKeeping(await io.readGlobal()));
173
+ } catch (e) {
174
+ errors.push(`全局配置:${e?.message || e}`);
175
+ }
176
+
177
+ const ok = errors.length === 0;
178
+ return {
179
+ ok,
180
+ bots,
181
+ errors,
182
+ message: ok
183
+ ? `已恢复 ${bots.length} 只鸟 + 全局设置的默认值;QQ 凭证、主人、面板密钥与 Gitee / SMTP / 外接协议令牌均已保留(协议开关回到关闭,需要时请重新打开)`
184
+ : `部分恢复失败:${errors.join(';')}`,
185
+ };
186
+ }
package/src/config.js CHANGED
@@ -17,7 +17,7 @@ export const CONFIG_PATH = PATHS.globalConfig;
17
17
  /* ------------------------------------------------------------------ */
18
18
 
19
19
  /** 全局配置:管进程本身(面板、日志、插件依赖策略) */
20
- const GLOBAL_DEFAULTS = {
20
+ export const GLOBAL_DEFAULTS = {
21
21
  logLevel: 'info',
22
22
  cooldownHint: true,
23
23
 
@@ -26,6 +26,12 @@ const GLOBAL_DEFAULTS = {
26
26
  host: '127.0.0.1',
27
27
  port: 15207,
28
28
  accessKey: '',
29
+ /**
30
+ * 给人登录面板用的密码(2026-11-28)。与 accessKey 分开:
31
+ * accessKey 给机器(dsh-roost / 脚本),loginPassword 给人在登录页输,
32
+ * 门槛 8+。留空时登录页退回 accessKey,老用户升级不断档。
33
+ */
34
+ loginPassword: '',
29
35
  portTries: 20,
30
36
  openBrowser: true,
31
37
  /**
@@ -249,7 +255,7 @@ const GLOBAL_DEFAULTS = {
249
255
  };
250
256
 
251
257
  /** 机器人配置:管连接与行为,每个机器人一份 */
252
- const BOT_DEFAULTS = {
258
+ export const BOT_DEFAULTS = {
253
259
  name: '',
254
260
  enabled: true,
255
261