qq-bot-roost 1.0.10 → 1.0.12

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,10 +8,10 @@
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-826%20passed-brightgreen" alt="测试 826 项">
11
+ <img src="https://img.shields.io/badge/tests-902%20passed-brightgreen" alt="测试 902 项">
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.0.10-blueviolet" alt="版本 1.0.10">
14
- <img src="https://img.shields.io/badge/license-Non--Commercial-red" alt="禁止商用">
13
+ <img src="https://img.shields.io/badge/version-1.0.12-blueviolet" alt="版本 1.0.12">
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/tdcq9594/qq-bot-roost/actions"><img src="https://img.shields.io/github/actions/workflow/status/tdcq9594/qq-bot-roost/ci.yml?branch=master" alt="CI"></a>
16
16
 
17
17
  [快速开始](#3-分钟跑起来) | [写插件](docs/插件开发规范.md) | [外部插件协议](docs/插件协议.md) | [配置参考](docs/配置参考.md) | [常见问题](docs/常见问题.md) | [贡献](CONTRIBUTING.md)
@@ -69,6 +69,7 @@
69
69
  - **流式回复**:`msg.replyStream()` 做 AI 打字机效果,自动维护分片序号;群聊自动降级成普通消息
70
70
  - **模板消息**:`msg.replyCard()` 一次带上 markdown 正文 + 按钮 + ark 模板,不会拆成三条碎片
71
71
  - **图文卡片**:`msg.replyTuwen({title, description, url, picUrl})` 发官方 2026-10-28 新增的 `msg_type=8` 卡片,字段长度和 https 在发之前就校验
72
+ - **通用图文自动出口**:`msg.replyAuto()` 面向**所有插件**——正文写标准 `![alt](路径)`,框架按内容自动选纯文本 / markdown / 富媒体;只有图片夹在两段文字中间时才按需预上传素材,且发完即删,上传不了自动降级成「文本 + 独立图」。支持 `keyboard`(纯文字带按钮会升成 markdown,不多发一条);框架**不校验图片路径**,调用方是可信的插件代码
72
73
  - **素材缓存**:同一个图片 url 两天内只上传一次,省富媒体频控和流量
73
74
  - **中间件管道**:去重、白名单、限流、命令冷却都可插拔
74
75
 
@@ -391,6 +392,7 @@ export default {
391
392
  | `ctx.tools()` / `ctx.callTool(名, 参数)` | 列出 / 调用别插件注册的工具 |
392
393
  | `ctx.mail.send(收件人, 内容)` / `ctx.mail.configured` | **邮件通知**:收件人填完整邮箱(任意服务商)或 QQ 号;SMTP 在面板「通知」页配,见[插件开发规范](docs/插件开发规范.md) |
393
394
  | `msg.reply` / `push` / `replyMarkdown` / `replyImage` / … | 各种发送方式 |
395
+ | `msg.replyAuto(正文, opts)` | **通用图文自动出口**(所有插件可用):按正文形态自动选出口,图片夹在文字中间时按需预上传,可带 `keyboard`;见[插件开发规范](docs/插件开发规范.md) |
394
396
 
395
397
  ---
396
398
 
@@ -424,7 +426,7 @@ bot/
424
426
  │ ├── paths.js 全项目路径的唯一来源(按机器人参数化)
425
427
  │ ├── config.js 全局配置 + 机器人配置 + 迁移
426
428
  │ ├── events.js 47 个官方事件的登记表
427
- │ ├── endpoints.js 47 个官方 HTTP 接口清单(测试校验覆盖率)
429
+ │ ├── endpoints.js 50 个官方 HTTP 接口清单(测试校验覆盖率)
428
430
  │ ├── outbound.js 出站调度器:窗口 / 限速 / 额度 / 降级
429
431
  │ ├── pipeline.js 中间件管道
430
432
  │ ├── session.js 多轮对话 + 免@粘性
@@ -601,31 +603,22 @@ mock 模式下:直接输入文本 = 模拟一条群 @ 消息;`!as <openid>`
601
603
 
602
604
  ## 许可
603
605
 
604
- **永久免费,禁止任何收费,禁止商业使用。** 完整条款见 [LICENSE](LICENSE)。
606
+ 本项目采用 **GNU Affero General Public License v3.0 only(AGPL-3.0-only)**,是 OSI 认证的开源许可证。完整条款见 [LICENSE](LICENSE)。
605
607
 
606
608
  | 场景 | 允许? |
607
609
  |------|--------|
608
- | 个人使用、学习、研究 | ✅ 随便用、随便改 |
609
- | 非营利项目、公益用途 | ✅ 可以 |
610
- | 学校、慈善组织、政府机构使用 | ✅ 可以 |
611
- | 自己改了再免费分享出去 | ✅ 可以,但须沿用同一许可并保留声明 |
612
- | 卖这个软件,或收下载费 / 授权费 / 会员费 | ❌ 禁止 |
613
- | 以「技术支持 / 培训 / 定制」名义收费 | ❌ 禁止 |
614
- | 拿它做收费服务、集成进商业产品 | ❌ 禁止 |
615
- | 设置「先打赏才能用」之类的门槛 | ❌ 禁止 |
616
-
617
- 三点要说明白:
618
-
619
- 1. **任何人不得就本软件收费**,包括二次分发者。这个项目也不提供任何商业授权——
620
- 不存在「付钱就能商用」的途径。如果有人声称代表本项目出售授权,那不是我们。
621
- 2. 严格说这**不属于 OSI 定义的开源**(开源许可证不允许限制使用领域),
622
- 准确说法是「源码公开、免费使用(source-available)」。
623
- 3. 协议结构参考了 [PolyForm Noncommercial 1.0.0](https://polyformproject.org/licenses/noncommercial/1.0.0),
624
- 并按「禁止任何收费」做了加严——所以不能直接叫 PolyForm,是一份自写协议。
625
-
626
- 自愿捐赠可以接受,但**不能**把任何付费行为设成使用前提。
627
-
628
- 一句话:**自己用、改了再免费分享都可以;任何形式的收费和商业使用都不行。**
610
+ | 个人使用、学习、研究、修改 | ✅ |
611
+ | 商业使用、收费分发、集成进商业产品 | ✅ 允许,但受下列条件约束 |
612
+ | 分发源码或二进制给他人 | ✅ 必须同样以 AGPL-3.0-only 授权、保留声明并提供完整对应源码 |
613
+ | 修改后通过网络向用户提供服务 | ✅ 视为分发,须向使用者提供对应源码(AGPL 第 13 条) |
614
+ | 改用更宽松许可、闭源再分发 | ❌ 不允许 |
615
+
616
+ 两点要说明白:
617
+
618
+ 1. **AGPL 不禁止商业使用,也不禁止收费**。它约束的是「不能把基于本项目的修改版闭源」:只要分发(含通过网络提供服务),就必须同样开源并给出对应源码。
619
+ 2. 选 AGPL 而不是普通 GPL,正是为了覆盖「拿去搭托管服务、用户只通过网页或接口使用」这种情形——GPL 只在分发二进制时触发源码义务,AGPL 把网络交互也算作分发。
620
+
621
+ > 仓库里的第三方投稿插件可能保留各自许可,见对应目录的 README。
629
622
 
630
623
  ---
631
624
 
package/package.json CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "qq-bot-roost",
3
- "version": "1.0.10",
3
+ "version": "1.0.12",
4
4
  "type": "module",
5
5
  "description": "栖 Roost:零依赖的 QQ 官方机器人框架,填 AppID/AppSecret 即连,插件可写任意语言",
6
- "license": "SEE LICENSE IN LICENSE",
6
+ "license": "AGPL-3.0-only",
7
7
  "repository": {
8
8
  "type": "git",
9
9
  "url": "git+https://github.com/tdcq9594/qq-bot-roost.git"
@@ -29,9 +29,9 @@
29
29
  "start": "node src/main.js",
30
30
  "mock": "node src/main.js --mock",
31
31
  "check": "node src/main.js --check",
32
- "test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.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",
32
+ "test": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.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/reply-auto.mjs && node --test test/plugin-observability.mjs && node --test test/outbound-dry.mjs",
33
33
  "test:e2e": "node test/e2e.mjs",
34
- "test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.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/e2e.mjs && node test/live-driver.mjs",
34
+ "test:all": "node test/selftest.mjs && node test/qrlogin.mjs && node test/deps.mjs && node --test test/trust.mjs && node --test test/manifest.mjs && node --test test/trace.mjs && node --test test/fuzz-tar.mjs && node --test test/group-name.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/reply-auto.mjs && node test/e2e.mjs && node test/live-driver.mjs",
35
35
  "check:secrets": "node scripts/check-secrets.mjs",
36
36
  "create": "node scripts/create-plugin.mjs",
37
37
  "test:plugin": "node scripts/test-plugin.mjs",
package/src/api.js CHANGED
@@ -1,9 +1,14 @@
1
1
  import crypto from 'node:crypto';
2
2
  import fs from 'node:fs/promises';
3
+ import path from 'node:path';
3
4
  import { createLogger } from './logger.js';
5
+ import { DIRS } from './paths.js';
4
6
  /** 路径里的 id 一律编码:openid / 群号是外部数据,含 / 会拼出别的路径 */
5
7
  const enc = (v) => encodeURIComponent(String(v ?? ''));
6
8
 
9
+ /** 本进程创建、尚未删除的 Markdown 素材 id(崩溃后靠它认领孤儿) */
10
+ const OWN_MEDIA_FILE = path.join(DIRS.data, 'media-images-own.json');
11
+
7
12
 
8
13
  const log = createLogger('api');
9
14
 
@@ -39,6 +44,56 @@ export const MEDIA_HARD_LIMIT = 200 * 1024 * 1024;
39
44
  */
40
45
  export const DIRECT_UPLOAD_LIMIT = 5 * 1024 * 1024;
41
46
 
47
+ /**
48
+ * Markdown 素材图床(`/v2/media-images`,机器人级)的单图上限。
49
+ * 跟 `/files` 那套完全无关:那边图片软限 20MB、直传 5MB、分片 200MB。
50
+ */
51
+ export const MEDIA_IMAGE_MAX = 10 * 1024 * 1024;
52
+
53
+ /** 官方只认这四种图片 MIME,且文件名扩展名必须与之一致 */
54
+ export const IMAGE_CONTENT_TYPES = Object.freeze({
55
+ '.png': 'image/png',
56
+ '.jpg': 'image/jpeg',
57
+ '.jpeg': 'image/jpeg',
58
+ '.gif': 'image/gif',
59
+ '.webp': 'image/webp',
60
+ });
61
+
62
+ /**
63
+ * 上传前的本地预检:只看文件头 + 扩展名,**不发任何网络请求**。
64
+ *
65
+ * 官方注意事项写明「服务端只校验文件名扩展名与 content_type 是否匹配,
66
+ * 不校验文件实际内容」,坏图会一路成功到发消息才失败。这里提前挡掉,
67
+ * 也顺手满足「扩展名与 content_type 一致」的 40035001 约束。
68
+ *
69
+ * @param {Buffer} head 文件前 12+ 字节
70
+ * @param {string} fileName 含扩展名的文件名
71
+ */
72
+ export function inspectImageFormat(head, fileName) {
73
+ const b = Buffer.isBuffer(head) ? head : Buffer.from(head ?? '');
74
+ const ext = path.extname(String(fileName ?? '')).toLowerCase();
75
+ const want = IMAGE_CONTENT_TYPES[ext];
76
+ if (!want) return { ok: false, reason: 'bad_format', detail: `扩展名 ${ext || '(无)'} 不在 png/jpeg/gif/webp 白名单` };
77
+ let actual = '';
78
+ if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) actual = 'image/png';
79
+ else if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) actual = 'image/jpeg';
80
+ else if (b.length >= 4 && b.toString('ascii', 0, 4) === 'GIF8') actual = 'image/gif';
81
+ else if (b.length >= 12 && b.toString('ascii', 0, 4) === 'RIFF' && b.toString('ascii', 8, 12) === 'WEBP') actual = 'image/webp';
82
+ else return { ok: false, reason: 'bad_format', detail: '文件头不是受支持的图片格式' };
83
+ if (actual !== want) return { ok: false, reason: 'bad_format', detail: `扩展名 ${ext} 与实际格式 ${actual} 不符` };
84
+ return { ok: true, contentType: want };
85
+ }
86
+
87
+ /**
88
+ * COS 的 ETag 即文件 MD5,可能带引号或弱校验前缀。
89
+ * 拿不到合法值时回退到本地算出的整文件 md5,complete 时服务端还会
90
+ * 与 COS 对象实际 ETag 比对,不一致返 40035003。
91
+ */
92
+ export function etagToMd5(etag, fallback = '') {
93
+ const v = String(etag ?? '').replace(/^W\//i, '').replace(/^"|"$/g, '').toLowerCase();
94
+ return /^[0-9a-f]{32}$/.test(v) ? v : fallback;
95
+ }
96
+
42
97
  /**
43
98
  * `md5_10m` 取的字节数:官方写死 10002432(约 9.54MB),不是整数 MB。
44
99
  * 这个值用于「秒传判断」,传错了服务端不会报错、只是秒传不生效。
@@ -160,6 +215,16 @@ export class QQApi {
160
215
  * 换个群必须重新传,不能跨目标复用。
161
216
  */
162
217
  this.mediaCache = new Map();
218
+ /**
219
+ * Markdown 素材图床里**本进程自己上传**的 image_id。
220
+ *
221
+ * 素材库是机器人级共享的,删除时只认这个集合里的 id,避免误删其它插件的素材;
222
+ * 也不给「传个 force 就能删别人素材」的后门。发完即删,正常情况集合是空的。
223
+ * 这三个端点已标 `internal:true`,不再进 `/api/qq/call` 白名单。
224
+ */
225
+ this._ownMediaImages = new Set();
226
+ /** 孤儿素材认领,一个进程只做一次 */
227
+ this._mediaReclaimDone = false;
163
228
  }
164
229
 
165
230
  async #request(method, path, body, { retried = false, headers } = {}) {
@@ -402,14 +467,21 @@ export class QQApi {
402
467
  * @param {string} presignedUrl 预签名上传地址
403
468
  * @param {Buffer} buf 分片二进制
404
469
  * @param {number} [timeoutMs]
470
+ * @param {string} [contentType] 仅 Markdown 素材上传需要:必须与 prepare 声明的
471
+ * content_type 完全一致,否则 COS 返 403。
472
+ * 分片上传**不传**,保持原来的裸 PUT 请求头不变。
473
+ * @returns {Promise<string>} 响应头 ETag(分片调用方忽略)
405
474
  */
406
- async #putPart(presignedUrl, buf, timeoutMs = 60_000) {
475
+ async #putPart(presignedUrl, buf, timeoutMs = 60_000, contentType = '') {
407
476
  let res;
408
477
  try {
409
478
  res = await fetch(presignedUrl, {
410
479
  method: 'PUT',
411
480
  signal: AbortSignal.timeout(timeoutMs),
412
- headers: { 'Content-Length': String(buf.length) },
481
+ headers: {
482
+ 'Content-Length': String(buf.length),
483
+ ...(contentType ? { 'Content-Type': contentType } : {}),
484
+ },
413
485
  body: buf,
414
486
  });
415
487
  } catch (e) {
@@ -420,6 +492,7 @@ export class QQApi {
420
492
  const detail = await res.text().catch(() => '');
421
493
  throw new Error(`分片 PUT 失败 HTTP ${res.status}${detail ? `:${detail.slice(0, 200)}` : ''}`);
422
494
  }
495
+ return res.headers?.get('etag') ?? '';
423
496
  }
424
497
 
425
498
  /**
@@ -585,6 +658,204 @@ export class QQApi {
585
658
  return scene === 'group' ? this.sendGroup(target, opts) : this.sendC2C(target, opts);
586
659
  }
587
660
 
661
+ /* ---------------- Markdown 素材图床(机器人级) ---------------- */
662
+
663
+ /**
664
+ * 与 `/v2/{groups,users}/{openid}/files` 是**两套体系**:
665
+ * 那边返回绑定会话的 `file_info`,只能喂 `msg_type=7` 的 `media`;
666
+ * 这边返回 `qqbot-media://` 引用,绑定机器人、跨群跨单聊可复用,
667
+ * 是 Markdown(`msg_type=2`)里插本地图的唯一方式。
668
+ *
669
+ * 官方流程:prepare → 裸 PUT 到预签名 URL → complete → 引用 → 删除。
670
+ * 本框架的策略是「自产自销、发完即删」:不建持久化缓存、不做 LRU 淘汰、
671
+ * 不列全量素材,配额常驻接近 0,代价是同一张图每次重传。
672
+ */
673
+
674
+ /**
675
+ * 把「本进程已创建、但还没删掉」的 image_id 落盘。
676
+ *
677
+ * 正常流程 complete → send → delete 之间只有几秒;但进程若恰好在这段
678
+ * 时间崩了,内存里的 `_ownMediaImages` 就没了,素材成了孤儿,攒满官方
679
+ * 100 张配额之后所有预上传都会失败。落一个极小的 JSON,下次进程第一次
680
+ * 上传时认领并删掉,配额就不会被崩溃残留慢慢吃掉。
681
+ */
682
+ async #persistOwnMedia() {
683
+ try {
684
+ await fs.mkdir(path.dirname(OWN_MEDIA_FILE), { recursive: true });
685
+ await fs.writeFile(OWN_MEDIA_FILE, JSON.stringify([...this._ownMediaImages]), 'utf8');
686
+ } catch (e) {
687
+ log.warn(`Markdown 素材归属记录写失败(不影响本次发送): ${e.message}`);
688
+ }
689
+ }
690
+
691
+ /** 进程内只跑一次:认领上次崩溃留下的孤儿素材并删除。 */
692
+ async #reclaimOrphanMediaImages() {
693
+ if (this._mediaReclaimDone) return;
694
+ this._mediaReclaimDone = true;
695
+ let ids;
696
+ try {
697
+ ids = JSON.parse(await fs.readFile(OWN_MEDIA_FILE, 'utf8'));
698
+ } catch {
699
+ return; // 没有记录文件 / 内容损坏,都当没有孤儿
700
+ }
701
+ if (!Array.isArray(ids) || !ids.length) return;
702
+ for (const raw of ids) {
703
+ const id = String(raw ?? '');
704
+ if (!id) continue;
705
+ try {
706
+ await this.#request('DELETE', `/v2/media-images/${enc(id)}/delete`);
707
+ } catch (e) {
708
+ // 可能已被平台回收或已删过:留到下次再试,不阻断本次发送
709
+ log.warn(`孤儿素材清理失败 image_id=${id}: ${e.message}`);
710
+ this._ownMediaImages.add(id);
711
+ }
712
+ }
713
+ await this.#persistOwnMedia();
714
+ }
715
+
716
+ /** POST /v2/media-images/prepare */
717
+ prepareMediaImage({ fileName, fileSize, contentType, md5, sha1 } = {}) {
718
+ return this.#request('POST', '/v2/media-images/prepare', {
719
+ file_name: String(fileName ?? ''),
720
+ file_size: Number(fileSize) || 0,
721
+ content_type: String(contentType ?? ''),
722
+ md5: String(md5 ?? ''),
723
+ sha1: String(sha1 ?? ''),
724
+ });
725
+ }
726
+
727
+ /** POST /v2/media-images/complete;md5 取 COS 的 ETag(去引号) */
728
+ async completeMediaImage({ uploadId, md5 } = {}) {
729
+ const r = await this.#request('POST', '/v2/media-images/complete', {
730
+ upload_id: String(uploadId ?? ''),
731
+ md5: String(md5 ?? ''),
732
+ });
733
+ // 凡经本 QQApi 创建的素材都算「自己人」,记下来供 finally 清理
734
+ if (r?.image_id) {
735
+ this._ownMediaImages.add(String(r.image_id));
736
+ await this.#persistOwnMedia();
737
+ }
738
+ return r;
739
+ }
740
+
741
+ /**
742
+ * DELETE /v2/media-images/{image_id}/delete
743
+ *
744
+ * 删除后引用立即失效,但**已发出的消息不受影响**(平台发送时已转存副本)。
745
+ * 只接受本进程自己创建的 image_id —— 不给「传个 force 就能删别人素材」的后门。
746
+ * 端点已标 `internal:true`,外部经 WebUI 调不到。
747
+ */
748
+ async deleteMediaImage(imageId) {
749
+ const id = String(imageId ?? '');
750
+ if (!id) throw new Error('deleteMediaImage 需要 image_id');
751
+ if (!this._ownMediaImages.has(id)) {
752
+ throw new Error(`拒绝删除非本进程上传的素材 ${id}(素材库是机器人级共享,可能属于其它插件)`);
753
+ }
754
+ const r = await this.#request('DELETE', `/v2/media-images/${enc(id)}/delete`);
755
+ this._ownMediaImages.delete(id);
756
+ await this.#persistOwnMedia();
757
+ return r;
758
+ }
759
+
760
+ /**
761
+ * 把一张本地图上传成 Markdown 可用的 `qqbot-media://` 引用。
762
+ *
763
+ * **预检前置**:大小 >10MB / 扩展名不在白名单 / 文件头与扩展名不符,
764
+ * 都在本地判掉并带 `reason`,跳过 prepare/PUT/complete 三次网络请求。
765
+ * 这是「图片过大」这条最高频降级场景的专用快路径。
766
+ *
767
+ * 框架**不校验路径所属目录**:调用方是可信的插件代码,路径是否可信由它把关。
768
+ * 这里只做「能不能当图片上传」的本地预检(大小 / 扩展名 / 文件头)。
769
+ *
770
+ * @param {string} filePath 插件给出的本地文件路径(绝对路径或 cwd 相对路径)
771
+ * @returns {Promise<{imageId:string,url:string,ttl:number,fileName:string}>}
772
+ */
773
+ async uploadMarkdownImage(filePath) {
774
+ // 先认领上次进程崩溃留下的孤儿素材,避免 100 张配额被慢慢占满
775
+ await this.#reclaimOrphanMediaImages();
776
+ const p = String(filePath ?? '');
777
+ if (!p) {
778
+ const e = new Error('uploadMarkdownImage 需要本地文件路径');
779
+ e.reason = 'outside';
780
+ throw e;
781
+ }
782
+
783
+ let buf;
784
+ let contentType;
785
+ try {
786
+ const st = await fs.stat(p);
787
+ if (st.size > MEDIA_IMAGE_MAX) {
788
+ const e = new Error(`${p} 有 ${(st.size / 1024 / 1024).toFixed(1)}MB,超过 Markdown 素材 10MB 上限`);
789
+ e.reason = 'oversize';
790
+ throw e;
791
+ }
792
+ // 只读 16 字节判断真实格式,别为了预检把 10MB 整包读进来两遍
793
+ const fh = await fs.open(p, 'r');
794
+ let head;
795
+ try {
796
+ const b = Buffer.alloc(16);
797
+ const { bytesRead } = await fh.read(b, 0, 16, 0);
798
+ head = b.subarray(0, bytesRead);
799
+ } finally {
800
+ await fh.close();
801
+ }
802
+ const fmt = inspectImageFormat(head, p);
803
+ if (!fmt.ok) {
804
+ const e = new Error(fmt.detail);
805
+ e.reason = fmt.reason;
806
+ throw e;
807
+ }
808
+ contentType = fmt.contentType;
809
+ buf = await fs.readFile(p);
810
+ if (buf.length > MEDIA_IMAGE_MAX) {
811
+ const e = new Error(`${p} 读取后超过 10MB 上限`);
812
+ e.reason = 'oversize';
813
+ throw e;
814
+ }
815
+ } catch (e) {
816
+ if (!e.reason) {
817
+ e.reason = /ENOENT|EACCES|EPERM|ENOTDIR/.test(`${e?.code ?? ''} ${e?.message ?? ''}`)
818
+ ? 'outside'
819
+ : 'internal';
820
+ }
821
+ throw e;
822
+ }
823
+
824
+ const fileName = p.split(/[\\/]/).pop() || 'image.png';
825
+ const md5 = crypto.createHash('md5').update(buf).digest('hex');
826
+ const sha1 = crypto.createHash('sha1').update(buf).digest('hex');
827
+
828
+ const prep = await this.prepareMediaImage({
829
+ fileName,
830
+ fileSize: buf.length,
831
+ contentType,
832
+ md5,
833
+ sha1,
834
+ });
835
+ const uploadId = prep?.upload_id;
836
+ const presignedUrl = prep?.presigned_url;
837
+ if (!uploadId || !presignedUrl) {
838
+ const e = new Error('media-images/prepare 未返回 upload_id / presigned_url');
839
+ e.reason = 'internal';
840
+ throw e;
841
+ }
842
+
843
+ const etag = await this.#putPart(presignedUrl, buf, 60_000, contentType);
844
+ const done = await this.completeMediaImage({ uploadId, md5: etagToMd5(etag, md5) });
845
+ if (!done?.image_id || !done?.url) {
846
+ const e = new Error('media-images/complete 未返回 image_id / url');
847
+ e.reason = 'internal';
848
+ throw e;
849
+ }
850
+ this._ownMediaImages.add(String(done.image_id));
851
+ return {
852
+ imageId: String(done.image_id),
853
+ url: String(done.url),
854
+ ttl: done.ttl,
855
+ fileName,
856
+ };
857
+ }
858
+
588
859
  /* ---------------- 撤回 ---------------- */
589
860
 
590
861
  /**
package/src/bot.js CHANGED
@@ -386,15 +386,16 @@ export class BotRuntime {
386
386
  * 文案得能指导下一步。
387
387
  *
388
388
  * 以前只有「AppID xxx 已有实例在运行(PID 2816)」——用户既不知道 2816
389
- * 是谁,也没有任何地方能查。而他遇到的往往是「那个进程早就不在了,
390
- * 只是记录没删掉」,这时候要做的事跟「真的有另一个进程在跑」完全不同。
389
+ * 是谁,也没有任何地方能查。后来改成一律让用户去面板手动清,但现在
390
+ * 实例锁带心跳租约:进程真的没了、或 pid 被复用给别的程序时,残留记录
391
+ * 会在认领时自动清掉。所以「去清记录」只能是兜底,不能当成第一步。
391
392
  */
392
393
  const cpid = Number(claimed.conflict?.pid) || 0;
393
394
  const who = cpid === process.pid ? '本进程里的另一个机器人配置' : `PID ${cpid}`;
394
395
  this.lastError =
395
396
  `AppID ${cfg.appId} 已被${who}占用。` +
396
- '如果那个进程已经关了,去「设置 → 实例锁」清掉这条记录再上线;' +
397
- '如果它确实还在跑,先把另一个停掉';
397
+ '如果那个进程确实还在跑,先把另一个停掉;' +
398
+ '如果已经关了,残留记录通常会在下次上线时自动清理,仍被拦住再去「设置 → 实例锁」清掉这条记录';
398
399
  this.log.error(this.lastError);
399
400
  return this.state;
400
401
  }
@@ -812,6 +813,11 @@ export class BotRuntime {
812
813
  bot: this,
813
814
  });
814
815
  } catch (e) {
816
+ /** 事件监听器也算运行期错误;以前只有消息 listener 留痕,这里会静默丢。
817
+ * 发送侧的已知限制不是插件写错,别刷运行期错误卡。 */
818
+ if (!['offline', 'expired', 'quota', 'rate'].includes(e?.code)) {
819
+ this.plugins?.noteRuntimeError?.(l.pluginId, e);
820
+ }
815
821
  this.metrics.bump('errors');
816
822
  this.log.error(`监听器 ${l.pluginId} 处理 ${eventName} 出错:`, e.stack || e.message);
817
823
  }
@@ -1004,6 +1010,8 @@ export class BotRuntime {
1004
1010
  this.log.warn(`命令 ${commandEntry.name} 回复失败: ${e.message}`);
1005
1011
  return;
1006
1012
  }
1013
+ /** 命令 handler 抛错也要在面板留痕(已知发送限制不记,免得刷屏) */
1014
+ this.plugins?.noteRuntimeError?.(commandEntry.pluginId, e);
1007
1015
  this.log.error(
1008
1016
  `命令 ${commandEntry.name}(插件 ${commandEntry.pluginId})执行出错:`,
1009
1017
  e.stack || e.message,
@@ -1059,6 +1067,11 @@ export class BotRuntime {
1059
1067
  if (ret === true) msg.claim();
1060
1068
  if (ret === true || msg.replied) handled = true;
1061
1069
  } catch (e) {
1070
+ // 运行期错误也要留痕:以前只进日志,面板上看不出插件在反复抛错。
1071
+ // 发送侧的已知限制不算插件异常,跟命令 handler 保持同一口径。
1072
+ if (!['offline', 'expired', 'quota', 'rate'].includes(e?.code)) {
1073
+ this.plugins?.noteRuntimeError?.(l.pluginId, e);
1074
+ }
1062
1075
  this.metrics.bump('errors');
1063
1076
  this.log.error(`监听器 ${l.pluginId} 处理 ${evt} 出错:`, e.stack || e.message);
1064
1077
  }
package/src/config.js CHANGED
@@ -234,6 +234,12 @@ const BOT_DEFAULTS = {
234
234
  dailyActive: 1000,
235
235
  activePerMinute: 20,
236
236
  downgradeToActive: true,
237
+ /**
238
+ * E3:dry 出站截获。开着时**不真发**,只记下「本来会发什么」,
239
+ * 面板「概览」页可以看最近 50 条。默认关。
240
+ * 只能截到**本进程内建插件**的出站;外部子进程插件(NDJSON)不经过这里。
241
+ */
242
+ dryRun: false,
237
243
  },
238
244
 
239
245
  session: {
package/src/endpoints.js CHANGED
@@ -45,6 +45,11 @@ export const OFFICIAL_ENDPOINTS = [
45
45
  { method: 'POST', path: '/v2/groups/{group_id}/upload_prepare', api: 'uploadPrepare', group: '消息·富媒体', note: '分片上传第一步' },
46
46
  { method: 'POST', path: '/v2/groups/{group_id}/upload_part_finish', api: 'uploadPartFinish', group: '消息·富媒体', note: '分片上传第二步' },
47
47
 
48
+ /* ---------------- 消息 / Markdown 素材(机器人级图床,仅框架内部用) ---------------- */
49
+ { method: 'POST', path: '/v2/media-images/prepare', api: 'prepareMediaImage', group: '消息·Markdown 素材', note: '单图 ≤10MB,upload_id 4 小时', internal: true },
50
+ { method: 'POST', path: '/v2/media-images/complete', api: 'completeMediaImage', group: '消息·Markdown 素材', note: 'md5 取 COS ETag', internal: true },
51
+ { method: 'DELETE', path: '/v2/media-images/{image_id}/delete', api: 'deleteMediaImage', group: '消息·Markdown 素材', note: '删除后引用失效,已发消息不受影响', internal: true },
52
+
48
53
  /* ---------------- 互动 / 自定义菜单 ---------------- */
49
54
  { method: 'GET', path: '/v2/menu', api: 'getGlobalMenu', group: '互动·菜单', note: '仅 C2C' },
50
55
  { method: 'PUT', path: '/v2/menu', api: 'setGlobalMenu', group: '互动·菜单', note: '仅 C2C,最多 10 项' },
@@ -187,9 +192,14 @@ export function riskOf(ep) {
187
192
  *
188
193
  * 白名单来自这张表本身——**不在表里的一律拒绝**,
189
194
  * 免得以后有人往 QQApi 加了个内部方法,外部就能顺手调。
195
+ *
196
+ * `internal:true` 的端点仍登记在官方清单里(覆盖度测试要校验),但**不对外开放**:
197
+ * 素材三步上传必须经 `api.uploadMarkdownImage()` 串起来,外部直接 prepare/complete
198
+ * 会绕过本地预检(10MB / 文件头 / 扩展名),还能无节制消耗机器人 100 张配额。
190
199
  */
191
200
  export const CALLABLE_METHODS = new Set(
192
- OFFICIAL_ENDPOINTS.map((e) => e.api).filter((v) => typeof v === 'string' && v),
201
+ OFFICIAL_ENDPOINTS.filter((e) => !e.internal)
202
+ .map((e) => e.api).filter((v) => typeof v === 'string' && v),
193
203
  );
194
204
 
195
205
  /**
@@ -199,7 +209,8 @@ export const CALLABLE_METHODS = new Set(
199
209
  export function capabilityList() {
200
210
  const byApi = new Map();
201
211
  for (const ep of OFFICIAL_ENDPOINTS) {
202
- if (!ep.api) continue;
212
+ // 内部专用端点不给外部能力清单,免得 AI 以为可以自己拼素材上传流程
213
+ if (!ep.api || ep.internal) continue;
203
214
  const cur = byApi.get(ep.api);
204
215
  if (!cur) {
205
216
  byApi.set(ep.api, {