@cxyhhhhh/openclaw-qqbot 1.6.7-alpha.1

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.
Files changed (218) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +470 -0
  3. package/README.zh.md +465 -0
  4. package/bin/qqbot-cli.js +243 -0
  5. package/dist/index.d.ts +17 -0
  6. package/dist/index.js +26 -0
  7. package/dist/src/admin-resolver.d.ts +33 -0
  8. package/dist/src/admin-resolver.js +157 -0
  9. package/dist/src/api.d.ts +264 -0
  10. package/dist/src/api.js +777 -0
  11. package/dist/src/channel.d.ts +29 -0
  12. package/dist/src/channel.js +452 -0
  13. package/dist/src/config.d.ts +56 -0
  14. package/dist/src/config.js +278 -0
  15. package/dist/src/credential-backup.d.ts +31 -0
  16. package/dist/src/credential-backup.js +66 -0
  17. package/dist/src/deliver-debounce.d.ts +74 -0
  18. package/dist/src/deliver-debounce.js +174 -0
  19. package/dist/src/gateway.d.ts +18 -0
  20. package/dist/src/gateway.js +2021 -0
  21. package/dist/src/group-history.d.ts +136 -0
  22. package/dist/src/group-history.js +226 -0
  23. package/dist/src/image-server.d.ts +87 -0
  24. package/dist/src/image-server.js +570 -0
  25. package/dist/src/inbound-attachments.d.ts +60 -0
  26. package/dist/src/inbound-attachments.js +248 -0
  27. package/dist/src/known-users.d.ts +100 -0
  28. package/dist/src/known-users.js +263 -0
  29. package/dist/src/message-gating.d.ts +53 -0
  30. package/dist/src/message-gating.js +107 -0
  31. package/dist/src/message-queue.d.ts +86 -0
  32. package/dist/src/message-queue.js +257 -0
  33. package/dist/src/onboarding.d.ts +10 -0
  34. package/dist/src/onboarding.js +203 -0
  35. package/dist/src/outbound-deliver.d.ts +48 -0
  36. package/dist/src/outbound-deliver.js +392 -0
  37. package/dist/src/outbound.d.ts +205 -0
  38. package/dist/src/outbound.js +926 -0
  39. package/dist/src/proactive.d.ts +170 -0
  40. package/dist/src/proactive.js +399 -0
  41. package/dist/src/ref-index-store.d.ts +70 -0
  42. package/dist/src/ref-index-store.js +250 -0
  43. package/dist/src/reply-dispatcher.d.ts +35 -0
  44. package/dist/src/reply-dispatcher.js +311 -0
  45. package/dist/src/request-context.d.ts +18 -0
  46. package/dist/src/request-context.js +30 -0
  47. package/dist/src/runtime.d.ts +3 -0
  48. package/dist/src/runtime.js +10 -0
  49. package/dist/src/session-store.d.ts +52 -0
  50. package/dist/src/session-store.js +254 -0
  51. package/dist/src/slash-commands.d.ts +77 -0
  52. package/dist/src/slash-commands.js +1461 -0
  53. package/dist/src/startup-greeting.d.ts +30 -0
  54. package/dist/src/startup-greeting.js +97 -0
  55. package/dist/src/streaming.d.ts +250 -0
  56. package/dist/src/streaming.js +914 -0
  57. package/dist/src/stt.d.ts +21 -0
  58. package/dist/src/stt.js +70 -0
  59. package/dist/src/tools/channel.d.ts +16 -0
  60. package/dist/src/tools/channel.js +234 -0
  61. package/dist/src/tools/remind.d.ts +2 -0
  62. package/dist/src/tools/remind.js +248 -0
  63. package/dist/src/types.d.ts +364 -0
  64. package/dist/src/types.js +17 -0
  65. package/dist/src/typing-keepalive.d.ts +27 -0
  66. package/dist/src/typing-keepalive.js +64 -0
  67. package/dist/src/update-checker.d.ts +34 -0
  68. package/dist/src/update-checker.js +160 -0
  69. package/dist/src/utils/audio-convert.d.ts +98 -0
  70. package/dist/src/utils/audio-convert.js +755 -0
  71. package/dist/src/utils/chunked-upload.d.ts +59 -0
  72. package/dist/src/utils/chunked-upload.js +289 -0
  73. package/dist/src/utils/file-utils.d.ts +61 -0
  74. package/dist/src/utils/file-utils.js +172 -0
  75. package/dist/src/utils/image-size.d.ts +51 -0
  76. package/dist/src/utils/image-size.js +234 -0
  77. package/dist/src/utils/media-send.d.ts +148 -0
  78. package/dist/src/utils/media-send.js +456 -0
  79. package/dist/src/utils/media-tags.d.ts +14 -0
  80. package/dist/src/utils/media-tags.js +164 -0
  81. package/dist/src/utils/payload.d.ts +112 -0
  82. package/dist/src/utils/payload.js +186 -0
  83. package/dist/src/utils/pkg-version.d.ts +5 -0
  84. package/dist/src/utils/pkg-version.js +51 -0
  85. package/dist/src/utils/platform.d.ts +137 -0
  86. package/dist/src/utils/platform.js +390 -0
  87. package/dist/src/utils/ssrf-guard.d.ts +25 -0
  88. package/dist/src/utils/ssrf-guard.js +91 -0
  89. package/dist/src/utils/text-parsing.d.ts +32 -0
  90. package/dist/src/utils/text-parsing.js +69 -0
  91. package/dist/src/utils/upload-cache.d.ts +34 -0
  92. package/dist/src/utils/upload-cache.js +93 -0
  93. package/index.ts +31 -0
  94. package/node_modules/@eshaz/web-worker/LICENSE +201 -0
  95. package/node_modules/@eshaz/web-worker/README.md +134 -0
  96. package/node_modules/@eshaz/web-worker/browser.js +17 -0
  97. package/node_modules/@eshaz/web-worker/cjs/browser.js +16 -0
  98. package/node_modules/@eshaz/web-worker/cjs/node.js +219 -0
  99. package/node_modules/@eshaz/web-worker/index.d.ts +4 -0
  100. package/node_modules/@eshaz/web-worker/node.js +223 -0
  101. package/node_modules/@eshaz/web-worker/package.json +54 -0
  102. package/node_modules/@wasm-audio-decoders/common/index.js +5 -0
  103. package/node_modules/@wasm-audio-decoders/common/package.json +36 -0
  104. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderCommon.js +231 -0
  105. package/node_modules/@wasm-audio-decoders/common/src/WASMAudioDecoderWorker.js +129 -0
  106. package/node_modules/@wasm-audio-decoders/common/src/puff/README +67 -0
  107. package/node_modules/@wasm-audio-decoders/common/src/puff/build_puff.js +31 -0
  108. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.c +863 -0
  109. package/node_modules/@wasm-audio-decoders/common/src/puff/puff.h +35 -0
  110. package/node_modules/@wasm-audio-decoders/common/src/utilities.js +3 -0
  111. package/node_modules/@wasm-audio-decoders/common/types.d.ts +7 -0
  112. package/node_modules/mpg123-decoder/README.md +265 -0
  113. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js +185 -0
  114. package/node_modules/mpg123-decoder/dist/mpg123-decoder.min.js.map +1 -0
  115. package/node_modules/mpg123-decoder/index.js +8 -0
  116. package/node_modules/mpg123-decoder/package.json +58 -0
  117. package/node_modules/mpg123-decoder/src/EmscriptenWasm.js +464 -0
  118. package/node_modules/mpg123-decoder/src/MPEGDecoder.js +200 -0
  119. package/node_modules/mpg123-decoder/src/MPEGDecoderWebWorker.js +21 -0
  120. package/node_modules/mpg123-decoder/types.d.ts +30 -0
  121. package/node_modules/silk-wasm/LICENSE +21 -0
  122. package/node_modules/silk-wasm/README.md +85 -0
  123. package/node_modules/silk-wasm/lib/index.cjs +16 -0
  124. package/node_modules/silk-wasm/lib/index.d.ts +70 -0
  125. package/node_modules/silk-wasm/lib/index.mjs +16 -0
  126. package/node_modules/silk-wasm/lib/silk.wasm +0 -0
  127. package/node_modules/silk-wasm/lib/utils.d.ts +4 -0
  128. package/node_modules/silk-wasm/package.json +39 -0
  129. package/node_modules/simple-yenc/.github/FUNDING.yml +1 -0
  130. package/node_modules/simple-yenc/.prettierignore +1 -0
  131. package/node_modules/simple-yenc/LICENSE +7 -0
  132. package/node_modules/simple-yenc/README.md +163 -0
  133. package/node_modules/simple-yenc/dist/esm.js +1 -0
  134. package/node_modules/simple-yenc/dist/index.js +1 -0
  135. package/node_modules/simple-yenc/package.json +50 -0
  136. package/node_modules/simple-yenc/rollup.config.js +27 -0
  137. package/node_modules/simple-yenc/src/simple-yenc.js +302 -0
  138. package/node_modules/ws/LICENSE +20 -0
  139. package/node_modules/ws/README.md +548 -0
  140. package/node_modules/ws/browser.js +8 -0
  141. package/node_modules/ws/index.js +13 -0
  142. package/node_modules/ws/lib/buffer-util.js +131 -0
  143. package/node_modules/ws/lib/constants.js +19 -0
  144. package/node_modules/ws/lib/event-target.js +292 -0
  145. package/node_modules/ws/lib/extension.js +203 -0
  146. package/node_modules/ws/lib/limiter.js +55 -0
  147. package/node_modules/ws/lib/permessage-deflate.js +528 -0
  148. package/node_modules/ws/lib/receiver.js +706 -0
  149. package/node_modules/ws/lib/sender.js +602 -0
  150. package/node_modules/ws/lib/stream.js +161 -0
  151. package/node_modules/ws/lib/subprotocol.js +62 -0
  152. package/node_modules/ws/lib/validation.js +152 -0
  153. package/node_modules/ws/lib/websocket-server.js +554 -0
  154. package/node_modules/ws/lib/websocket.js +1393 -0
  155. package/node_modules/ws/package.json +69 -0
  156. package/node_modules/ws/wrapper.mjs +8 -0
  157. package/openclaw.plugin.json +17 -0
  158. package/package.json +67 -0
  159. package/preload.cjs +33 -0
  160. package/scripts/cleanup-legacy-plugins.sh +124 -0
  161. package/scripts/link-sdk-core.cjs +185 -0
  162. package/scripts/postinstall-link-sdk.js +113 -0
  163. package/scripts/proactive-api-server.ts +369 -0
  164. package/scripts/send-proactive.ts +293 -0
  165. package/scripts/set-markdown.sh +156 -0
  166. package/scripts/test-sendmedia.ts +116 -0
  167. package/scripts/upgrade-via-npm.ps1 +451 -0
  168. package/scripts/upgrade-via-npm.sh +528 -0
  169. package/scripts/upgrade-via-source.sh +916 -0
  170. package/skills/qqbot-channel/SKILL.md +263 -0
  171. package/skills/qqbot-channel/references/api_references.md +521 -0
  172. package/skills/qqbot-media/SKILL.md +60 -0
  173. package/skills/qqbot-remind/SKILL.md +149 -0
  174. package/src/admin-resolver.ts +181 -0
  175. package/src/api.ts +1138 -0
  176. package/src/channel.ts +477 -0
  177. package/src/config.ts +347 -0
  178. package/src/credential-backup.ts +72 -0
  179. package/src/deliver-debounce.ts +229 -0
  180. package/src/gateway.ts +2257 -0
  181. package/src/group-history.ts +328 -0
  182. package/src/image-server.ts +675 -0
  183. package/src/inbound-attachments.ts +321 -0
  184. package/src/known-users.ts +353 -0
  185. package/src/message-gating.ts +190 -0
  186. package/src/message-queue.ts +349 -0
  187. package/src/onboarding.ts +274 -0
  188. package/src/openclaw-plugin-sdk.d.ts +587 -0
  189. package/src/outbound-deliver.ts +473 -0
  190. package/src/outbound.ts +1119 -0
  191. package/src/proactive.ts +530 -0
  192. package/src/ref-index-store.ts +335 -0
  193. package/src/reply-dispatcher.ts +334 -0
  194. package/src/request-context.ts +39 -0
  195. package/src/runtime.ts +14 -0
  196. package/src/session-store.ts +303 -0
  197. package/src/slash-commands.ts +1615 -0
  198. package/src/startup-greeting.ts +120 -0
  199. package/src/streaming.ts +1102 -0
  200. package/src/stt.ts +86 -0
  201. package/src/tools/channel.ts +281 -0
  202. package/src/tools/remind.ts +300 -0
  203. package/src/types.ts +386 -0
  204. package/src/typing-keepalive.ts +59 -0
  205. package/src/update-checker.ts +174 -0
  206. package/src/utils/audio-convert.ts +859 -0
  207. package/src/utils/chunked-upload.ts +419 -0
  208. package/src/utils/file-utils.ts +193 -0
  209. package/src/utils/image-size.ts +266 -0
  210. package/src/utils/media-send.ts +585 -0
  211. package/src/utils/media-tags.ts +182 -0
  212. package/src/utils/payload.ts +265 -0
  213. package/src/utils/pkg-version.ts +54 -0
  214. package/src/utils/platform.ts +435 -0
  215. package/src/utils/ssrf-guard.ts +102 -0
  216. package/src/utils/text-parsing.ts +75 -0
  217. package/src/utils/upload-cache.ts +128 -0
  218. package/tsconfig.json +16 -0
@@ -0,0 +1,570 @@
1
+ /**
2
+ * 本地图床服务器
3
+ * 提供安全的图片存储和访问服务
4
+ */
5
+ import http from "node:http";
6
+ import fs from "node:fs";
7
+ import { pipeline } from "node:stream/promises";
8
+ import { Readable } from "node:stream";
9
+ import path from "node:path";
10
+ import crypto from "node:crypto";
11
+ import { validateRemoteUrl } from "./utils/ssrf-guard.js";
12
+ import { getQQBotMediaDir } from "./utils/platform.js";
13
+ const DEFAULT_CONFIG = {
14
+ port: 18765,
15
+ storageDir: "./qqbot-images",
16
+ baseUrl: "",
17
+ ttlSeconds: 3600, // 默认 1 小时过期
18
+ allowedFormats: ["png", "jpg", "jpeg", "gif", "webp"],
19
+ };
20
+ let serverInstance = null;
21
+ let currentConfig = { ...DEFAULT_CONFIG };
22
+ let imageIndex = new Map();
23
+ /**
24
+ * 生成安全的随机 ID
25
+ */
26
+ function generateImageId() {
27
+ return crypto.randomBytes(16).toString("hex");
28
+ }
29
+ /**
30
+ * 验证请求路径是否安全(防止目录遍历攻击)
31
+ */
32
+ function isPathSafe(requestPath, baseDir) {
33
+ const normalizedBase = path.resolve(baseDir);
34
+ const normalizedPath = path.resolve(baseDir, requestPath);
35
+ return normalizedPath.startsWith(normalizedBase + path.sep) || normalizedPath === normalizedBase;
36
+ }
37
+ /**
38
+ * 获取 MIME 类型
39
+ */
40
+ function getMimeType(ext) {
41
+ const mimeTypes = {
42
+ png: "image/png",
43
+ jpg: "image/jpeg",
44
+ jpeg: "image/jpeg",
45
+ gif: "image/gif",
46
+ webp: "image/webp",
47
+ };
48
+ return mimeTypes[ext.toLowerCase()] || "application/octet-stream";
49
+ }
50
+ /**
51
+ * 从 MIME 类型获取扩展名
52
+ */
53
+ function getExtFromMime(mimeType) {
54
+ const extMap = {
55
+ "image/png": "png",
56
+ "image/jpeg": "jpg",
57
+ "image/gif": "gif",
58
+ "image/webp": "webp",
59
+ "application/pdf": "pdf",
60
+ "application/json": "json",
61
+ "text/plain": "txt",
62
+ "text/csv": "csv",
63
+ "application/msword": "doc",
64
+ "application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
65
+ "application/vnd.ms-excel": "xls",
66
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
67
+ };
68
+ return extMap[mimeType] || null;
69
+ }
70
+ /**
71
+ * 清理过期图片
72
+ */
73
+ function cleanupExpiredImages() {
74
+ const now = Date.now();
75
+ const expiredIds = [];
76
+ for (const [id, image] of imageIndex) {
77
+ if (image.ttl > 0 && now - image.createdAt > image.ttl * 1000) {
78
+ expiredIds.push(id);
79
+ }
80
+ }
81
+ for (const id of expiredIds) {
82
+ const image = imageIndex.get(id);
83
+ if (image) {
84
+ const filePath = path.join(currentConfig.storageDir, image.filename);
85
+ try {
86
+ if (fs.existsSync(filePath)) {
87
+ fs.unlinkSync(filePath);
88
+ }
89
+ }
90
+ catch {
91
+ // 忽略删除错误
92
+ }
93
+ imageIndex.delete(id);
94
+ }
95
+ }
96
+ }
97
+ /**
98
+ * 加载已有的图片索引
99
+ */
100
+ function loadImageIndex() {
101
+ const indexPath = path.join(currentConfig.storageDir, ".index.json");
102
+ try {
103
+ if (fs.existsSync(indexPath)) {
104
+ const data = JSON.parse(fs.readFileSync(indexPath, "utf-8"));
105
+ imageIndex = new Map(Object.entries(data));
106
+ }
107
+ }
108
+ catch {
109
+ imageIndex = new Map();
110
+ }
111
+ }
112
+ /**
113
+ * 保存图片索引
114
+ */
115
+ function saveImageIndex() {
116
+ const indexPath = path.join(currentConfig.storageDir, ".index.json");
117
+ try {
118
+ const data = Object.fromEntries(imageIndex);
119
+ fs.writeFileSync(indexPath, JSON.stringify(data, null, 2));
120
+ }
121
+ catch {
122
+ // 忽略保存错误
123
+ }
124
+ }
125
+ /**
126
+ * 处理 HTTP 请求
127
+ */
128
+ function handleRequest(req, res) {
129
+ const url = new URL(req.url || "/", `http://localhost:${currentConfig.port}`);
130
+ const pathname = url.pathname;
131
+ // 设置 CORS 头(允许 QQ 服务器访问)
132
+ res.setHeader("Access-Control-Allow-Origin", "*");
133
+ res.setHeader("Access-Control-Allow-Methods", "GET, OPTIONS");
134
+ if (req.method === "OPTIONS") {
135
+ res.writeHead(204);
136
+ res.end();
137
+ return;
138
+ }
139
+ // 只允许 GET 请求访问图片
140
+ if (req.method !== "GET") {
141
+ res.writeHead(405, { "Content-Type": "text/plain" });
142
+ res.end("Method Not Allowed");
143
+ return;
144
+ }
145
+ // 解析图片 ID(路径格式: /images/{id}.{ext})
146
+ const match = pathname.match(/^\/images\/([a-f0-9]{32})\.(\w+)$/);
147
+ if (!match) {
148
+ res.writeHead(404, { "Content-Type": "text/plain" });
149
+ res.end("Not Found");
150
+ return;
151
+ }
152
+ const [, imageId, requestedExt] = match;
153
+ const image = imageIndex.get(imageId);
154
+ if (!image) {
155
+ res.writeHead(404, { "Content-Type": "text/plain" });
156
+ res.end("Image Not Found");
157
+ return;
158
+ }
159
+ // 检查是否过期
160
+ if (image.ttl > 0 && Date.now() - image.createdAt > image.ttl * 1000) {
161
+ res.writeHead(410, { "Content-Type": "text/plain" });
162
+ res.end("Image Expired");
163
+ return;
164
+ }
165
+ // 安全检查:确保文件路径在存储目录内
166
+ const filePath = path.join(currentConfig.storageDir, image.filename);
167
+ if (!isPathSafe(image.filename, currentConfig.storageDir)) {
168
+ res.writeHead(403, { "Content-Type": "text/plain" });
169
+ res.end("Forbidden");
170
+ return;
171
+ }
172
+ // 读取并返回图片
173
+ try {
174
+ if (!fs.existsSync(filePath)) {
175
+ res.writeHead(404, { "Content-Type": "text/plain" });
176
+ res.end("File Not Found");
177
+ return;
178
+ }
179
+ const imageData = fs.readFileSync(filePath);
180
+ res.writeHead(200, {
181
+ "Content-Type": image.mimeType,
182
+ "Content-Length": imageData.length,
183
+ "Cache-Control": image.ttl > 0 ? `max-age=${image.ttl}` : "max-age=31536000",
184
+ });
185
+ res.end(imageData);
186
+ }
187
+ catch (err) {
188
+ res.writeHead(500, { "Content-Type": "text/plain" });
189
+ res.end("Internal Server Error");
190
+ }
191
+ }
192
+ /**
193
+ * 启动图床服务器
194
+ */
195
+ export function startImageServer(config) {
196
+ return new Promise((resolve, reject) => {
197
+ if (serverInstance) {
198
+ const baseUrl = currentConfig.baseUrl || `http://localhost:${currentConfig.port}`;
199
+ resolve(baseUrl);
200
+ return;
201
+ }
202
+ currentConfig = { ...DEFAULT_CONFIG, ...config };
203
+ // 确保存储目录存在
204
+ if (!fs.existsSync(currentConfig.storageDir)) {
205
+ fs.mkdirSync(currentConfig.storageDir, { recursive: true });
206
+ }
207
+ // 加载图片索引
208
+ loadImageIndex();
209
+ // 启动定期清理
210
+ const cleanupInterval = setInterval(cleanupExpiredImages, 60000); // 每分钟清理一次
211
+ serverInstance = http.createServer(handleRequest);
212
+ serverInstance.on("error", (err) => {
213
+ clearInterval(cleanupInterval);
214
+ reject(err);
215
+ });
216
+ serverInstance.listen(currentConfig.port, () => {
217
+ const baseUrl = currentConfig.baseUrl || `http://localhost:${currentConfig.port}`;
218
+ resolve(baseUrl);
219
+ });
220
+ });
221
+ }
222
+ /**
223
+ * 停止图床服务器
224
+ */
225
+ export function stopImageServer() {
226
+ return new Promise((resolve) => {
227
+ if (serverInstance) {
228
+ serverInstance.close(() => {
229
+ serverInstance = null;
230
+ saveImageIndex();
231
+ resolve();
232
+ });
233
+ }
234
+ else {
235
+ resolve();
236
+ }
237
+ });
238
+ }
239
+ /**
240
+ * 保存图片并返回访问 URL
241
+ * @param imageData 图片数据(Buffer 或 base64 字符串)
242
+ * @param mimeType 图片 MIME 类型
243
+ * @param ttlSeconds 过期时间(秒),默认使用配置值
244
+ * @returns 图片访问 URL
245
+ */
246
+ export function saveImage(imageData, mimeType = "image/png", ttlSeconds) {
247
+ // 转换 base64 为 Buffer
248
+ let buffer;
249
+ if (typeof imageData === "string") {
250
+ // 处理 data URL 格式
251
+ const base64Match = imageData.match(/^data:([^;]+);base64,(.+)$/);
252
+ if (base64Match) {
253
+ mimeType = base64Match[1];
254
+ buffer = Buffer.from(base64Match[2], "base64");
255
+ }
256
+ else {
257
+ buffer = Buffer.from(imageData, "base64");
258
+ }
259
+ }
260
+ else {
261
+ buffer = imageData;
262
+ }
263
+ // 生成唯一 ID 和文件名
264
+ const imageId = generateImageId();
265
+ const ext = getExtFromMime(mimeType) || "png";
266
+ const filename = `${imageId}.${ext}`;
267
+ // 确保存储目录存在
268
+ if (!fs.existsSync(currentConfig.storageDir)) {
269
+ fs.mkdirSync(currentConfig.storageDir, { recursive: true });
270
+ }
271
+ // 保存文件
272
+ const filePath = path.join(currentConfig.storageDir, filename);
273
+ fs.writeFileSync(filePath, buffer);
274
+ // 记录到索引
275
+ const image = {
276
+ id: imageId,
277
+ filename,
278
+ mimeType,
279
+ createdAt: Date.now(),
280
+ ttl: ttlSeconds ?? currentConfig.ttlSeconds,
281
+ };
282
+ imageIndex.set(imageId, image);
283
+ saveImageIndex();
284
+ // 返回访问 URL
285
+ const baseUrl = currentConfig.baseUrl || `http://localhost:${currentConfig.port}`;
286
+ return `${baseUrl}/images/${imageId}.${ext}`;
287
+ }
288
+ /**
289
+ * 从本地文件路径保存图片到图床
290
+ * @param filePath 本地文件路径
291
+ * @param ttlSeconds 过期时间(秒),默认使用配置值
292
+ * @returns 图片访问 URL,如果文件不存在或不是图片则返回 null
293
+ */
294
+ export function saveImageFromPath(filePath, ttlSeconds) {
295
+ try {
296
+ console.log(`[image-server] saveImageFromPath: ${filePath}`);
297
+ // 检查文件是否存在
298
+ if (!fs.existsSync(filePath)) {
299
+ console.log(`[image-server] File not found: ${filePath}`);
300
+ return null;
301
+ }
302
+ // 读取文件
303
+ const buffer = fs.readFileSync(filePath);
304
+ console.log(`[image-server] File size: ${buffer.length}`);
305
+ // 根据扩展名获取 MIME 类型
306
+ const ext = path.extname(filePath).toLowerCase().replace(".", "");
307
+ console.log(`[image-server] Extension: "${ext}"`);
308
+ const mimeType = getMimeType(ext);
309
+ console.log(`[image-server] MIME type: ${mimeType}`);
310
+ // 只处理图片文件
311
+ if (!mimeType.startsWith("image/")) {
312
+ console.log(`[image-server] Not an image file`);
313
+ return null;
314
+ }
315
+ // 使用 saveImage 保存
316
+ return saveImage(buffer, mimeType, ttlSeconds);
317
+ }
318
+ catch (err) {
319
+ console.error(`[image-server] saveImageFromPath error:`, err);
320
+ return null;
321
+ }
322
+ }
323
+ /**
324
+ * 检查图床服务器是否运行中
325
+ */
326
+ export function isImageServerRunning() {
327
+ return serverInstance !== null;
328
+ }
329
+ /**
330
+ * 确保图床服务器正在运行
331
+ * 如果未运行,则自动启动
332
+ * @param publicBaseUrl 公网访问的基础 URL(如 http://your-server:18765)
333
+ * @returns 基础 URL,启动失败返回 null
334
+ */
335
+ export async function ensureImageServer(publicBaseUrl) {
336
+ if (isImageServerRunning()) {
337
+ return publicBaseUrl || currentConfig.baseUrl || `http://0.0.0.0:${currentConfig.port}`;
338
+ }
339
+ try {
340
+ const config = {
341
+ port: DEFAULT_CONFIG.port,
342
+ storageDir: DEFAULT_CONFIG.storageDir,
343
+ // 使用用户配置的公网地址
344
+ baseUrl: publicBaseUrl || `http://0.0.0.0:${DEFAULT_CONFIG.port}`,
345
+ ttlSeconds: 3600, // 1 小时过期
346
+ };
347
+ await startImageServer(config);
348
+ console.log(`[image-server] Auto-started on port ${config.port}, baseUrl: ${config.baseUrl}`);
349
+ return config.baseUrl;
350
+ }
351
+ catch (err) {
352
+ console.error(`[image-server] Failed to auto-start: ${err}`);
353
+ return null;
354
+ }
355
+ }
356
+ /** 默认下载目录:与入站附件统一放在 ~/.openclaw/media/qqbot/downloads/ */
357
+ const DEFAULT_DOWNLOAD_DIR = getQQBotMediaDir("downloads");
358
+ /**
359
+ * 下载远程文件到系统临时目录。
360
+ *
361
+ * 文件名采用 UUID 保证不重名不覆盖,调用方用完后应自行删除。
362
+ *
363
+ * 安全措施:
364
+ * 1. SSRF 防护 — DNS 解析后校验 IP,拒绝私有/保留网段
365
+ * 2. Content-Type 黑名单 — 拦截 text/html(登录页/错误页/人机验证页)
366
+ * 3. 超时控制 — 默认 30 秒,传 0 表示不限时
367
+ * 4. 大小限制 — 可选,通过 Content-Length 预检 + 流式字节计数双重保护
368
+ *
369
+ * @param url 远程文件 URL
370
+ * @param originalFilename 原始文件名(可选,仅用于推导扩展名)
371
+ * @param options 下载选项
372
+ * @returns DownloadResult,filePath 为 null 表示失败,error 包含失败原因
373
+ */
374
+ export async function downloadFile(url, originalFilename, options) {
375
+ const timeoutMs = options?.timeoutMs ?? 30_000;
376
+ const destDir = options?.destDir ?? DEFAULT_DOWNLOAD_DIR;
377
+ const maxSizeBytes = options?.maxSizeBytes ?? 0; // 0 = 不限制
378
+ const maxRetries = options?.maxRetries ?? 2;
379
+ // ---- SSRF 防护(只做一次,不需要重试) ----
380
+ try {
381
+ await validateRemoteUrl(url);
382
+ }
383
+ catch (err) {
384
+ const msg = err instanceof Error ? err.message : String(err);
385
+ console.error(`[image-server] SSRF check failed: ${msg}`);
386
+ return { filePath: null, error: `URL 安全检查未通过: ${msg}` };
387
+ }
388
+ // 确保目标目录存在(只做一次)
389
+ if (!fs.existsSync(destDir)) {
390
+ fs.mkdirSync(destDir, { recursive: true });
391
+ }
392
+ let lastError = null;
393
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
394
+ if (attempt > 0) {
395
+ // 指数退避:1s, 2s
396
+ const delayMs = attempt * 1000;
397
+ console.log(`[image-server] Retry ${attempt}/${maxRetries} after ${delayMs}ms: ${url.slice(0, 120)}`);
398
+ await new Promise(r => setTimeout(r, delayMs));
399
+ }
400
+ const result = await downloadFileOnce(url, originalFilename, { timeoutMs, destDir, maxSizeBytes });
401
+ // 成功 或 不可重试的错误 → 直接返回
402
+ if (result.filePath || !result.retryable) {
403
+ return { filePath: result.filePath, error: result.error };
404
+ }
405
+ // 可重试的错误,记录后继续
406
+ lastError = { filePath: null, error: result.error };
407
+ console.error(`[image-server] Attempt ${attempt + 1}/${maxRetries + 1} failed (retryable): ${result.error}`);
408
+ }
409
+ // 所有重试用完
410
+ return lastError ?? { filePath: null, error: "下载失败(重试次数耗尽)" };
411
+ }
412
+ /**
413
+ * 执行一次下载尝试(无重试逻辑)。
414
+ */
415
+ async function downloadFileOnce(url, originalFilename, opts) {
416
+ const { timeoutMs, destDir, maxSizeBytes } = opts;
417
+ const controller = new AbortController();
418
+ // timeoutMs > 0 时启用超时;为 0 表示不限时
419
+ const timeoutId = timeoutMs > 0
420
+ ? setTimeout(() => controller.abort(), timeoutMs)
421
+ : null;
422
+ let tempPath = null;
423
+ try {
424
+ // 下载文件(带超时控制)
425
+ const response = await fetch(url, { signal: controller.signal });
426
+ if (!response.ok) {
427
+ const reason = `HTTP ${response.status} ${response.statusText}`;
428
+ console.error(`[image-server] Download failed: ${reason}`);
429
+ // 5xx 服务端错误可重试,4xx 不可重试
430
+ const retryable = response.status >= 500;
431
+ return { filePath: null, error: `下载失败 (${reason})`, retryable };
432
+ }
433
+ if (!response.body) {
434
+ console.error(`[image-server] Download failed: empty response body`);
435
+ return { filePath: null, error: `下载失败 (响应体为空)`, retryable: false };
436
+ }
437
+ // ---- 预检 Content-Length(如果服务端返回了该头) ----
438
+ if (maxSizeBytes > 0) {
439
+ const contentLength = Number(response.headers.get("content-length"));
440
+ if (contentLength > 0 && contentLength > maxSizeBytes) {
441
+ const sizeMB = (contentLength / (1024 * 1024)).toFixed(1);
442
+ const limitMB = Math.round(maxSizeBytes / (1024 * 1024));
443
+ console.error(`[image-server] File too large (Content-Length: ${sizeMB}MB, limit: ${limitMB}MB): ${url}`);
444
+ return { filePath: null, error: `文件过大(${sizeMB}MB),超过了${limitMB}M的下载限制`, retryable: false };
445
+ }
446
+ }
447
+ // 推导扩展名:originalFilename > Content-Disposition > Content-Type > .bin
448
+ const contentType = response.headers.get("content-type") ?? "";
449
+ let ext = "";
450
+ if (originalFilename) {
451
+ try {
452
+ ext = path.extname(decodeURIComponent(originalFilename));
453
+ }
454
+ catch {
455
+ ext = path.extname(originalFilename);
456
+ }
457
+ }
458
+ if (!ext) {
459
+ const disposition = response.headers.get("content-disposition");
460
+ if (disposition) {
461
+ const m = disposition.match(/filename\*?=(?:UTF-8''|")?([^";]+)"?/i);
462
+ if (m?.[1]) {
463
+ try {
464
+ ext = path.extname(decodeURIComponent(m[1]));
465
+ }
466
+ catch { /* keep empty */ }
467
+ }
468
+ }
469
+ }
470
+ if (!ext) {
471
+ const mime = contentType.split(";")[0]?.trim() ?? "";
472
+ ext = mime ? (`.${getExtFromMime(mime) ?? "bin"}`) : ".bin";
473
+ }
474
+ // UUID 文件名,绝对不会重名
475
+ const uniqueName = `${crypto.randomUUID()}${ext}`;
476
+ const filePath = path.join(destDir, uniqueName);
477
+ tempPath = filePath + ".tmp";
478
+ // ---- 流式写入临时文件(内存占用恒定,不会 OOM) ----
479
+ const nodeStream = Readable.fromWeb(response.body);
480
+ // 如果设置了大小限制,包装一个 Transform 流来监控已写入字节数
481
+ if (maxSizeBytes > 0) {
482
+ const { Transform } = await import("node:stream");
483
+ let bytesWritten = 0;
484
+ const sizeGuard = new Transform({
485
+ transform(chunk, _encoding, callback) {
486
+ bytesWritten += chunk.length;
487
+ if (bytesWritten > maxSizeBytes) {
488
+ const sizeMB = (bytesWritten / (1024 * 1024)).toFixed(1);
489
+ const limitMB = Math.round(maxSizeBytes / (1024 * 1024));
490
+ callback(new Error(`DOWNLOAD_SIZE_EXCEEDED: ${sizeMB}MB > ${limitMB}MB`));
491
+ }
492
+ else {
493
+ callback(null, chunk);
494
+ }
495
+ },
496
+ });
497
+ const writeStream = fs.createWriteStream(tempPath);
498
+ await pipeline(nodeStream, sizeGuard, writeStream);
499
+ }
500
+ else {
501
+ const writeStream = fs.createWriteStream(tempPath);
502
+ await pipeline(nodeStream, writeStream);
503
+ }
504
+ // 流式写入完成,原子重命名为最终文件
505
+ const stat = await fs.promises.stat(tempPath);
506
+ fs.renameSync(tempPath, filePath);
507
+ tempPath = null; // 重命名成功,不再需要清理
508
+ console.log(`[image-server] Downloaded file: ${filePath} (${stat.size} bytes)`);
509
+ return { filePath };
510
+ }
511
+ catch (err) {
512
+ // 清理不完整的临时文件
513
+ if (tempPath) {
514
+ try {
515
+ fs.unlinkSync(tempPath);
516
+ }
517
+ catch { /* ignore cleanup error */ }
518
+ }
519
+ if (err instanceof Error && err.name === "AbortError") {
520
+ console.error(`[image-server] Download timeout after ${timeoutMs}ms: ${url}`);
521
+ return { filePath: null, error: `下载超时(${Math.round(timeoutMs / 1000)}秒)`, retryable: true };
522
+ }
523
+ // 大小超限错误 — 不可重试
524
+ if (err instanceof Error && err.message.startsWith("DOWNLOAD_SIZE_EXCEEDED:")) {
525
+ const limitMB = maxSizeBytes > 0 ? Math.round(maxSizeBytes / (1024 * 1024)) : 0;
526
+ console.error(`[image-server] Download size exceeded ${limitMB}MB: ${url}`);
527
+ return { filePath: null, error: `文件过大,超过了${limitMB}M的下载限制`, retryable: false };
528
+ }
529
+ // 网络层临时错误 — 可重试
530
+ const retryable = isRetryableNetworkError(err);
531
+ const msg = err instanceof Error ? err.message : String(err);
532
+ console.error(`[image-server] Download error (retryable=${retryable}):`, err);
533
+ return { filePath: null, error: `下载出错: ${msg}`, retryable };
534
+ }
535
+ finally {
536
+ if (timeoutId)
537
+ clearTimeout(timeoutId);
538
+ }
539
+ }
540
+ /**
541
+ * 判断错误是否为可重试的网络临时错误。
542
+ *
543
+ * 覆盖常见的 TCP/DNS 层面临时故障:
544
+ * - ETIMEDOUT: TCP 连接超时
545
+ * - ECONNRESET: 连接被对端重置
546
+ * - ECONNREFUSED: 连接被拒绝
547
+ * - ENOTFOUND: DNS 解析失败
548
+ * - EAI_AGAIN: DNS 临时失败
549
+ * - UND_ERR_CONNECT_TIMEOUT: undici 连接超时
550
+ * - fetch failed: Node.js fetch 底层网络错误的通用消息
551
+ */
552
+ function isRetryableNetworkError(err) {
553
+ if (!(err instanceof Error))
554
+ return false;
555
+ const code = err.code;
556
+ if (code && ["ETIMEDOUT", "ECONNRESET", "ECONNREFUSED", "ENOTFOUND", "EAI_AGAIN", "UND_ERR_CONNECT_TIMEOUT"].includes(code)) {
557
+ return true;
558
+ }
559
+ // Node.js fetch 抛出 TypeError: fetch failed 时,真正的网络错误在 cause 中
560
+ if (err.message === "fetch failed" && err.cause) {
561
+ return isRetryableNetworkError(err.cause);
562
+ }
563
+ return false;
564
+ }
565
+ /**
566
+ * 获取图床服务器配置
567
+ */
568
+ export function getImageServerConfig() {
569
+ return { ...currentConfig };
570
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 入站附件处理模块
3
+ *
4
+ * 负责下载、转换、转录用户发送的附件(图片/语音/文件),
5
+ * 并归类为统一的 ProcessedAttachments 结构供 gateway 消费。
6
+ */
7
+ export interface RawAttachment {
8
+ content_type: string;
9
+ url: string;
10
+ filename?: string;
11
+ voice_wav_url?: string;
12
+ asr_refer_text?: string;
13
+ }
14
+ export type TranscriptSource = "stt" | "asr" | "fallback";
15
+ /** processAttachments 的返回值 */
16
+ export interface ProcessedAttachments {
17
+ /** 附件描述文本(其它类型附件) */
18
+ attachmentInfo: string;
19
+ /** 图片本地路径或远程 URL */
20
+ imageUrls: string[];
21
+ /** 图片 MIME 类型(与 imageUrls 一一对应) */
22
+ imageMediaTypes: string[];
23
+ /** 语音本地路径 */
24
+ voiceAttachmentPaths: string[];
25
+ /** 语音远程 URL */
26
+ voiceAttachmentUrls: string[];
27
+ /** QQ ASR 原始识别文本 */
28
+ voiceAsrReferTexts: string[];
29
+ /** 语音转录文本 */
30
+ voiceTranscripts: string[];
31
+ /** 转录来源 */
32
+ voiceTranscriptSources: TranscriptSource[];
33
+ /** 每个附件的本地路径(与原始 attachments 数组一一对应,未下载的为 null) */
34
+ attachmentLocalPaths: Array<string | null>;
35
+ }
36
+ interface ProcessContext {
37
+ appId: string;
38
+ /** 对话 ID:群聊传 groupOpenid,私聊传 senderId(用于按群/用户隔离下载目录) */
39
+ peerId?: string;
40
+ cfg: unknown;
41
+ log?: {
42
+ info: (msg: string) => void;
43
+ error: (msg: string) => void;
44
+ debug?: (msg: string) => void;
45
+ };
46
+ }
47
+ /**
48
+ * 处理入站消息的附件列表。
49
+ *
50
+ * 三阶段流水线:
51
+ * 1. 并行下载所有附件到本地
52
+ * 2. 并行处理语音转换 + STT 转录
53
+ * 3. 按原始顺序归类结果
54
+ */
55
+ export declare function processAttachments(attachments: RawAttachment[] | undefined, ctx: ProcessContext): Promise<ProcessedAttachments>;
56
+ /**
57
+ * 将语音转录结果组装为用户消息中的文本片段。
58
+ */
59
+ export declare function formatVoiceText(transcripts: string[]): string;
60
+ export {};