dsh-message-gateway 0.1.33 → 0.1.36
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.en.md +32 -3
- package/README.es.md +32 -3
- package/README.md +33 -3
- package/lib/client.js +114 -27
- package/lib/client.js.map +2 -2
- package/lib/index.js +1105 -80
- package/lib/index.js.map +4 -4
- package/package.json +10 -9
package/lib/index.js
CHANGED
|
@@ -8,19 +8,88 @@ var __export = (target, all) => {
|
|
|
8
8
|
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
9
|
};
|
|
10
10
|
|
|
11
|
+
// src/host/incoming.ts
|
|
12
|
+
async function downloadBytes(url, opts = {}) {
|
|
13
|
+
const { timeoutMs = 6e4, maxBytes = 100 * 1024 * 1024, headers } = opts;
|
|
14
|
+
if (!/^https?:\/\//i.test(url)) throw new Error("\u975E\u6CD5\u4E0B\u8F7D\u5730\u5740");
|
|
15
|
+
const controller = new AbortController();
|
|
16
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
17
|
+
try {
|
|
18
|
+
const response = await fetch(url, { headers, signal: controller.signal });
|
|
19
|
+
if (!response.ok) throw new Error(`\u4E0B\u8F7D\u5931\u8D25 HTTP ${response.status}`);
|
|
20
|
+
const contentLength = Number(response.headers.get("content-length") ?? "0");
|
|
21
|
+
if (contentLength > maxBytes) throw new Error("\u9644\u4EF6\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
22
|
+
const buf = new Uint8Array(await response.arrayBuffer());
|
|
23
|
+
if (buf.byteLength > maxBytes) throw new Error("\u9644\u4EF6\u8D85\u8FC7\u5927\u5C0F\u4E0A\u9650");
|
|
24
|
+
return buf;
|
|
25
|
+
} finally {
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
async function collectStream(stream) {
|
|
30
|
+
const chunks = [];
|
|
31
|
+
let total = 0;
|
|
32
|
+
const iterable = stream;
|
|
33
|
+
for await (const chunk of iterable) {
|
|
34
|
+
chunks.push(chunk);
|
|
35
|
+
total += chunk.byteLength;
|
|
36
|
+
}
|
|
37
|
+
const out = new Uint8Array(total);
|
|
38
|
+
let offset = 0;
|
|
39
|
+
for (const chunk of chunks) {
|
|
40
|
+
out.set(chunk, offset);
|
|
41
|
+
offset += chunk.byteLength;
|
|
42
|
+
}
|
|
43
|
+
return out;
|
|
44
|
+
}
|
|
45
|
+
var init_incoming = __esm({
|
|
46
|
+
"src/host/incoming.ts"() {
|
|
47
|
+
"use strict";
|
|
48
|
+
}
|
|
49
|
+
});
|
|
50
|
+
|
|
11
51
|
// src/host/wechat-ilink-bridge.ts
|
|
12
52
|
var wechat_ilink_bridge_exports = {};
|
|
13
53
|
__export(wechat_ilink_bridge_exports, {
|
|
14
54
|
WechatIlinkBridge: () => WechatIlinkBridge
|
|
15
55
|
});
|
|
16
56
|
import crypto from "node:crypto";
|
|
17
|
-
|
|
57
|
+
function parseIlinkAesKey(aesKeyBase64) {
|
|
58
|
+
const decoded = Buffer.from(aesKeyBase64, "base64");
|
|
59
|
+
if (decoded.length === 16) return decoded;
|
|
60
|
+
if (decoded.length === 32 && /^[0-9a-fA-F]{32}$/.test(decoded.toString("ascii"))) {
|
|
61
|
+
return Buffer.from(decoded.toString("ascii"), "hex");
|
|
62
|
+
}
|
|
63
|
+
throw new Error(`aes_key \u65E0\u6CD5\u8BC6\u522B\uFF08\u89E3\u7801\u540E ${decoded.length} \u5B57\u8282\uFF09`);
|
|
64
|
+
}
|
|
65
|
+
function ilinkMediaUrl(media) {
|
|
66
|
+
if (typeof media.full_url === "string" && media.full_url !== "") return media.full_url;
|
|
67
|
+
const param = typeof media.encrypt_query_param === "string" ? media.encrypt_query_param : "";
|
|
68
|
+
return `${ILINK_CDN_BASE}/download?encrypted_query_param=${encodeURIComponent(param)}`;
|
|
69
|
+
}
|
|
70
|
+
async function downloadIlinkMedia(media) {
|
|
71
|
+
const encrypted = await downloadBytes(ilinkMediaUrl(media), { maxBytes: ILINK_MEDIA_MAX_BYTES });
|
|
72
|
+
const aesKey = typeof media.aes_key === "string" ? media.aes_key : "";
|
|
73
|
+
if (aesKey === "") return encrypted;
|
|
74
|
+
const key = parseIlinkAesKey(aesKey);
|
|
75
|
+
const decipher = crypto.createDecipheriv("aes-128-ecb", key, null);
|
|
76
|
+
return new Uint8Array(Buffer.concat([decipher.update(Buffer.from(encrypted)), decipher.final()]));
|
|
77
|
+
}
|
|
78
|
+
var ILINK_BASE_URL, ILINK_APP_ID, ILINK_CLIENT_VERSION, ILINK_CDN_BASE, ILINK_MEDIA_MAX_BYTES, ITEM_TEXT, ITEM_IMAGE, ITEM_VOICE, ITEM_FILE, ITEM_VIDEO, WechatIlinkBridge;
|
|
18
79
|
var init_wechat_ilink_bridge = __esm({
|
|
19
80
|
"src/host/wechat-ilink-bridge.ts"() {
|
|
20
81
|
"use strict";
|
|
82
|
+
init_incoming();
|
|
21
83
|
ILINK_BASE_URL = "https://ilinkai.weixin.qq.com";
|
|
22
84
|
ILINK_APP_ID = "bot";
|
|
23
85
|
ILINK_CLIENT_VERSION = (2 & 255) << 16 | (4 & 255) << 8 | 8 & 255;
|
|
86
|
+
ILINK_CDN_BASE = "https://novac2c.cdn.weixin.qq.com/c2c";
|
|
87
|
+
ILINK_MEDIA_MAX_BYTES = 100 * 1024 * 1024;
|
|
88
|
+
ITEM_TEXT = 1;
|
|
89
|
+
ITEM_IMAGE = 2;
|
|
90
|
+
ITEM_VOICE = 3;
|
|
91
|
+
ITEM_FILE = 4;
|
|
92
|
+
ITEM_VIDEO = 5;
|
|
24
93
|
WechatIlinkBridge = class _WechatIlinkBridge {
|
|
25
94
|
stopped = false;
|
|
26
95
|
pollController = null;
|
|
@@ -148,7 +217,7 @@ var init_wechat_ilink_bridge = __esm({
|
|
|
148
217
|
const msgs = data.msgs ?? [];
|
|
149
218
|
for (const msg of msgs) {
|
|
150
219
|
if (msg.message_type !== 1) continue;
|
|
151
|
-
this.handleInboundMessage(msg);
|
|
220
|
+
void this.handleInboundMessage(msg);
|
|
152
221
|
}
|
|
153
222
|
} catch (err) {
|
|
154
223
|
if (this.stopped) break;
|
|
@@ -163,18 +232,62 @@ var init_wechat_ilink_bridge = __esm({
|
|
|
163
232
|
/**
|
|
164
233
|
* 处理单条从微信拉取到的消息。
|
|
165
234
|
*/
|
|
166
|
-
handleInboundMessage(msg) {
|
|
235
|
+
async handleInboundMessage(msg) {
|
|
167
236
|
const fromUser = String(msg.from_user_id ?? "");
|
|
168
237
|
if (!fromUser) return;
|
|
169
238
|
let text = "";
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
239
|
+
const attachments = [];
|
|
240
|
+
const notes = [];
|
|
241
|
+
const items = Array.isArray(msg.item_list) ? msg.item_list : [];
|
|
242
|
+
for (const item of items) {
|
|
243
|
+
if (item.type === ITEM_TEXT && item.text_item?.text) {
|
|
244
|
+
text += (text ? "\n" : "") + String(item.text_item.text).trim();
|
|
245
|
+
continue;
|
|
246
|
+
}
|
|
247
|
+
if (item.type === ITEM_IMAGE) {
|
|
248
|
+
const img = item.image_item;
|
|
249
|
+
if (img?.media === void 0) continue;
|
|
250
|
+
try {
|
|
251
|
+
const aesKey = typeof img.aeskey === "string" && img.aeskey !== "" ? Buffer.from(img.aeskey, "hex").toString("base64") : img.media.aes_key;
|
|
252
|
+
const data = await downloadIlinkMedia({ ...img.media, aes_key: aesKey });
|
|
253
|
+
attachments.push({ kind: "image", data });
|
|
254
|
+
} catch (error) {
|
|
255
|
+
notes.push(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
256
|
+
}
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (item.type === ITEM_VOICE) {
|
|
260
|
+
const voice = item.voice_item;
|
|
261
|
+
if (typeof voice?.text === "string" && voice.text.trim() !== "") {
|
|
262
|
+
text += (text ? "\n" : "") + voice.text.trim();
|
|
174
263
|
}
|
|
264
|
+
if (voice?.media !== void 0) {
|
|
265
|
+
try {
|
|
266
|
+
const data = await downloadIlinkMedia(voice.media);
|
|
267
|
+
attachments.push({ kind: "file", data, name: "voice.silk" });
|
|
268
|
+
} catch (error) {
|
|
269
|
+
notes.push(`\uFF08\u8BED\u97F3\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
if (item.type === ITEM_FILE || item.type === ITEM_VIDEO) {
|
|
275
|
+
const node = item.type === ITEM_FILE ? item.file_item : item.video_item;
|
|
276
|
+
if (node?.media === void 0) continue;
|
|
277
|
+
const fallbackName = item.type === ITEM_FILE ? "file.bin" : "video.mp4";
|
|
278
|
+
const name = typeof node.file_name === "string" && node.file_name !== "" ? node.file_name : fallbackName;
|
|
279
|
+
try {
|
|
280
|
+
const data = await downloadIlinkMedia(node.media);
|
|
281
|
+
attachments.push({ kind: "file", data, name });
|
|
282
|
+
} catch (error) {
|
|
283
|
+
notes.push(`\uFF08${item.type === ITEM_FILE ? "\u6587\u4EF6" : "\u89C6\u9891"}\u63A5\u6536\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
284
|
+
}
|
|
285
|
+
continue;
|
|
175
286
|
}
|
|
176
287
|
}
|
|
177
|
-
if (
|
|
288
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
289
|
+
${notes.join("\n")}`;
|
|
290
|
+
if (text === "" && attachments.length === 0) return;
|
|
178
291
|
const contextToken = msg.context_token ?? "";
|
|
179
292
|
const sessionId = msg.session_id || fromUser;
|
|
180
293
|
const frame = {
|
|
@@ -219,7 +332,7 @@ var init_wechat_ilink_bridge = __esm({
|
|
|
219
332
|
sink,
|
|
220
333
|
chatType: msg.group_id ? "group" : "single"
|
|
221
334
|
};
|
|
222
|
-
this.callbacks.onText(text, identity);
|
|
335
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
223
336
|
}
|
|
224
337
|
/**
|
|
225
338
|
* 获取微信用户的 typing_ticket(打字态凭证)。
|
|
@@ -695,6 +808,64 @@ var WecomBridge = class {
|
|
|
695
808
|
const content = frame.body?.text?.content ?? "";
|
|
696
809
|
if (content.trim() !== "") this.callbacks.onText(content, frame);
|
|
697
810
|
});
|
|
811
|
+
client.on("message.image", async (frame) => {
|
|
812
|
+
const img = frame.body?.image;
|
|
813
|
+
if (img?.url === void 0 || img.url === "") return;
|
|
814
|
+
try {
|
|
815
|
+
const { buffer, filename } = await client.downloadFile(img.url, img.aeskey);
|
|
816
|
+
if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
|
|
817
|
+
this.callbacks.onText("", frame, [{ kind: "image", data: new Uint8Array(buffer), name: filename }]);
|
|
818
|
+
} catch (err) {
|
|
819
|
+
this.callbacks.onText(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
|
|
820
|
+
}
|
|
821
|
+
});
|
|
822
|
+
client.on("message.file", async (frame) => {
|
|
823
|
+
const f = frame.body?.file;
|
|
824
|
+
if (f?.url === void 0 || f.url === "") return;
|
|
825
|
+
try {
|
|
826
|
+
const { buffer, filename } = await client.downloadFile(f.url, f.aeskey);
|
|
827
|
+
if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
|
|
828
|
+
this.callbacks.onText("", frame, [{ kind: "file", data: new Uint8Array(buffer), name: filename }]);
|
|
829
|
+
} catch (err) {
|
|
830
|
+
this.callbacks.onText(`\uFF08\u6587\u4EF6\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
|
|
831
|
+
}
|
|
832
|
+
});
|
|
833
|
+
client.on("message.video", async (frame) => {
|
|
834
|
+
const v = frame.body?.video;
|
|
835
|
+
if (v?.url === void 0 || v.url === "") return;
|
|
836
|
+
try {
|
|
837
|
+
const { buffer, filename } = await client.downloadFile(v.url, v.aeskey);
|
|
838
|
+
if (buffer.byteLength === 0) throw new Error("\u4E0B\u8F7D\u7ED3\u679C\u4E3A\u7A7A");
|
|
839
|
+
this.callbacks.onText("", frame, [{ kind: "file", data: new Uint8Array(buffer), name: filename ?? "video.mp4" }]);
|
|
840
|
+
} catch (err) {
|
|
841
|
+
this.callbacks.onText(`\uFF08\u89C6\u9891\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`, frame);
|
|
842
|
+
}
|
|
843
|
+
});
|
|
844
|
+
client.on("message.mixed", async (frame) => {
|
|
845
|
+
const items = frame.body?.mixed?.msg_item ?? [];
|
|
846
|
+
const texts = [];
|
|
847
|
+
const attachments = [];
|
|
848
|
+
for (const item of items) {
|
|
849
|
+
if (item.msgtype === "text") {
|
|
850
|
+
const t = item.text?.content ?? "";
|
|
851
|
+
if (t.trim() !== "") texts.push(t.trim());
|
|
852
|
+
} else if (item.msgtype === "image" && item.image?.url) {
|
|
853
|
+
try {
|
|
854
|
+
const { buffer } = await client.downloadFile(item.image.url, item.image.aeskey);
|
|
855
|
+
if (buffer.byteLength > 0) {
|
|
856
|
+
attachments.push({ kind: "image", data: new Uint8Array(buffer) });
|
|
857
|
+
}
|
|
858
|
+
} catch (err) {
|
|
859
|
+
texts.push(`\uFF08\u56FE\u7247\u63A5\u6536\u5931\u8D25\uFF1A${err instanceof Error ? err.message : String(err)}\uFF09`);
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
this.callbacks.onText(texts.join("\n"), frame, attachments.length > 0 ? attachments : void 0);
|
|
864
|
+
});
|
|
865
|
+
client.on("message.voice", (frame) => {
|
|
866
|
+
const content = frame.body?.voice?.content ?? "";
|
|
867
|
+
if (content.trim() !== "") this.callbacks.onText(content, frame);
|
|
868
|
+
});
|
|
698
869
|
client.on("event.enter_chat", (frame) => {
|
|
699
870
|
this.callbacks.onEnter(frame);
|
|
700
871
|
});
|
|
@@ -779,6 +950,10 @@ import { ProxyAgent, fetch as undiciFetch } from "undici";
|
|
|
779
950
|
var cachedProxyUrl = void 0;
|
|
780
951
|
async function getProxyUrl() {
|
|
781
952
|
if (cachedProxyUrl !== void 0) return cachedProxyUrl;
|
|
953
|
+
if (process.env.DSH_GATEWAY_DISABLE_PROXY === "1") {
|
|
954
|
+
cachedProxyUrl = null;
|
|
955
|
+
return null;
|
|
956
|
+
}
|
|
782
957
|
const envProxy = process.env.https_proxy || process.env.HTTPS_PROXY || process.env.http_proxy || process.env.HTTP_PROXY || process.env.all_proxy || process.env.ALL_PROXY;
|
|
783
958
|
if (envProxy) {
|
|
784
959
|
cachedProxyUrl = envProxy;
|
|
@@ -834,11 +1009,25 @@ async function smartFetch(url, init) {
|
|
|
834
1009
|
json: () => res.json()
|
|
835
1010
|
};
|
|
836
1011
|
}
|
|
1012
|
+
async function smartFetchBinary(url, init) {
|
|
1013
|
+
const urlStr = String(url);
|
|
1014
|
+
const isOverseas = /discord\.com|discordapp\.com|telegram\.org|api\.openai\.com/i.test(urlStr);
|
|
1015
|
+
if (isOverseas) {
|
|
1016
|
+
const dispatcher = await getProxyDispatcher();
|
|
1017
|
+
if (dispatcher) {
|
|
1018
|
+
const res2 = await undiciFetch(urlStr, { ...init, dispatcher });
|
|
1019
|
+
return { status: res2.status, arrayBuffer: () => res2.arrayBuffer() };
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
const res = await fetch(url, init);
|
|
1023
|
+
return { status: res.status, arrayBuffer: () => res.arrayBuffer() };
|
|
1024
|
+
}
|
|
837
1025
|
|
|
838
1026
|
// src/host/telegram-bridge.ts
|
|
839
1027
|
var EDIT_INTERVAL_MS = 1200;
|
|
840
1028
|
var MSG_LIMIT = 4096;
|
|
841
1029
|
var POLL_TIMEOUT = 25;
|
|
1030
|
+
var TG_DOWNLOAD_LIMIT = 20 * 1024 * 1024;
|
|
842
1031
|
var TelegramBridge = class {
|
|
843
1032
|
constructor(token, callbacks) {
|
|
844
1033
|
this.token = token;
|
|
@@ -900,7 +1089,7 @@ var TelegramBridge = class {
|
|
|
900
1089
|
const updates = result;
|
|
901
1090
|
for (const update of updates) {
|
|
902
1091
|
this.offset = Math.max(this.offset, update.update_id + 1);
|
|
903
|
-
if (update.message !== void 0) this.handleMessage(update.message);
|
|
1092
|
+
if (update.message !== void 0) void this.handleMessage(update.message);
|
|
904
1093
|
}
|
|
905
1094
|
} else {
|
|
906
1095
|
this.setStatus("error", "poll failed");
|
|
@@ -908,13 +1097,53 @@ var TelegramBridge = class {
|
|
|
908
1097
|
}
|
|
909
1098
|
if (!this.stopped) this.pollTimer = setTimeout(() => void this.poll(), 0);
|
|
910
1099
|
}
|
|
911
|
-
handleMessage(m) {
|
|
1100
|
+
async handleMessage(m) {
|
|
912
1101
|
const from = m.from;
|
|
913
1102
|
if (from?.is_bot === true) return;
|
|
914
|
-
const text = typeof m.text === "string" ? m.text.trim() : "";
|
|
915
|
-
if (text === "") return;
|
|
916
1103
|
const chat = m.chat;
|
|
917
1104
|
if (chat === void 0) return;
|
|
1105
|
+
const caption = typeof m.caption === "string" ? m.caption.trim() : "";
|
|
1106
|
+
let text = typeof m.text === "string" ? m.text.trim() : "";
|
|
1107
|
+
if (text === "") text = caption;
|
|
1108
|
+
const notes = [];
|
|
1109
|
+
const attachments = [];
|
|
1110
|
+
if (Array.isArray(m.photo) && m.photo.length > 0) {
|
|
1111
|
+
const sizes = m.photo;
|
|
1112
|
+
const best = sizes.reduce((a, b) => {
|
|
1113
|
+
const sa = a.file_size ?? (a.width ?? 0) * (a.height ?? 0);
|
|
1114
|
+
const sb = b.file_size ?? (b.width ?? 0) * (b.height ?? 0);
|
|
1115
|
+
return sb > sa ? b : a;
|
|
1116
|
+
});
|
|
1117
|
+
if (best.file_id !== void 0) {
|
|
1118
|
+
const data = await this.downloadTelegramFile(best.file_id);
|
|
1119
|
+
if (data !== null) attachments.push({ kind: "image", data });
|
|
1120
|
+
else notes.push("\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09");
|
|
1121
|
+
}
|
|
1122
|
+
} else {
|
|
1123
|
+
const mediaKeys = ["animation", "document", "video", "video_note", "voice", "audio", "sticker"];
|
|
1124
|
+
for (const key of mediaKeys) {
|
|
1125
|
+
const media = m[key];
|
|
1126
|
+
if (media?.file_id === void 0) continue;
|
|
1127
|
+
const size = media.file_size ?? 0;
|
|
1128
|
+
if (size > TG_DOWNLOAD_LIMIT) {
|
|
1129
|
+
notes.push(`\uFF08${key} \u8D85\u8FC7\u5B98\u65B9 20MB \u4E0B\u8F7D\u4E0A\u9650\uFF0C\u672A\u4E0B\u8F7D\uFF09`);
|
|
1130
|
+
break;
|
|
1131
|
+
}
|
|
1132
|
+
const data = await this.downloadTelegramFile(media.file_id);
|
|
1133
|
+
if (data !== null) {
|
|
1134
|
+
attachments.push({ kind: "file", data, name: media.file_name, mediaType: media.mime_type });
|
|
1135
|
+
} else {
|
|
1136
|
+
notes.push(`\uFF08${key} \u4E0B\u8F7D\u5931\u8D25\uFF09`);
|
|
1137
|
+
}
|
|
1138
|
+
break;
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
if (text === "" && attachments.length === 0 && notes.length === 0) {
|
|
1142
|
+
const contentKeys = ["contact", "location", "venue", "poll", "dice", "game", "forward_origin"];
|
|
1143
|
+
if (!contentKeys.some((k) => m[k] !== void 0)) return;
|
|
1144
|
+
text = "\uFF08\u6536\u5230\u8BE5\u7C7B\u578B Telegram \u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09";
|
|
1145
|
+
}
|
|
1146
|
+
if (text === "" && notes.length > 0) text = notes.join("\n");
|
|
918
1147
|
const frame = { chatId: chat.id, messageId: m.message_id ?? 0, chatType: chat.type ?? "private" };
|
|
919
1148
|
const sink = {
|
|
920
1149
|
stream: (f, sid, content, finish) => void this.streamReply(f, sid, content, finish)
|
|
@@ -925,8 +1154,26 @@ var TelegramBridge = class {
|
|
|
925
1154
|
sink,
|
|
926
1155
|
chatType: (chat.type ?? "private") === "private" ? "single" : "group"
|
|
927
1156
|
};
|
|
928
|
-
console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60) });
|
|
929
|
-
this.callbacks.onText(text, identity);
|
|
1157
|
+
console.log("[dsh-message-gateway] telegram text", { chatId: chat.id, text: text.slice(0, 60), atts: attachments.length });
|
|
1158
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
1159
|
+
}
|
|
1160
|
+
/** 官方文档:getFile(file_id) → file_path → https://api.telegram.org/file/bot<token>/<file_path>。 */
|
|
1161
|
+
async downloadTelegramFile(fileId) {
|
|
1162
|
+
try {
|
|
1163
|
+
const result = await this.api("getFile", { file_id: fileId });
|
|
1164
|
+
const filePath = result?.result?.file_path;
|
|
1165
|
+
if (filePath === void 0 || filePath === "") return null;
|
|
1166
|
+
const dispatcher = await getProxyDispatcher();
|
|
1167
|
+
const response = await fetch(`https://api.telegram.org/file/bot${this.token}/${filePath}`, {
|
|
1168
|
+
signal: AbortSignal.timeout(6e4),
|
|
1169
|
+
...dispatcher ? { dispatcher } : {}
|
|
1170
|
+
});
|
|
1171
|
+
if (!response.ok) return null;
|
|
1172
|
+
return new Uint8Array(await response.arrayBuffer());
|
|
1173
|
+
} catch (error) {
|
|
1174
|
+
console.warn("[dsh-message-gateway] telegram download failed", fileId, String(error));
|
|
1175
|
+
return null;
|
|
1176
|
+
}
|
|
930
1177
|
}
|
|
931
1178
|
/** 流式回复:状态合并 + 单 worker——首次 sendMessage,随后 editMessageText 渐进更新(限频)。 */
|
|
932
1179
|
async streamReply(frame, streamId, content, finish) {
|
|
@@ -1033,6 +1280,7 @@ var REST = "https://discord.com/api/v10";
|
|
|
1033
1280
|
var INTENTS = 1 << 0 | 1 << 9 | 1 << 12 | 1 << 15;
|
|
1034
1281
|
var EDIT_INTERVAL_MS2 = 1200;
|
|
1035
1282
|
var MSG_LIMIT2 = 2e3;
|
|
1283
|
+
var DISCORD_ATTACH_MAX_BYTES = 50 * 1024 * 1024;
|
|
1036
1284
|
var DiscordBridge = class {
|
|
1037
1285
|
constructor(token, callbacks) {
|
|
1038
1286
|
this.token = token;
|
|
@@ -1115,7 +1363,7 @@ var DiscordBridge = class {
|
|
|
1115
1363
|
this.setStatus("connected", name);
|
|
1116
1364
|
console.log("[dsh-message-gateway] discord READY", name);
|
|
1117
1365
|
} else if (payload.t === "MESSAGE_CREATE") {
|
|
1118
|
-
this.handleMessage(payload.d);
|
|
1366
|
+
void this.handleMessage(payload.d);
|
|
1119
1367
|
}
|
|
1120
1368
|
break;
|
|
1121
1369
|
}
|
|
@@ -1166,11 +1414,37 @@ var DiscordBridge = class {
|
|
|
1166
1414
|
clearTimeout(timer);
|
|
1167
1415
|
}
|
|
1168
1416
|
}
|
|
1169
|
-
handleMessage(d) {
|
|
1417
|
+
async handleMessage(d) {
|
|
1170
1418
|
const author = d.author;
|
|
1171
1419
|
if (author?.bot === true) return;
|
|
1172
|
-
|
|
1173
|
-
|
|
1420
|
+
let text = typeof d.content === "string" ? d.content.trim() : "";
|
|
1421
|
+
const notes = [];
|
|
1422
|
+
const attachments = [];
|
|
1423
|
+
const rawAtts = Array.isArray(d.attachments) ? d.attachments : [];
|
|
1424
|
+
for (const a of rawAtts) {
|
|
1425
|
+
const filename = typeof a.filename === "string" ? a.filename : "\u672A\u77E5";
|
|
1426
|
+
const buf = await this.downloadAttachment(a);
|
|
1427
|
+
if (buf === null) {
|
|
1428
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${filename}\u300D\u4E0B\u8F7D\u5931\u8D25\uFF09`);
|
|
1429
|
+
continue;
|
|
1430
|
+
}
|
|
1431
|
+
const contentType = typeof a.content_type === "string" ? a.content_type : "";
|
|
1432
|
+
attachments.push({
|
|
1433
|
+
kind: contentType.startsWith("image/") ? "image" : "file",
|
|
1434
|
+
data: buf,
|
|
1435
|
+
mediaType: contentType === "" ? void 0 : contentType,
|
|
1436
|
+
name: filename
|
|
1437
|
+
});
|
|
1438
|
+
}
|
|
1439
|
+
const embeds = Array.isArray(d.embeds) ? d.embeds : [];
|
|
1440
|
+
for (const e of embeds) {
|
|
1441
|
+
const title = typeof e.title === "string" ? e.title : "";
|
|
1442
|
+
const url = typeof e.url === "string" ? e.url : "";
|
|
1443
|
+
if (title !== "" || url !== "") notes.push(`\uFF08\u5D4C\u5165\u5185\u5BB9\uFF1A${title} ${url}\uFF09`.replace(/\s+/g, " "));
|
|
1444
|
+
}
|
|
1445
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
1446
|
+
${notes.join("\n")}`;
|
|
1447
|
+
if (text === "" && attachments.length === 0) return;
|
|
1174
1448
|
const channelId = String(d.channel_id ?? "");
|
|
1175
1449
|
if (channelId === "") return;
|
|
1176
1450
|
const guildId = typeof d.guild_id === "string" ? d.guild_id : "";
|
|
@@ -1184,8 +1458,39 @@ var DiscordBridge = class {
|
|
|
1184
1458
|
sink,
|
|
1185
1459
|
chatType: guildId === "" ? "single" : "group"
|
|
1186
1460
|
};
|
|
1187
|
-
console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60) });
|
|
1188
|
-
this.callbacks.onText(text, identity);
|
|
1461
|
+
console.log("[dsh-message-gateway] discord text", { channelId, text: text.slice(0, 60), atts: attachments.length });
|
|
1462
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
1463
|
+
}
|
|
1464
|
+
/**
|
|
1465
|
+
* 下载附件。官方 Reference 明确要求合法的 User-Agent(否则可能被 Cloudflare 拦截);
|
|
1466
|
+
* CDN 是签名 URL,官方未说明是否需要 Bot 鉴权,故先不带鉴权、401/403 时带 token 重试。
|
|
1467
|
+
*/
|
|
1468
|
+
async downloadAttachment(att) {
|
|
1469
|
+
const url = typeof att.url === "string" ? att.url : "";
|
|
1470
|
+
if (url === "") return null;
|
|
1471
|
+
const userAgent = "DiscordBot (https://github.com/a792883583/dsh-message-gateway, 1.0.0)";
|
|
1472
|
+
try {
|
|
1473
|
+
let response = await smartFetchBinary(url, { headers: { "User-Agent": userAgent }, signal: AbortSignal.timeout(6e4) });
|
|
1474
|
+
if (response.status === 401 || response.status === 403) {
|
|
1475
|
+
response = await smartFetchBinary(url, {
|
|
1476
|
+
headers: { "User-Agent": userAgent, authorization: `Bot ${this.token}` },
|
|
1477
|
+
signal: AbortSignal.timeout(6e4)
|
|
1478
|
+
});
|
|
1479
|
+
}
|
|
1480
|
+
if (response.status !== 200) {
|
|
1481
|
+
console.warn("[dsh-message-gateway] discord attachment http", response.status);
|
|
1482
|
+
return null;
|
|
1483
|
+
}
|
|
1484
|
+
const buf = new Uint8Array(await response.arrayBuffer());
|
|
1485
|
+
if (buf.byteLength > DISCORD_ATTACH_MAX_BYTES) {
|
|
1486
|
+
console.warn("[dsh-message-gateway] discord attachment too large", buf.byteLength);
|
|
1487
|
+
return null;
|
|
1488
|
+
}
|
|
1489
|
+
return buf;
|
|
1490
|
+
} catch (error) {
|
|
1491
|
+
console.warn("[dsh-message-gateway] discord attachment failed", String(error));
|
|
1492
|
+
return null;
|
|
1493
|
+
}
|
|
1189
1494
|
}
|
|
1190
1495
|
/** 流式回复:状态合并 + 单 worker——首次发送消息,随后 PATCH 渐进更新(限频)。 */
|
|
1191
1496
|
async streamReply(frame, streamId, content, finish) {
|
|
@@ -1271,11 +1576,47 @@ var DiscordBridge = class {
|
|
|
1271
1576
|
};
|
|
1272
1577
|
|
|
1273
1578
|
// src/host/qq-bridge.ts
|
|
1579
|
+
init_incoming();
|
|
1274
1580
|
import { createPrivateKey, sign, verify } from "node:crypto";
|
|
1275
1581
|
var TOKEN_URL = "https://api.bot.qq.com/app/getAppAccessToken";
|
|
1276
1582
|
var BASE = "https://api.bot.qq.com";
|
|
1277
1583
|
var INTENTS2 = 1 << 25;
|
|
1278
1584
|
var DEDUP_CAP = 64;
|
|
1585
|
+
var QQ_ATTACH_MAX_BYTES = 200 * 1024 * 1024;
|
|
1586
|
+
async function collectQqAttachments(node) {
|
|
1587
|
+
const attachments = [];
|
|
1588
|
+
const asrTexts = [];
|
|
1589
|
+
const notes = [];
|
|
1590
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1591
|
+
const walk = async (item) => {
|
|
1592
|
+
const list = Array.isArray(item.attachments) ? item.attachments : [];
|
|
1593
|
+
for (const a of list) {
|
|
1594
|
+
const url = typeof a.url === "string" ? a.url : "";
|
|
1595
|
+
const name = typeof a.filename === "string" && a.filename !== "" ? a.filename : "\u672A\u77E5";
|
|
1596
|
+
if (typeof a.asr_refer_text === "string" && a.asr_refer_text.trim() !== "") {
|
|
1597
|
+
asrTexts.push(a.asr_refer_text.trim());
|
|
1598
|
+
}
|
|
1599
|
+
if (url === "" || seen.has(url)) continue;
|
|
1600
|
+
seen.add(url);
|
|
1601
|
+
try {
|
|
1602
|
+
const data = await downloadBytes(url, { maxBytes: QQ_ATTACH_MAX_BYTES });
|
|
1603
|
+
const contentType = typeof a.content_type === "string" ? a.content_type : "";
|
|
1604
|
+
attachments.push({
|
|
1605
|
+
kind: contentType.startsWith("image/") ? "image" : "file",
|
|
1606
|
+
data,
|
|
1607
|
+
mediaType: contentType === "" ? void 0 : contentType,
|
|
1608
|
+
name
|
|
1609
|
+
});
|
|
1610
|
+
} catch (error) {
|
|
1611
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${name}\u300D\u4E0B\u8F7D\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
const elements = Array.isArray(item.msg_elements) ? item.msg_elements : [];
|
|
1615
|
+
for (const el of elements) await walk(el);
|
|
1616
|
+
};
|
|
1617
|
+
await walk(node);
|
|
1618
|
+
return { attachments, asrTexts, notes };
|
|
1619
|
+
}
|
|
1279
1620
|
function qqEd25519Key(secret) {
|
|
1280
1621
|
let seed = secret;
|
|
1281
1622
|
while (Buffer.byteLength(seed) < 32) seed += seed;
|
|
@@ -1517,9 +1858,9 @@ var QQBridge = class {
|
|
|
1517
1858
|
this.setStatus("connected", "qq");
|
|
1518
1859
|
console.log("[dsh-message-gateway] qq READY");
|
|
1519
1860
|
} else if (payload.t === "C2C_MESSAGE_CREATE") {
|
|
1520
|
-
this.handleMessage(payload.d, "c2c");
|
|
1861
|
+
void this.handleMessage(payload.d, "c2c");
|
|
1521
1862
|
} else if (payload.t === "GROUP_AT_MESSAGE_CREATE") {
|
|
1522
|
-
this.handleMessage(payload.d, "group");
|
|
1863
|
+
void this.handleMessage(payload.d, "group");
|
|
1523
1864
|
}
|
|
1524
1865
|
break;
|
|
1525
1866
|
}
|
|
@@ -1587,11 +1928,10 @@ var QQBridge = class {
|
|
|
1587
1928
|
}
|
|
1588
1929
|
}
|
|
1589
1930
|
/** 单聊/群聊消息分发(content 群聊已去 @前缀)。 */
|
|
1590
|
-
handleMessage(d, scene) {
|
|
1931
|
+
async handleMessage(d, scene) {
|
|
1591
1932
|
const author = d.author;
|
|
1592
1933
|
if (author?.bot === true) return;
|
|
1593
|
-
|
|
1594
|
-
if (text === "") return;
|
|
1934
|
+
let text = typeof d.content === "string" ? d.content.trim() : "";
|
|
1595
1935
|
const msgId = String(d.id ?? "");
|
|
1596
1936
|
if (msgId === "") return;
|
|
1597
1937
|
if (this.recentMsgIds.has(msgId)) return;
|
|
@@ -1602,6 +1942,12 @@ var QQBridge = class {
|
|
|
1602
1942
|
}
|
|
1603
1943
|
const openid = scene === "c2c" ? author?.user_openid ?? "" : String(d.group_openid ?? "");
|
|
1604
1944
|
if (openid === "") return;
|
|
1945
|
+
const { attachments, asrTexts, notes } = await collectQqAttachments(d);
|
|
1946
|
+
if (asrTexts.length > 0) text = text === "" ? asrTexts.join("\n") : `${text}
|
|
1947
|
+
${asrTexts.join("\n")}`;
|
|
1948
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
1949
|
+
${notes.join("\n")}`;
|
|
1950
|
+
if (text === "" && attachments.length === 0) return;
|
|
1605
1951
|
const frame = { openid, msgId, scene };
|
|
1606
1952
|
const sink = {
|
|
1607
1953
|
// 单聊:流式(ack 开启,「正在处理…」就地增长);群聊:不支持流式,关闭 ack 只发定稿。
|
|
@@ -1615,8 +1961,8 @@ var QQBridge = class {
|
|
|
1615
1961
|
sink,
|
|
1616
1962
|
chatType: scene === "c2c" ? "single" : "group"
|
|
1617
1963
|
};
|
|
1618
|
-
console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60) });
|
|
1619
|
-
this.callbacks.onText(text, identity);
|
|
1964
|
+
console.log("[dsh-message-gateway] qq text", { scene, openid, text: text.slice(0, 60), atts: attachments.length });
|
|
1965
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
1620
1966
|
}
|
|
1621
1967
|
/** 停止网关连接。 */
|
|
1622
1968
|
stop() {
|
|
@@ -1699,8 +2045,17 @@ var QqWebhookBridge = class {
|
|
|
1699
2045
|
sink,
|
|
1700
2046
|
chatType: scene === "c2c" ? "single" : "group"
|
|
1701
2047
|
};
|
|
1702
|
-
|
|
1703
|
-
|
|
2048
|
+
void (async () => {
|
|
2049
|
+
let body = typeof d.content === "string" ? d.content.trim() : "";
|
|
2050
|
+
const { attachments, asrTexts, notes } = await collectQqAttachments(d);
|
|
2051
|
+
if (asrTexts.length > 0) body = body === "" ? asrTexts.join("\n") : `${body}
|
|
2052
|
+
${asrTexts.join("\n")}`;
|
|
2053
|
+
if (notes.length > 0) body = body === "" ? notes.join("\n") : `${body}
|
|
2054
|
+
${notes.join("\n")}`;
|
|
2055
|
+
if (body === "" && attachments.length === 0) return;
|
|
2056
|
+
console.log("[dsh-message-gateway] qq webhook text", { scene, openid, text: body.slice(0, 60), atts: attachments.length });
|
|
2057
|
+
this.callbacks.onText(body, identity, attachments.length > 0 ? attachments : void 0);
|
|
2058
|
+
})();
|
|
1704
2059
|
return true;
|
|
1705
2060
|
}
|
|
1706
2061
|
/** 确保 access_token 未过期(提前 60s 刷新)。 */
|
|
@@ -1756,6 +2111,250 @@ var QqWebhookBridge = class {
|
|
|
1756
2111
|
// src/host/email-bridge.ts
|
|
1757
2112
|
import { connect } from "node:net";
|
|
1758
2113
|
import { connect as tlsConnect } from "node:tls";
|
|
2114
|
+
|
|
2115
|
+
// src/host/email-mime.ts
|
|
2116
|
+
function tokenize(text) {
|
|
2117
|
+
let i = 0;
|
|
2118
|
+
const parseList = () => {
|
|
2119
|
+
if (text[i] !== "(") return null;
|
|
2120
|
+
i += 1;
|
|
2121
|
+
const out = [];
|
|
2122
|
+
while (i < text.length) {
|
|
2123
|
+
const c = text[i];
|
|
2124
|
+
if (c === " " || c === "\r" || c === "\n" || c === " ") {
|
|
2125
|
+
i += 1;
|
|
2126
|
+
continue;
|
|
2127
|
+
}
|
|
2128
|
+
if (c === ")") {
|
|
2129
|
+
i += 1;
|
|
2130
|
+
return out;
|
|
2131
|
+
}
|
|
2132
|
+
if (c === "(") {
|
|
2133
|
+
const inner = parseList();
|
|
2134
|
+
if (inner === null) return null;
|
|
2135
|
+
out.push(inner);
|
|
2136
|
+
continue;
|
|
2137
|
+
}
|
|
2138
|
+
if (c === '"') {
|
|
2139
|
+
i += 1;
|
|
2140
|
+
let s = "";
|
|
2141
|
+
while (i < text.length && text[i] !== '"') {
|
|
2142
|
+
if (text[i] === "\\" && i + 1 < text.length) {
|
|
2143
|
+
i += 1;
|
|
2144
|
+
s += text[i];
|
|
2145
|
+
i += 1;
|
|
2146
|
+
continue;
|
|
2147
|
+
}
|
|
2148
|
+
s += text[i];
|
|
2149
|
+
i += 1;
|
|
2150
|
+
}
|
|
2151
|
+
i += 1;
|
|
2152
|
+
out.push(s);
|
|
2153
|
+
continue;
|
|
2154
|
+
}
|
|
2155
|
+
let atom = "";
|
|
2156
|
+
while (i < text.length && !" ()\r\n ".includes(text[i])) {
|
|
2157
|
+
atom += text[i];
|
|
2158
|
+
i += 1;
|
|
2159
|
+
}
|
|
2160
|
+
out.push(atom.toUpperCase() === "NIL" ? null : atom);
|
|
2161
|
+
}
|
|
2162
|
+
return out;
|
|
2163
|
+
};
|
|
2164
|
+
while (i < text.length && /\s/.test(text[i])) i += 1;
|
|
2165
|
+
return parseList();
|
|
2166
|
+
}
|
|
2167
|
+
function asParams(tok) {
|
|
2168
|
+
const out = {};
|
|
2169
|
+
if (!Array.isArray(tok)) return out;
|
|
2170
|
+
for (let i = 0; i + 1 < tok.length; i += 2) {
|
|
2171
|
+
const k = tok[i];
|
|
2172
|
+
const v = tok[i + 1];
|
|
2173
|
+
if (typeof k === "string" && typeof v === "string") out[k.toLowerCase()] = v;
|
|
2174
|
+
}
|
|
2175
|
+
return out;
|
|
2176
|
+
}
|
|
2177
|
+
function pctToBuffer(s) {
|
|
2178
|
+
const bytes = [];
|
|
2179
|
+
for (let i = 0; i < s.length; i += 1) {
|
|
2180
|
+
if (s[i] === "%" && i + 2 < s.length) {
|
|
2181
|
+
const hex = s.slice(i + 1, i + 3);
|
|
2182
|
+
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
|
2183
|
+
bytes.push(parseInt(hex, 16));
|
|
2184
|
+
i += 2;
|
|
2185
|
+
continue;
|
|
2186
|
+
}
|
|
2187
|
+
}
|
|
2188
|
+
bytes.push(s.charCodeAt(i) & 255);
|
|
2189
|
+
}
|
|
2190
|
+
return Buffer.from(bytes);
|
|
2191
|
+
}
|
|
2192
|
+
function bufferToString(buf, charset) {
|
|
2193
|
+
const cs = charset.trim().toLowerCase();
|
|
2194
|
+
if (cs === "iso-8859-1" || cs === "latin1" || cs === "windows-1252") return buf.toString("latin1");
|
|
2195
|
+
if (cs === "us-ascii" || cs === "ascii") return buf.toString("ascii");
|
|
2196
|
+
return buf.toString("utf8");
|
|
2197
|
+
}
|
|
2198
|
+
function decodeRfc2231(value) {
|
|
2199
|
+
const m = value.match(/^([^']*)'([^']*)'(.*)$/);
|
|
2200
|
+
const charset = m === null ? "utf-8" : m[1];
|
|
2201
|
+
const encoded = m === null ? value : m[3];
|
|
2202
|
+
return bufferToString(pctToBuffer(encoded), charset);
|
|
2203
|
+
}
|
|
2204
|
+
function decodeEncodedWords(value) {
|
|
2205
|
+
return value.replace(/=\?([^?]+)\?([BbQq])\?([^?]*)\?=/g, (_all, charset, enc, text) => {
|
|
2206
|
+
try {
|
|
2207
|
+
if (enc.toUpperCase() === "B") return bufferToString(Buffer.from(text, "base64"), charset);
|
|
2208
|
+
const qp = text.replace(/_/g, " ").replace(/=([0-9A-Fa-f]{2})/g, (_x, h) => String.fromCharCode(parseInt(h, 16)));
|
|
2209
|
+
return bufferToString(Buffer.from(qp, "latin1"), charset);
|
|
2210
|
+
} catch {
|
|
2211
|
+
return text;
|
|
2212
|
+
}
|
|
2213
|
+
});
|
|
2214
|
+
}
|
|
2215
|
+
function paramValue(params, base) {
|
|
2216
|
+
const single = params[`${base}*`];
|
|
2217
|
+
if (single !== void 0) return { value: single, extended: true };
|
|
2218
|
+
const parts = [];
|
|
2219
|
+
const re = new RegExp(`^${base}\\*(\\d+)(\\*)?$`);
|
|
2220
|
+
for (const [k, v] of Object.entries(params)) {
|
|
2221
|
+
const m = k.match(re);
|
|
2222
|
+
if (m !== null) parts.push({ i: Number(m[1]), v, ext: m[2] === "*" });
|
|
2223
|
+
}
|
|
2224
|
+
if (parts.length > 0) {
|
|
2225
|
+
parts.sort((a, b) => a.i - b.i);
|
|
2226
|
+
return { value: parts.map((p) => p.v).join(""), extended: parts[0].ext };
|
|
2227
|
+
}
|
|
2228
|
+
const plain = params[base];
|
|
2229
|
+
return plain === void 0 ? null : { value: plain, extended: false };
|
|
2230
|
+
}
|
|
2231
|
+
function sanitizeFilename(name) {
|
|
2232
|
+
const base = name.split(/[\\/]/).pop() ?? name;
|
|
2233
|
+
const cleaned = base.replace(/[\u0000-\u001f\u007f]/g, "").trim();
|
|
2234
|
+
return cleaned === "" ? "attachment" : cleaned;
|
|
2235
|
+
}
|
|
2236
|
+
function pickFilename(params) {
|
|
2237
|
+
for (const base of ["filename", "name"]) {
|
|
2238
|
+
const hit = paramValue(params, base);
|
|
2239
|
+
if (hit === null) continue;
|
|
2240
|
+
const decoded = hit.extended ? decodeRfc2231(hit.value) : decodeEncodedWords(hit.value);
|
|
2241
|
+
if (decoded.trim() !== "") return sanitizeFilename(decoded);
|
|
2242
|
+
}
|
|
2243
|
+
return "";
|
|
2244
|
+
}
|
|
2245
|
+
function interpret(sexp, prefix) {
|
|
2246
|
+
if (!Array.isArray(sexp) || sexp.length === 0) return null;
|
|
2247
|
+
if (Array.isArray(sexp[0])) {
|
|
2248
|
+
const children = [];
|
|
2249
|
+
let idx = 0;
|
|
2250
|
+
while (idx < sexp.length && Array.isArray(sexp[idx])) {
|
|
2251
|
+
const childPart = prefix === "" ? String(children.length + 1) : `${prefix}.${children.length + 1}`;
|
|
2252
|
+
const child = interpret(sexp[idx], childPart);
|
|
2253
|
+
if (child !== null) children.push(child);
|
|
2254
|
+
idx += 1;
|
|
2255
|
+
}
|
|
2256
|
+
const subtypeRaw = sexp[idx];
|
|
2257
|
+
const subtype2 = typeof subtypeRaw === "string" ? subtypeRaw.toLowerCase() : "mixed";
|
|
2258
|
+
const params2 = asParams(sexp[idx + 1]);
|
|
2259
|
+
return {
|
|
2260
|
+
part: prefix,
|
|
2261
|
+
type: "multipart",
|
|
2262
|
+
subtype: subtype2,
|
|
2263
|
+
params: params2,
|
|
2264
|
+
id: "",
|
|
2265
|
+
encoding: "",
|
|
2266
|
+
octets: 0,
|
|
2267
|
+
disposition: "",
|
|
2268
|
+
filename: "",
|
|
2269
|
+
children
|
|
2270
|
+
};
|
|
2271
|
+
}
|
|
2272
|
+
const type = typeof sexp[0] === "string" ? sexp[0].toLowerCase() : "application";
|
|
2273
|
+
const subtype = typeof sexp[1] === "string" ? sexp[1].toLowerCase() : "octet-stream";
|
|
2274
|
+
const params = asParams(sexp[2]);
|
|
2275
|
+
const id = typeof sexp[3] === "string" ? sexp[3].replace(/^<|>$/g, "") : "";
|
|
2276
|
+
const encoding = typeof sexp[5] === "string" ? sexp[5].toLowerCase() : "7bit";
|
|
2277
|
+
const octets = Number(sexp[6] ?? 0) || 0;
|
|
2278
|
+
let disposition = "";
|
|
2279
|
+
let dispParams = {};
|
|
2280
|
+
for (let i = 7; i < sexp.length; i += 1) {
|
|
2281
|
+
const el = sexp[i];
|
|
2282
|
+
if (Array.isArray(el) && el.length >= 1 && typeof el[0] === "string") {
|
|
2283
|
+
disposition = el[0].toLowerCase();
|
|
2284
|
+
dispParams = asParams(el[1]);
|
|
2285
|
+
break;
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
const merged = { ...params, ...dispParams };
|
|
2289
|
+
return {
|
|
2290
|
+
part: prefix === "" ? "1" : prefix,
|
|
2291
|
+
type,
|
|
2292
|
+
subtype,
|
|
2293
|
+
params: merged,
|
|
2294
|
+
id,
|
|
2295
|
+
encoding,
|
|
2296
|
+
octets,
|
|
2297
|
+
disposition,
|
|
2298
|
+
filename: pickFilename(merged),
|
|
2299
|
+
children: []
|
|
2300
|
+
};
|
|
2301
|
+
}
|
|
2302
|
+
function parseBodyStructure(sexp) {
|
|
2303
|
+
const tok = tokenize(sexp);
|
|
2304
|
+
if (tok === null) return null;
|
|
2305
|
+
return interpret(tok, "");
|
|
2306
|
+
}
|
|
2307
|
+
function flattenParts(root) {
|
|
2308
|
+
if (root === null) return [];
|
|
2309
|
+
const out = [];
|
|
2310
|
+
const walk = (node) => {
|
|
2311
|
+
if (node.children.length > 0) {
|
|
2312
|
+
for (const c of node.children) walk(c);
|
|
2313
|
+
return;
|
|
2314
|
+
}
|
|
2315
|
+
out.push(node);
|
|
2316
|
+
};
|
|
2317
|
+
walk(root);
|
|
2318
|
+
return out;
|
|
2319
|
+
}
|
|
2320
|
+
function decodeBody(raw, encoding) {
|
|
2321
|
+
const enc = encoding.toLowerCase();
|
|
2322
|
+
if (enc === "base64") {
|
|
2323
|
+
return new Uint8Array(Buffer.from(raw.replace(/[^A-Za-z0-9+/=]/g, ""), "base64"));
|
|
2324
|
+
}
|
|
2325
|
+
if (enc === "quoted-printable") {
|
|
2326
|
+
const bytes = [];
|
|
2327
|
+
for (let i = 0; i < raw.length; i += 1) {
|
|
2328
|
+
if (raw[i] === "=") {
|
|
2329
|
+
if (raw[i + 1] === "\r" && raw[i + 2] === "\n") {
|
|
2330
|
+
i += 2;
|
|
2331
|
+
continue;
|
|
2332
|
+
}
|
|
2333
|
+
if (raw[i + 1] === "\n") {
|
|
2334
|
+
i += 1;
|
|
2335
|
+
continue;
|
|
2336
|
+
}
|
|
2337
|
+
const hex = raw.slice(i + 1, i + 3);
|
|
2338
|
+
if (/^[0-9a-fA-F]{2}$/.test(hex)) {
|
|
2339
|
+
bytes.push(parseInt(hex, 16));
|
|
2340
|
+
i += 2;
|
|
2341
|
+
continue;
|
|
2342
|
+
}
|
|
2343
|
+
}
|
|
2344
|
+
bytes.push(raw.charCodeAt(i) & 255);
|
|
2345
|
+
}
|
|
2346
|
+
return new Uint8Array(Buffer.from(bytes));
|
|
2347
|
+
}
|
|
2348
|
+
return new Uint8Array(Buffer.from(raw, "latin1"));
|
|
2349
|
+
}
|
|
2350
|
+
|
|
2351
|
+
// src/host/email-bridge.ts
|
|
2352
|
+
function isSenderAllowed(from, allowed) {
|
|
2353
|
+
const list = (allowed ?? "").split(",").map((s) => s.trim().toLowerCase()).filter((s) => s !== "");
|
|
2354
|
+
if (list.length === 0) return true;
|
|
2355
|
+
return list.includes((from ?? "").trim().toLowerCase());
|
|
2356
|
+
}
|
|
2357
|
+
var EMAIL_ATTACH_MAX_BYTES = 25 * 1024 * 1024;
|
|
1759
2358
|
var POLL_MS = 3e4;
|
|
1760
2359
|
var RETRY_MS = 5e3;
|
|
1761
2360
|
var MAX_BODY = 12e3;
|
|
@@ -1919,6 +2518,49 @@ var ImapClient = class {
|
|
|
1919
2518
|
const text = literalAt(res, "BODY[TEXT]")?.value ?? "";
|
|
1920
2519
|
return { uid, header, text };
|
|
1921
2520
|
}
|
|
2521
|
+
/**
|
|
2522
|
+
* 取 BODYSTRUCTURE(RFC 3501 §6.4.5):一次拿到整棵 MIME 树,
|
|
2523
|
+
* 含每个 part 的类型/参数/ID/编码/字节数与 Content-Disposition,
|
|
2524
|
+
* 便于在下载正文前判断哪些是附件。BODY.PEEK 不置 \Seen。
|
|
2525
|
+
*/
|
|
2526
|
+
async fetchStructure(id) {
|
|
2527
|
+
let res;
|
|
2528
|
+
try {
|
|
2529
|
+
res = await this.command(`FETCH ${id} (UID BODYSTRUCTURE)`, 3e4);
|
|
2530
|
+
} catch {
|
|
2531
|
+
return null;
|
|
2532
|
+
}
|
|
2533
|
+
const idx = res.indexOf("BODYSTRUCTURE");
|
|
2534
|
+
if (idx === -1) return null;
|
|
2535
|
+
const start = res.indexOf("(", idx);
|
|
2536
|
+
if (start === -1) return null;
|
|
2537
|
+
let depth = 0;
|
|
2538
|
+
for (let i = start; i < res.length; i += 1) {
|
|
2539
|
+
const c = res[i];
|
|
2540
|
+
if (c === '"') {
|
|
2541
|
+
i += 1;
|
|
2542
|
+
while (i < res.length && res[i] !== '"') {
|
|
2543
|
+
if (res[i] === "\\") i += 1;
|
|
2544
|
+
i += 1;
|
|
2545
|
+
}
|
|
2546
|
+
continue;
|
|
2547
|
+
}
|
|
2548
|
+
if (c === "(") depth += 1;
|
|
2549
|
+
else if (c === ")") {
|
|
2550
|
+
depth -= 1;
|
|
2551
|
+
if (depth === 0) return parseBodyStructure(res.slice(start, i + 1));
|
|
2552
|
+
}
|
|
2553
|
+
}
|
|
2554
|
+
return null;
|
|
2555
|
+
}
|
|
2556
|
+
/**
|
|
2557
|
+
* 拉取指定 part 的正文(原始编码,尚未 base64/QP 解码)。
|
|
2558
|
+
* RFC 3501 §6.4.5:必须用 BODY.PEEK 以免把邮件标记为已读。
|
|
2559
|
+
*/
|
|
2560
|
+
async fetchPart(id, part) {
|
|
2561
|
+
const res = await this.command(`FETCH ${id} (BODY.PEEK[${part}])`, 6e4);
|
|
2562
|
+
return literalAt(res, `BODY[${part}]`)?.value ?? "";
|
|
2563
|
+
}
|
|
1922
2564
|
async markSeen(id) {
|
|
1923
2565
|
await this.command(`STORE ${id} +FLAGS (\\Seen)`);
|
|
1924
2566
|
}
|
|
@@ -2217,10 +2859,60 @@ var EmailBridge = class {
|
|
|
2217
2859
|
const threadKey = references[0] ?? (inReplyTo !== "" ? inReplyTo : messageId);
|
|
2218
2860
|
const from = parseAddress(headerField(fetched.header, "From"));
|
|
2219
2861
|
const subject = headerField(fetched.header, "Subject");
|
|
2220
|
-
const
|
|
2862
|
+
const root = await this.imap.fetchStructure(id);
|
|
2863
|
+
const parts = flattenParts(root);
|
|
2864
|
+
const notes = [];
|
|
2865
|
+
const attachments = [];
|
|
2866
|
+
const textNode = parts.find((p) => p.type === "text" && p.subtype === "plain");
|
|
2867
|
+
let text = "";
|
|
2868
|
+
if (textNode !== void 0) {
|
|
2869
|
+
try {
|
|
2870
|
+
const raw = await this.imap.fetchPart(id, textNode.part);
|
|
2871
|
+
text = cleanBody(Buffer.from(decodeBody(raw, textNode.encoding)).toString("utf8"));
|
|
2872
|
+
} catch {
|
|
2873
|
+
notes.push("\uFF08\u6B63\u6587\u8BFB\u53D6\u5931\u8D25\uFF0C\u5DF2\u56DE\u9000\u5230\u539F\u59CB\u6B63\u6587\uFF09");
|
|
2874
|
+
}
|
|
2875
|
+
}
|
|
2876
|
+
if (text.trim() === "") text = cleanBody(fetched.text);
|
|
2877
|
+
for (const p of parts) {
|
|
2878
|
+
if (p === textNode) continue;
|
|
2879
|
+
const isAttachment = p.disposition === "attachment" || p.disposition === "" && p.filename !== "" || p.disposition !== "inline" && p.filename !== "" && p.disposition !== "attachment";
|
|
2880
|
+
if (!isAttachment) continue;
|
|
2881
|
+
if (p.filename === "") continue;
|
|
2882
|
+
if (p.octets > EMAIL_ATTACH_MAX_BYTES) {
|
|
2883
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u7EA6 ${Math.round(p.octets / 1024 / 1024)}MB\uFF0C\u8D85\u8FC7\u4E0A\u9650\u672A\u4E0B\u8F7D\uFF09`);
|
|
2884
|
+
continue;
|
|
2885
|
+
}
|
|
2886
|
+
try {
|
|
2887
|
+
const raw = await this.imap.fetchPart(id, p.part);
|
|
2888
|
+
const data = decodeBody(raw, p.encoding);
|
|
2889
|
+
if (data.byteLength === 0) {
|
|
2890
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u4E3A\u7A7A\uFF09`);
|
|
2891
|
+
continue;
|
|
2892
|
+
}
|
|
2893
|
+
attachments.push({
|
|
2894
|
+
kind: p.type === "image" ? "image" : "file",
|
|
2895
|
+
data,
|
|
2896
|
+
mediaType: p.type === "image" ? `image/${p.subtype}` : `${p.type}/${p.subtype}`,
|
|
2897
|
+
name: p.filename
|
|
2898
|
+
});
|
|
2899
|
+
} catch (error) {
|
|
2900
|
+
notes.push(`\uFF08\u9644\u4EF6\u300C${p.filename}\u300D\u8BFB\u53D6\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`);
|
|
2901
|
+
}
|
|
2902
|
+
}
|
|
2221
2903
|
void this.imap.markSeen(id).catch(() => {
|
|
2222
2904
|
});
|
|
2223
|
-
if (
|
|
2905
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
2906
|
+
${notes.join("\n")}`;
|
|
2907
|
+
if (from === "" || text.trim() === "" && attachments.length === 0) return;
|
|
2908
|
+
if (!isSenderAllowed(from, this.cred.allowedSenders)) {
|
|
2909
|
+
console.warn("[dsh-message-gateway] email dropped by sender allowlist", {
|
|
2910
|
+
from,
|
|
2911
|
+
subject: subject.slice(0, 40),
|
|
2912
|
+
hint: "\u82E5\u975E\u9884\u671F\uFF0C\u8BF7\u68C0\u67E5\u8BE5\u90AE\u7BB1\u51ED\u636E\u7684 allowedSenders \u914D\u7F6E"
|
|
2913
|
+
});
|
|
2914
|
+
return;
|
|
2915
|
+
}
|
|
2224
2916
|
const frame = { from, subject, threadKey };
|
|
2225
2917
|
const sink = {
|
|
2226
2918
|
ack: false,
|
|
@@ -2236,8 +2928,8 @@ var EmailBridge = class {
|
|
|
2236
2928
|
sink,
|
|
2237
2929
|
chatType: "single"
|
|
2238
2930
|
};
|
|
2239
|
-
console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length });
|
|
2240
|
-
this.callbacks.onText(text, identity);
|
|
2931
|
+
console.log("[dsh-message-gateway] email text", { from, subject: subject.slice(0, 40), len: text.length, atts: attachments.length });
|
|
2932
|
+
this.callbacks.onText(text, identity, attachments.length > 0 ? attachments : void 0);
|
|
2241
2933
|
}
|
|
2242
2934
|
async sendReply(frame, content) {
|
|
2243
2935
|
try {
|
|
@@ -2282,7 +2974,9 @@ function sleep(ms) {
|
|
|
2282
2974
|
}
|
|
2283
2975
|
|
|
2284
2976
|
// src/host/feishu-bridge.ts
|
|
2977
|
+
init_incoming();
|
|
2285
2978
|
import * as lark from "@larksuiteoapi/node-sdk";
|
|
2979
|
+
var FEISHU_TEXT_TYPES = /* @__PURE__ */ new Set(["text"]);
|
|
2286
2980
|
var FeishuBridge = class {
|
|
2287
2981
|
constructor(cred, callbacks) {
|
|
2288
2982
|
this.cred = cred;
|
|
@@ -2318,23 +3012,66 @@ var FeishuBridge = class {
|
|
|
2318
3012
|
"im.message.receive_v1": async (data) => {
|
|
2319
3013
|
try {
|
|
2320
3014
|
const msg = data.message;
|
|
2321
|
-
if (!msg
|
|
2322
|
-
const
|
|
2323
|
-
|
|
2324
|
-
|
|
2325
|
-
|
|
2326
|
-
|
|
2327
|
-
|
|
3015
|
+
if (!msg) return;
|
|
3016
|
+
const messageId = msg.message_id;
|
|
3017
|
+
const messageType = msg.message_type;
|
|
3018
|
+
let text = "";
|
|
3019
|
+
const attachments = [];
|
|
3020
|
+
if (FEISHU_TEXT_TYPES.has(messageType)) {
|
|
3021
|
+
const parsedContent = JSON.parse(msg.content || "{}");
|
|
3022
|
+
text = parsedContent.text || "";
|
|
3023
|
+
if (msg.chat_type === "group" && Array.isArray(msg.mentions)) {
|
|
3024
|
+
for (const mention of msg.mentions) {
|
|
3025
|
+
if (mention.key) {
|
|
3026
|
+
text = text.replace(new RegExp(mention.key, "g"), "").trim();
|
|
3027
|
+
}
|
|
2328
3028
|
}
|
|
2329
3029
|
}
|
|
3030
|
+
} else if (messageType === "image") {
|
|
3031
|
+
const parsed = JSON.parse(msg.content || "{}");
|
|
3032
|
+
if (parsed.image_key !== void 0) {
|
|
3033
|
+
const data2 = await this.downloadMessageResource(messageId, parsed.image_key, "image");
|
|
3034
|
+
if (data2 === null) text = "\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09";
|
|
3035
|
+
else attachments.push({ kind: "image", data: data2, name: `${parsed.image_key}.img` });
|
|
3036
|
+
}
|
|
3037
|
+
} else if (messageType === "file" || messageType === "audio" || messageType === "media") {
|
|
3038
|
+
const parsed = JSON.parse(msg.content || "{}");
|
|
3039
|
+
if (parsed.file_key !== void 0) {
|
|
3040
|
+
const data2 = await this.downloadMessageResource(messageId, parsed.file_key, "file");
|
|
3041
|
+
if (data2 === null) text = "\uFF08\u6587\u4EF6\u4E0B\u8F7D\u5931\u8D25\uFF09";
|
|
3042
|
+
else attachments.push({ kind: "file", data: data2, name: parsed.file_name ?? `${parsed.file_key}.bin` });
|
|
3043
|
+
}
|
|
3044
|
+
} else if (messageType === "post") {
|
|
3045
|
+
const parsed = JSON.parse(msg.content || "{}");
|
|
3046
|
+
const rows = parsed.content_v2 ?? parsed.content ?? [];
|
|
3047
|
+
const texts = [];
|
|
3048
|
+
for (const row of rows) {
|
|
3049
|
+
for (const node of row) {
|
|
3050
|
+
if (node.tag === "text" && typeof node.text === "string") texts.push(node.text);
|
|
3051
|
+
else if (node.tag === "img" && node.image_key !== void 0) {
|
|
3052
|
+
const data2 = await this.downloadMessageResource(messageId, node.image_key, "image");
|
|
3053
|
+
if (data2 !== null) attachments.push({ kind: "image", data: data2, name: `${node.image_key}.img` });
|
|
3054
|
+
}
|
|
3055
|
+
}
|
|
3056
|
+
}
|
|
3057
|
+
text = texts.join("");
|
|
3058
|
+
} else if (messageType === "sticker") {
|
|
3059
|
+
text = "\uFF08\u6536\u5230\u8868\u60C5\u5305\u6D88\u606F\uFF1A\u98DE\u4E66\u4E0D\u652F\u6301\u4E0B\u8F7D\u8868\u60C5\u5305\u8D44\u6E90\uFF0C\u65E0\u6CD5\u5904\u7406\uFF09";
|
|
3060
|
+
} else {
|
|
3061
|
+
text = `\uFF08\u6536\u5230\u98DE\u4E66\u300C${messageType}\u300D\u7C7B\u578B\u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09`;
|
|
2330
3062
|
}
|
|
2331
|
-
|
|
2332
|
-
|
|
2333
|
-
|
|
2334
|
-
|
|
2335
|
-
|
|
2336
|
-
|
|
2337
|
-
|
|
3063
|
+
text = text.trim();
|
|
3064
|
+
if (text === "" && attachments.length === 0) return;
|
|
3065
|
+
this.callbacks.onText(
|
|
3066
|
+
text,
|
|
3067
|
+
{
|
|
3068
|
+
chatId: msg.chat_id,
|
|
3069
|
+
messageId,
|
|
3070
|
+
senderId: data.sender?.sender_id?.user_id || data.sender?.sender_id?.open_id || "",
|
|
3071
|
+
chatType: msg.chat_type === "group" ? "group" : "single"
|
|
3072
|
+
},
|
|
3073
|
+
attachments.length > 0 ? attachments : void 0
|
|
3074
|
+
);
|
|
2338
3075
|
} catch (err) {
|
|
2339
3076
|
console.error("[dsh-message-gateway] feishu message parsing error", err);
|
|
2340
3077
|
}
|
|
@@ -2353,6 +3090,31 @@ var FeishuBridge = class {
|
|
|
2353
3090
|
this.setStatus("error", error instanceof Error ? error.message : String(error));
|
|
2354
3091
|
}
|
|
2355
3092
|
}
|
|
3093
|
+
/**
|
|
3094
|
+
* 下载消息中的资源文件。
|
|
3095
|
+
*
|
|
3096
|
+
* 官方文档:必须使用「获取消息中的资源文件」
|
|
3097
|
+
* `GET /open-apis/im/v1/messages/:message_id/resources/:file_key`——
|
|
3098
|
+
* **不能**用 `im/v1/images/:image_key`(后者只能下载机器人自己上传的图片,
|
|
3099
|
+
* 下载用户发来的图会报 234008)。图片把 image_key 的值填到 file_key 位置。
|
|
3100
|
+
*
|
|
3101
|
+
* @param messageId 消息 ID
|
|
3102
|
+
* @param fileKey 图片传 image_key;文件/音频/视频传 file_key
|
|
3103
|
+
* @param type image=图片(含富文本图片);file=文件/音频/视频
|
|
3104
|
+
*/
|
|
3105
|
+
async downloadMessageResource(messageId, fileKey, type) {
|
|
3106
|
+
if (this.client === null) return null;
|
|
3107
|
+
try {
|
|
3108
|
+
const res = await this.client.im.messageResource.get({
|
|
3109
|
+
params: { type },
|
|
3110
|
+
path: { message_id: messageId, file_key: fileKey }
|
|
3111
|
+
});
|
|
3112
|
+
return await collectStream(res.getReadableStream());
|
|
3113
|
+
} catch (error) {
|
|
3114
|
+
console.warn("[dsh-message-gateway] feishu resource download failed", fileKey, String(error));
|
|
3115
|
+
return null;
|
|
3116
|
+
}
|
|
3117
|
+
}
|
|
2356
3118
|
/**
|
|
2357
3119
|
* 回复某条消息(通过 message_id 引用回复)。
|
|
2358
3120
|
*/
|
|
@@ -2406,6 +3168,7 @@ var FeishuBridge = class {
|
|
|
2406
3168
|
};
|
|
2407
3169
|
|
|
2408
3170
|
// src/host/dingtalk-bridge.ts
|
|
3171
|
+
init_incoming();
|
|
2409
3172
|
import { DWClient, TOPIC_ROBOT } from "dingtalk-stream";
|
|
2410
3173
|
var DingTalkBridge = class {
|
|
2411
3174
|
constructor(cred, callbacks) {
|
|
@@ -2414,6 +3177,9 @@ var DingTalkBridge = class {
|
|
|
2414
3177
|
}
|
|
2415
3178
|
client = null;
|
|
2416
3179
|
started = false;
|
|
3180
|
+
/** 企业内部应用 accessToken 缓存(下载机器人消息文件需要)。 */
|
|
3181
|
+
accessToken = null;
|
|
3182
|
+
accessTokenExpiresAt = 0;
|
|
2417
3183
|
status = { state: "idle", detail: "", connectedAt: null };
|
|
2418
3184
|
setStatus(state, detail = "") {
|
|
2419
3185
|
this.status = {
|
|
@@ -2444,18 +3210,58 @@ var DingTalkBridge = class {
|
|
|
2444
3210
|
body: JSON.stringify({ status: "SUCCESS" })
|
|
2445
3211
|
}
|
|
2446
3212
|
});
|
|
2447
|
-
const
|
|
2448
|
-
|
|
3213
|
+
const msgtype = raw.msgtype ?? "text";
|
|
3214
|
+
const robotCode = raw.robotCode ?? this.cred.robotCode ?? "";
|
|
3215
|
+
let text = "";
|
|
3216
|
+
const attachments = [];
|
|
3217
|
+
const notes = [];
|
|
3218
|
+
if (msgtype === "text") {
|
|
3219
|
+
text = raw.text?.content?.trim() || "";
|
|
3220
|
+
} else if (msgtype === "picture") {
|
|
3221
|
+
const downloadCode = raw.content?.downloadCode ?? "";
|
|
3222
|
+
const data = await this.downloadRobotFile(downloadCode, robotCode);
|
|
3223
|
+
if (data === null) text = "\uFF08\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09";
|
|
3224
|
+
else attachments.push({ kind: "image", data, name: `dingtalk-${raw.msgId ?? Date.now()}.jpg` });
|
|
3225
|
+
} else if (msgtype === "richText") {
|
|
3226
|
+
const nodes = raw.content?.richText ?? [];
|
|
3227
|
+
const texts = [];
|
|
3228
|
+
for (const node of nodes) {
|
|
3229
|
+
if (typeof node.text === "string" && node.text !== "") texts.push(node.text);
|
|
3230
|
+
else if (node.type === "picture" && node.downloadCode !== void 0) {
|
|
3231
|
+
const data = await this.downloadRobotFile(node.downloadCode, robotCode);
|
|
3232
|
+
if (data !== null) attachments.push({ kind: "image", data, name: `dingtalk-${Date.now()}.jpg` });
|
|
3233
|
+
else notes.push("\uFF08\u5BCC\u6587\u672C\u56FE\u7247\u4E0B\u8F7D\u5931\u8D25\uFF09");
|
|
3234
|
+
}
|
|
3235
|
+
}
|
|
3236
|
+
text = texts.join("");
|
|
3237
|
+
} else if (msgtype === "audio") {
|
|
3238
|
+
text = raw.content?.recognition?.trim() || "\uFF08\u6536\u5230\u8BED\u97F3\u6D88\u606F\uFF0C\u4F46\u5E73\u53F0\u672A\u63D0\u4F9B\u8BC6\u522B\u6587\u672C\uFF09";
|
|
3239
|
+
const downloadCode = raw.content?.downloadCode ?? "";
|
|
3240
|
+
if (downloadCode !== "") {
|
|
3241
|
+
const data = await this.downloadRobotFile(downloadCode, robotCode);
|
|
3242
|
+
if (data !== null) attachments.push({ kind: "file", data, name: `voice-${Date.now()}.bin` });
|
|
3243
|
+
}
|
|
3244
|
+
} else if (msgtype === "video" || msgtype === "file") {
|
|
3245
|
+
const downloadCode = raw.content?.downloadCode ?? "";
|
|
3246
|
+
const data = await this.downloadRobotFile(downloadCode, robotCode);
|
|
3247
|
+
if (data === null) notes.push(`\uFF08${msgtype === "video" ? "\u89C6\u9891" : "\u6587\u4EF6"}\u4E0B\u8F7D\u5931\u8D25\uFF0C\u6216\u8BE5\u573A\u666F\u4E0D\u652F\u6301\u63A5\u6536\uFF09`);
|
|
3248
|
+
else attachments.push({ kind: "file", data, name: `dingtalk-${Date.now()}.bin` });
|
|
3249
|
+
} else {
|
|
3250
|
+
text = `\uFF08\u6536\u5230\u9489\u9489\u300C${msgtype}\u300D\u7C7B\u578B\u6D88\u606F\uFF0C\u6682\u4E0D\u652F\u6301\u5904\u7406\uFF09`;
|
|
3251
|
+
}
|
|
3252
|
+
if (notes.length > 0) text = text === "" ? notes.join("\n") : `${text}
|
|
3253
|
+
${notes.join("\n")}`;
|
|
3254
|
+
if (text.trim() === "" && attachments.length === 0) return;
|
|
2449
3255
|
const isGroup = raw.conversationType === "2";
|
|
2450
3256
|
const sessionWebhook = raw.sessionWebhook || "";
|
|
2451
|
-
this.callbacks.onText(text, {
|
|
3257
|
+
this.callbacks.onText(text.trim(), {
|
|
2452
3258
|
conversationId: raw.conversationId || "",
|
|
2453
3259
|
msgId: raw.msgId || downstream.headers.messageId,
|
|
2454
3260
|
senderNick: raw.senderNick || "",
|
|
2455
3261
|
senderStaffId: raw.senderStaffId || "",
|
|
2456
3262
|
sessionWebhook,
|
|
2457
3263
|
chatType: isGroup ? "group" : "single"
|
|
2458
|
-
});
|
|
3264
|
+
}, attachments.length > 0 ? attachments : void 0);
|
|
2459
3265
|
} catch (err) {
|
|
2460
3266
|
console.error("[dsh-message-gateway] dingtalk message parsing error", err);
|
|
2461
3267
|
}
|
|
@@ -2472,6 +3278,62 @@ var DingTalkBridge = class {
|
|
|
2472
3278
|
this.setStatus("error", error instanceof Error ? error.message : String(error));
|
|
2473
3279
|
}
|
|
2474
3280
|
}
|
|
3281
|
+
/**
|
|
3282
|
+
* 取企业内部应用 accessToken(官方 v1.0 接口,AppKey/AppSecret)。
|
|
3283
|
+
* 带 60 秒提前过期的本地缓存,避免每条附件都换一次令牌。
|
|
3284
|
+
*/
|
|
3285
|
+
async getAccessToken() {
|
|
3286
|
+
if (this.accessToken !== null && Date.now() < this.accessTokenExpiresAt) return this.accessToken;
|
|
3287
|
+
try {
|
|
3288
|
+
const response = await fetch("https://api.dingtalk.com/v1.0/oauth2/accessToken", {
|
|
3289
|
+
method: "POST",
|
|
3290
|
+
headers: { "content-type": "application/json" },
|
|
3291
|
+
body: JSON.stringify({ appKey: this.cred.clientId, appSecret: this.cred.clientSecret })
|
|
3292
|
+
});
|
|
3293
|
+
if (!response.ok) {
|
|
3294
|
+
console.warn("[dsh-message-gateway] dingtalk accessToken http", response.status);
|
|
3295
|
+
return null;
|
|
3296
|
+
}
|
|
3297
|
+
const body = await response.json();
|
|
3298
|
+
if (typeof body.accessToken !== "string" || body.accessToken === "") return null;
|
|
3299
|
+
this.accessToken = body.accessToken;
|
|
3300
|
+
this.accessTokenExpiresAt = Date.now() + Math.max(0, (body.expireIn ?? 7200) - 60) * 1e3;
|
|
3301
|
+
return this.accessToken;
|
|
3302
|
+
} catch (error) {
|
|
3303
|
+
console.warn("[dsh-message-gateway] dingtalk accessToken failed", String(error));
|
|
3304
|
+
return null;
|
|
3305
|
+
}
|
|
3306
|
+
}
|
|
3307
|
+
/**
|
|
3308
|
+
* 下载机器人接收到的消息文件。
|
|
3309
|
+
*
|
|
3310
|
+
* 官方文档两步走:
|
|
3311
|
+
* 1. `POST /v1.0/robot/messageFiles/download`(header `x-acs-dingtalk-access-token`,
|
|
3312
|
+
* body `{ downloadCode, robotCode }`)→ `{ downloadUrl }`
|
|
3313
|
+
* 2. GET 该 downloadUrl 取二进制(返回的文件名无扩展名,官方要求自行判断/替换)
|
|
3314
|
+
*/
|
|
3315
|
+
async downloadRobotFile(downloadCode, robotCode) {
|
|
3316
|
+
if (downloadCode === "") return null;
|
|
3317
|
+
const token = await this.getAccessToken();
|
|
3318
|
+
if (token === null) return null;
|
|
3319
|
+
try {
|
|
3320
|
+
const response = await fetch("https://api.dingtalk.com/v1.0/robot/messageFiles/download", {
|
|
3321
|
+
method: "POST",
|
|
3322
|
+
headers: { "x-acs-dingtalk-access-token": token, "content-type": "application/json" },
|
|
3323
|
+
body: JSON.stringify({ downloadCode, robotCode })
|
|
3324
|
+
});
|
|
3325
|
+
if (!response.ok) {
|
|
3326
|
+
console.warn("[dsh-message-gateway] dingtalk file download http", response.status);
|
|
3327
|
+
return null;
|
|
3328
|
+
}
|
|
3329
|
+
const body = await response.json();
|
|
3330
|
+
if (typeof body.downloadUrl !== "string" || body.downloadUrl === "") return null;
|
|
3331
|
+
return await downloadBytes(body.downloadUrl, { timeoutMs: 6e4 });
|
|
3332
|
+
} catch (error) {
|
|
3333
|
+
console.warn("[dsh-message-gateway] dingtalk file download failed", String(error));
|
|
3334
|
+
return null;
|
|
3335
|
+
}
|
|
3336
|
+
}
|
|
2475
3337
|
/**
|
|
2476
3338
|
* 回复单次消息(通过 sessionWebhook 回复)。
|
|
2477
3339
|
*/
|
|
@@ -2512,22 +3374,73 @@ var DingTalkBridge = class {
|
|
|
2512
3374
|
// src/host/bridge-manager.ts
|
|
2513
3375
|
init_wechat_ilink_bridge();
|
|
2514
3376
|
var DEFAULT_MAX_CHAT_AGENTS = 40;
|
|
3377
|
+
var IMAGE_MEDIA_TYPES = ["image/png", "image/jpeg", "image/webp", "image/gif"];
|
|
3378
|
+
function normalizeImageMediaType(mediaType) {
|
|
3379
|
+
const t = (mediaType ?? "").trim().toLowerCase();
|
|
3380
|
+
return IMAGE_MEDIA_TYPES.includes(t) ? t : null;
|
|
3381
|
+
}
|
|
2515
3382
|
var STREAM_PUSH_INTERVAL = 600;
|
|
2516
3383
|
var ACK_HEARTBEAT_INTERVAL = 4e3;
|
|
2517
3384
|
var BridgeManager = class {
|
|
2518
3385
|
constructor(ctx, config) {
|
|
2519
3386
|
this.ctx = ctx;
|
|
2520
3387
|
this.config = config;
|
|
3388
|
+
if (typeof this.ctx.on === "function") {
|
|
3389
|
+
try {
|
|
3390
|
+
this.disposeStreamSub = this.ctx.on(
|
|
3391
|
+
"agent/assistant-stream",
|
|
3392
|
+
(payload) => this.handleAssistantStream(payload),
|
|
3393
|
+
{ global: true }
|
|
3394
|
+
);
|
|
3395
|
+
} catch (error) {
|
|
3396
|
+
console.warn("[dsh-message-gateway] assistant stream subscribe skipped", error);
|
|
3397
|
+
}
|
|
3398
|
+
}
|
|
2521
3399
|
}
|
|
2522
3400
|
wecom = null;
|
|
2523
3401
|
onStatusCallback = null;
|
|
2524
3402
|
/** 各聊天在途回复(key = 平台:chatKey)。 */
|
|
2525
3403
|
pendingMap = /* @__PURE__ */ new Map();
|
|
3404
|
+
/** 会话 id → 在途回复(0.2 流式帧按会话路由到对应平台聊天)。 */
|
|
3405
|
+
pendingBySession = /* @__PURE__ */ new Map();
|
|
3406
|
+
/** 全局流式帧订阅的 disposer。 */
|
|
3407
|
+
disposeStreamSub = void 0;
|
|
2526
3408
|
/** Webhook 在途请求(同步等待完整回复;全局单槽位)。 */
|
|
2527
3409
|
awaiting = null;
|
|
2528
3410
|
/** 各聊天的独立 agent 会话(key = 平台:chatKey;webhook 固定 'webhook')。 */
|
|
2529
3411
|
agents = /* @__PURE__ */ new Map();
|
|
2530
3412
|
disposed = false;
|
|
3413
|
+
/** 0.2 流式帧:按会话 id 找到在途平台回复,把文本增量接到现有节流推送管线。 */
|
|
3414
|
+
handleAssistantStream(payload) {
|
|
3415
|
+
const p = this.pendingBySession.get(payload.agent.session.id);
|
|
3416
|
+
if (p === void 0) return;
|
|
3417
|
+
const frame = payload.frame;
|
|
3418
|
+
if (frame.type === "start") {
|
|
3419
|
+
p.currentStepBuffer = "";
|
|
3420
|
+
return;
|
|
3421
|
+
}
|
|
3422
|
+
if (frame.type === "chunk") {
|
|
3423
|
+
if (frame.chunk.type !== "text-delta" || frame.chunk.text === "") return;
|
|
3424
|
+
p.currentStepBuffer += frame.chunk.text;
|
|
3425
|
+
p.buffer = [...p.stepMessages, p.currentStepBuffer].filter(Boolean).join("\n\n");
|
|
3426
|
+
this.keepAlive(p.key, p);
|
|
3427
|
+
this.scheduleStream(p);
|
|
3428
|
+
return;
|
|
3429
|
+
}
|
|
3430
|
+
this.keepAlive(p.key, p);
|
|
3431
|
+
}
|
|
3432
|
+
/** 任意新事件或流式 chunk 都滑动续期兜底超时。 */
|
|
3433
|
+
keepAlive(key, p) {
|
|
3434
|
+
if (p.fallback === null) return;
|
|
3435
|
+
clearTimeout(p.fallback);
|
|
3436
|
+
p.fallback = setTimeout(() => {
|
|
3437
|
+
if (this.pendingMap.get(key) === p) {
|
|
3438
|
+
console.warn("[dsh-message-gateway] idle timeout (no events for 90s)", { key });
|
|
3439
|
+
this.finishPending(key);
|
|
3440
|
+
}
|
|
3441
|
+
}, 90 * 1e3);
|
|
3442
|
+
p.fallback.unref?.();
|
|
3443
|
+
}
|
|
2531
3444
|
/** 当前语言的文案。 */
|
|
2532
3445
|
t(key) {
|
|
2533
3446
|
return botText(this.config.botLocale, key);
|
|
@@ -2542,16 +3455,7 @@ var BridgeManager = class {
|
|
|
2542
3455
|
p.cursor = i + 1;
|
|
2543
3456
|
const event = events[i];
|
|
2544
3457
|
if (!event) continue;
|
|
2545
|
-
|
|
2546
|
-
clearTimeout(p.fallback);
|
|
2547
|
-
p.fallback = setTimeout(() => {
|
|
2548
|
-
if (this.pendingMap.get(key) === p) {
|
|
2549
|
-
console.warn("[dsh-message-gateway] idle timeout (no events for 90s)", { key });
|
|
2550
|
-
this.finishPending(key);
|
|
2551
|
-
}
|
|
2552
|
-
}, 90 * 1e3);
|
|
2553
|
-
p.fallback.unref?.();
|
|
2554
|
-
}
|
|
3458
|
+
this.keepAlive(key, p);
|
|
2555
3459
|
if (event.type === "assistant/chunk") {
|
|
2556
3460
|
const chunk = event.data?.chunk;
|
|
2557
3461
|
if (chunk && chunk.type === "text-delta" && typeof chunk.text === "string") {
|
|
@@ -2639,6 +3543,8 @@ var BridgeManager = class {
|
|
|
2639
3543
|
p.heartbeat = null;
|
|
2640
3544
|
}
|
|
2641
3545
|
this.pendingMap.delete(key);
|
|
3546
|
+
const pending = this.pendingBySession.get(p.sessionId);
|
|
3547
|
+
if (pending === p) this.pendingBySession.delete(p.sessionId);
|
|
2642
3548
|
if (p.ackSent && !p.pushed) {
|
|
2643
3549
|
void p.sink.stream(p.frame, p.streamId, this.t("timeout"), true);
|
|
2644
3550
|
}
|
|
@@ -2663,7 +3569,8 @@ var BridgeManager = class {
|
|
|
2663
3569
|
let provider = selection?.provider ?? "";
|
|
2664
3570
|
let model = selection?.model ?? "";
|
|
2665
3571
|
if (provider === "" || model === "") {
|
|
2666
|
-
const
|
|
3572
|
+
const roots = this.ctx.agents.roots?.() ?? [];
|
|
3573
|
+
const root = roots[0] ?? this.ctx.agents.list()[0];
|
|
2667
3574
|
provider = root?.options.provider ?? "";
|
|
2668
3575
|
model = root?.options.model ?? "";
|
|
2669
3576
|
}
|
|
@@ -2712,8 +3619,11 @@ var BridgeManager = class {
|
|
|
2712
3619
|
}
|
|
2713
3620
|
}
|
|
2714
3621
|
}
|
|
2715
|
-
|
|
2716
|
-
|
|
3622
|
+
const installModel = installModelSelection;
|
|
3623
|
+
if (installModelSelection.length >= 2) {
|
|
3624
|
+
installModel(agentCtx, { current: selection, assembled: void 0 });
|
|
3625
|
+
} else {
|
|
3626
|
+
installModel(agentCtx);
|
|
2717
3627
|
}
|
|
2718
3628
|
}
|
|
2719
3629
|
});
|
|
@@ -2748,6 +3658,9 @@ var BridgeManager = class {
|
|
|
2748
3658
|
async dispose() {
|
|
2749
3659
|
if (this.disposed) return;
|
|
2750
3660
|
this.disposed = true;
|
|
3661
|
+
this.disposeStreamSub?.();
|
|
3662
|
+
this.disposeStreamSub = void 0;
|
|
3663
|
+
this.pendingBySession.clear();
|
|
2751
3664
|
this.wecom?.stop();
|
|
2752
3665
|
this.wecom = null;
|
|
2753
3666
|
this.telegram?.stop();
|
|
@@ -2780,11 +3693,61 @@ var BridgeManager = class {
|
|
|
2780
3693
|
finishAllPending() {
|
|
2781
3694
|
for (const key of [...this.pendingMap.keys()]) this.finishPending(key);
|
|
2782
3695
|
}
|
|
3696
|
+
/**
|
|
3697
|
+
* 文本 + 附件 → 内容块。
|
|
3698
|
+
* - 图片:走 ctx.attachments.saveImage → ImageBlock(多模态直接交给模型);
|
|
3699
|
+
* 平台 MIME 不在受支持集合(png/jpeg/webp/gif)时退化为文件块。
|
|
3700
|
+
* - 其它文件:ctx.attachments.saveFile → FileBlock(请求组装时投影为
|
|
3701
|
+
* 「文件名 + 字节数 + 只读路径」句柄文本,Agent 可用文件工具读取处理)。
|
|
3702
|
+
* - 任何保存失败都会产出用户可见的占位文本,绝不静默丢弃。
|
|
3703
|
+
*/
|
|
3704
|
+
async buildContentBlocks(text, attachments) {
|
|
3705
|
+
const blocks = [];
|
|
3706
|
+
if (text.trim() !== "") blocks.push({ type: "text", text });
|
|
3707
|
+
const list = attachments ?? [];
|
|
3708
|
+
if (list.length === 0) return blocks;
|
|
3709
|
+
const store = this.ctx.get?.("attachments");
|
|
3710
|
+
if (store === void 0) {
|
|
3711
|
+
blocks.push({ type: "text", text: "\uFF08\u6536\u5230\u9644\u4EF6\uFF0C\u4F46\u9644\u4EF6\u5B58\u50A8\u670D\u52A1\u4E0D\u53EF\u7528\uFF0C\u65E0\u6CD5\u5904\u7406\uFF09" });
|
|
3712
|
+
return blocks;
|
|
3713
|
+
}
|
|
3714
|
+
for (const att of list) {
|
|
3715
|
+
try {
|
|
3716
|
+
if (att.kind === "image") {
|
|
3717
|
+
const mediaType = normalizeImageMediaType(att.mediaType);
|
|
3718
|
+
if (mediaType === null) {
|
|
3719
|
+
const ref = await store.saveFile({ data: att.data, name: att.name });
|
|
3720
|
+
blocks.push({ type: "file", attachment: ref });
|
|
3721
|
+
} else {
|
|
3722
|
+
const ref = await store.saveImage({ data: att.data, mediaType, name: att.name });
|
|
3723
|
+
blocks.push({ type: "image", attachment: ref });
|
|
3724
|
+
}
|
|
3725
|
+
} else {
|
|
3726
|
+
const ref = await store.saveFile({ data: att.data, name: att.name });
|
|
3727
|
+
blocks.push({ type: "file", attachment: ref });
|
|
3728
|
+
}
|
|
3729
|
+
} catch (error) {
|
|
3730
|
+
if (att.kind === "image") {
|
|
3731
|
+
try {
|
|
3732
|
+
const ref = await store.saveFile({ data: att.data, name: att.name });
|
|
3733
|
+
blocks.push({ type: "file", attachment: ref });
|
|
3734
|
+
continue;
|
|
3735
|
+
} catch {
|
|
3736
|
+
}
|
|
3737
|
+
}
|
|
3738
|
+
blocks.push({
|
|
3739
|
+
type: "text",
|
|
3740
|
+
text: `\uFF08\u9644\u4EF6\u300C${att.name ?? "\u672A\u77E5"}\u300D\u4FDD\u5B58\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}\uFF09`
|
|
3741
|
+
});
|
|
3742
|
+
}
|
|
3743
|
+
}
|
|
3744
|
+
return blocks;
|
|
3745
|
+
}
|
|
2783
3746
|
/**
|
|
2784
3747
|
* 外部平台消息统一入口:命令优先,否则注入该聊天独立 agent 会话,
|
|
2785
3748
|
* 回复经 sink 流式回发。所有已打通的平台共用此管线。
|
|
2786
3749
|
*/
|
|
2787
|
-
async handleExternalMessage(id, rawText) {
|
|
3750
|
+
async handleExternalMessage(id, rawText, attachments) {
|
|
2788
3751
|
if (this.disposed) return;
|
|
2789
3752
|
const text = stripMention(rawText);
|
|
2790
3753
|
const reply = (content) => {
|
|
@@ -2803,6 +3766,11 @@ var BridgeManager = class {
|
|
|
2803
3766
|
}
|
|
2804
3767
|
const route = this.matchRoute(id.key, text);
|
|
2805
3768
|
const routedText = route !== null && route.prefix !== "" ? text.slice(route.prefix.length).trim() : text;
|
|
3769
|
+
const content = await this.buildContentBlocks(routedText, attachments);
|
|
3770
|
+
if (content.length === 0) {
|
|
3771
|
+
console.warn("[dsh-message-gateway] no content to send", { key: id.key });
|
|
3772
|
+
return;
|
|
3773
|
+
}
|
|
2806
3774
|
const agent = await this.ensureAgentForKey(id.key, route?.rule);
|
|
2807
3775
|
if (agent === null) {
|
|
2808
3776
|
console.warn("[dsh-message-gateway] no dedicated agent available");
|
|
@@ -2811,11 +3779,13 @@ var BridgeManager = class {
|
|
|
2811
3779
|
const message = {
|
|
2812
3780
|
id: MessageId(`dsh-gateway-${Date.now().toString(36)}`),
|
|
2813
3781
|
role: "user",
|
|
2814
|
-
content
|
|
3782
|
+
content,
|
|
2815
3783
|
source: { kind: "plugin", plugin: "dsh-message-gateway", form: "relay" }
|
|
2816
3784
|
};
|
|
2817
3785
|
const session = agent.session;
|
|
2818
3786
|
const p = {
|
|
3787
|
+
key: id.key,
|
|
3788
|
+
sessionId: session.id,
|
|
2819
3789
|
frame: id.frame,
|
|
2820
3790
|
sink: id.sink,
|
|
2821
3791
|
streamId: `gw-${Date.now().toString(36)}`,
|
|
@@ -2833,6 +3803,7 @@ var BridgeManager = class {
|
|
|
2833
3803
|
heartbeat: null
|
|
2834
3804
|
};
|
|
2835
3805
|
this.pendingMap.set(id.key, p);
|
|
3806
|
+
this.pendingBySession.set(session.id, p);
|
|
2836
3807
|
if (id.sink.ack !== false) {
|
|
2837
3808
|
p.ackSent = true;
|
|
2838
3809
|
id.sink.stream(id.frame, p.streamId, this.t("ack"), false);
|
|
@@ -2925,7 +3896,7 @@ var BridgeManager = class {
|
|
|
2925
3896
|
this.wecom?.stop();
|
|
2926
3897
|
const bridge = new WecomBridge(cred, {
|
|
2927
3898
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
2928
|
-
onText: (rawText, frame) => {
|
|
3899
|
+
onText: (rawText, frame, attachments) => {
|
|
2929
3900
|
const body = frame.body ?? {};
|
|
2930
3901
|
const chattype = body.chattype ?? "single";
|
|
2931
3902
|
const userid = body.from?.userid ?? "";
|
|
@@ -2936,7 +3907,7 @@ var BridgeManager = class {
|
|
|
2936
3907
|
// 企业微信走单一流式消息(ack → 内容 → 定稿同一条消息就地更新);
|
|
2937
3908
|
// 不再叠加 response_url 投递,避免出现重复消息。
|
|
2938
3909
|
};
|
|
2939
|
-
void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText);
|
|
3910
|
+
void this.handleExternalMessage({ key, frame, sink, chatType: chattype === "group" ? "group" : "single" }, rawText, attachments);
|
|
2940
3911
|
},
|
|
2941
3912
|
onEnter: (frame) => {
|
|
2942
3913
|
if (!this.config.welcomeReply) return;
|
|
@@ -3244,7 +4215,7 @@ ${secret}`;
|
|
|
3244
4215
|
};
|
|
3245
4216
|
const bridge = new WechatIlinkBridge(ilinkCred, {
|
|
3246
4217
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3247
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4218
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3248
4219
|
});
|
|
3249
4220
|
this.wechat = bridge;
|
|
3250
4221
|
bridge.start();
|
|
@@ -3261,7 +4232,7 @@ ${secret}`;
|
|
|
3261
4232
|
{ clientId: cred.clientId ?? "", clientSecret: cred.clientSecret ?? "", robotCode: cred.robotCode },
|
|
3262
4233
|
{
|
|
3263
4234
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3264
|
-
onText: (text, frame) => {
|
|
4235
|
+
onText: (text, frame, attachments) => {
|
|
3265
4236
|
const identity = {
|
|
3266
4237
|
key: `dingtalk:${frame.conversationId}`,
|
|
3267
4238
|
frame,
|
|
@@ -3275,7 +4246,7 @@ ${secret}`;
|
|
|
3275
4246
|
},
|
|
3276
4247
|
chatType: frame.chatType
|
|
3277
4248
|
};
|
|
3278
|
-
void this.handleExternalMessage(identity, text);
|
|
4249
|
+
void this.handleExternalMessage(identity, text, attachments);
|
|
3279
4250
|
}
|
|
3280
4251
|
}
|
|
3281
4252
|
);
|
|
@@ -3294,7 +4265,7 @@ ${secret}`;
|
|
|
3294
4265
|
{ appId: cred.appId ?? "", appSecret: cred.appSecret ?? "" },
|
|
3295
4266
|
{
|
|
3296
4267
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3297
|
-
onText: (text, frame) => {
|
|
4268
|
+
onText: (text, frame, attachments) => {
|
|
3298
4269
|
const identity = {
|
|
3299
4270
|
key: `feishu:${frame.chatId}`,
|
|
3300
4271
|
frame,
|
|
@@ -3308,7 +4279,7 @@ ${secret}`;
|
|
|
3308
4279
|
},
|
|
3309
4280
|
chatType: frame.chatType
|
|
3310
4281
|
};
|
|
3311
|
-
void this.handleExternalMessage(identity, text);
|
|
4282
|
+
void this.handleExternalMessage(identity, text, attachments);
|
|
3312
4283
|
}
|
|
3313
4284
|
}
|
|
3314
4285
|
);
|
|
@@ -3325,7 +4296,7 @@ ${secret}`;
|
|
|
3325
4296
|
this.telegram?.stop();
|
|
3326
4297
|
const bridge = new TelegramBridge(cred.token ?? "", {
|
|
3327
4298
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3328
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4299
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3329
4300
|
});
|
|
3330
4301
|
this.telegram = bridge;
|
|
3331
4302
|
bridge.start();
|
|
@@ -3340,7 +4311,7 @@ ${secret}`;
|
|
|
3340
4311
|
this.discord?.stop();
|
|
3341
4312
|
const bridge = new DiscordBridge(cred.token ?? "", {
|
|
3342
4313
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3343
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4314
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3344
4315
|
});
|
|
3345
4316
|
this.discord = bridge;
|
|
3346
4317
|
bridge.start();
|
|
@@ -3355,7 +4326,7 @@ ${secret}`;
|
|
|
3355
4326
|
this.qq?.stop();
|
|
3356
4327
|
const bridge = new QQBridge(cred.appId ?? "", cred.secret ?? "", {
|
|
3357
4328
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3358
|
-
onText: (text, identity) => void this.handleExternalMessage(identity, text)
|
|
4329
|
+
onText: (text, identity, attachments) => void this.handleExternalMessage(identity, text, attachments)
|
|
3359
4330
|
});
|
|
3360
4331
|
this.qq = bridge;
|
|
3361
4332
|
bridge.start();
|
|
@@ -3376,15 +4347,66 @@ ${secret}`;
|
|
|
3376
4347
|
smtpHost: cred.smtpHost ?? void 0,
|
|
3377
4348
|
smtpPort: cred.smtpPort ?? void 0,
|
|
3378
4349
|
smtpUser: cred.smtpUser ?? void 0,
|
|
3379
|
-
smtpPass: cred.smtpPass ?? void 0
|
|
4350
|
+
smtpPass: cred.smtpPass ?? void 0,
|
|
4351
|
+
// 安全:发件人白名单(空 = 不限制,保持向后兼容)。
|
|
4352
|
+
allowedSenders: cred.allowedSenders ?? void 0
|
|
3380
4353
|
};
|
|
3381
4354
|
const bridge = new EmailBridge(emailCred, {
|
|
3382
4355
|
onStatus: (status) => this.onStatusCallback?.(status),
|
|
3383
|
-
onText: (text, identity) => void this.
|
|
4356
|
+
onText: (text, identity, attachments) => void this.handleInboundEmail(identity, text, attachments)
|
|
3384
4357
|
});
|
|
3385
4358
|
this.email = bridge;
|
|
3386
4359
|
bridge.start();
|
|
3387
4360
|
}
|
|
4361
|
+
/**
|
|
4362
|
+
* 邮件入站分流:先问审批闸门要不要这条消息,再决定是否交给 agent。
|
|
4363
|
+
*
|
|
4364
|
+
* 为什么需要这一层:审批回信("approve")**不能**被当成一句闲聊喂给模型。
|
|
4365
|
+
* 若直接把回信交给 agent,模型会看到"approve"并自由发挥,而真正的审批
|
|
4366
|
+
* 状态却仍挂在原地 —— 用户以为批准了,实际什么也没发生。
|
|
4367
|
+
*
|
|
4368
|
+
* 因此顺序是:审批闸门先认领 → 认领了就地回执并**终止**;不认领才进 agent。
|
|
4369
|
+
*
|
|
4370
|
+
* 审批闸门未安装或未配置时,这个调用会快速失败(连接被拒/404),
|
|
4371
|
+
* 邮件照常进入 agent —— 即"没装审批闸门"的行为与从前完全一致。
|
|
4372
|
+
*/
|
|
4373
|
+
async handleInboundEmail(identity, text, attachments) {
|
|
4374
|
+
const claimed = await this.tryApprovalGate(identity, text);
|
|
4375
|
+
if (claimed) return;
|
|
4376
|
+
await this.handleExternalMessage(identity, text, attachments);
|
|
4377
|
+
}
|
|
4378
|
+
/**
|
|
4379
|
+
* 尝试把一条入站消息交给 dsh-approval-gate 处理。
|
|
4380
|
+
*
|
|
4381
|
+
* @param identity - 入站身份(含 frame.from 作为发件人)。
|
|
4382
|
+
* @param text - 消息正文。
|
|
4383
|
+
* @returns 是否被审批闸门认领(true = 已处理,不应再进 agent)。
|
|
4384
|
+
*/
|
|
4385
|
+
async tryApprovalGate(identity, text) {
|
|
4386
|
+
const frame = identity.frame;
|
|
4387
|
+
const sender = frame?.from ?? "";
|
|
4388
|
+
if (sender === "") return false;
|
|
4389
|
+
const port = process.env.DSH_WEB_PORT ?? process.env.PORT ?? "3080";
|
|
4390
|
+
const url = `http://127.0.0.1:${port}/approval/reply`;
|
|
4391
|
+
try {
|
|
4392
|
+
const res = await fetch(url, {
|
|
4393
|
+
method: "POST",
|
|
4394
|
+
headers: { "Content-Type": "application/json" },
|
|
4395
|
+
body: JSON.stringify({ sender, text }),
|
|
4396
|
+
signal: AbortSignal.timeout(5e3)
|
|
4397
|
+
});
|
|
4398
|
+
if (!res.ok) return false;
|
|
4399
|
+
const body = await res.json();
|
|
4400
|
+
if (body.handled !== true) return false;
|
|
4401
|
+
if (typeof body.reply === "string" && body.reply !== "") {
|
|
4402
|
+
identity.sink.stream(identity.frame, `approval-${Date.now().toString(36)}`, body.reply, true);
|
|
4403
|
+
}
|
|
4404
|
+
console.log("[dsh-message-gateway] inbound message claimed by approval gate", { sender, len: text.length });
|
|
4405
|
+
return true;
|
|
4406
|
+
} catch {
|
|
4407
|
+
return false;
|
|
4408
|
+
}
|
|
4409
|
+
}
|
|
3388
4410
|
/** 停止 Email 桥。 */
|
|
3389
4411
|
stopEmail() {
|
|
3390
4412
|
this.email?.stop();
|
|
@@ -3620,7 +4642,9 @@ var PLATFORMS = [
|
|
|
3620
4642
|
{ key: "smtpHost", labelKey: "field.smtpHost", kind: "text" },
|
|
3621
4643
|
{ key: "smtpPort", labelKey: "field.smtpPort", kind: "number" },
|
|
3622
4644
|
{ key: "smtpUser", labelKey: "field.smtpUser", kind: "text" },
|
|
3623
|
-
{ key: "smtpPass", labelKey: "field.smtpPass", placeholderKey: "field.secret.ph", kind: "secret" }
|
|
4645
|
+
{ key: "smtpPass", labelKey: "field.smtpPass", placeholderKey: "field.secret.ph", kind: "secret" },
|
|
4646
|
+
// 安全:发件人白名单。留空 = 不限制(旧行为);填写后只有名单内地址能进入 agent。
|
|
4647
|
+
{ key: "allowedSenders", labelKey: "field.allowedSenders", placeholderKey: "field.allowedSenders.ph", kind: "text" }
|
|
3624
4648
|
]
|
|
3625
4649
|
},
|
|
3626
4650
|
{
|
|
@@ -4951,6 +5975,7 @@ export {
|
|
|
4951
5975
|
index_default as default,
|
|
4952
5976
|
headerField,
|
|
4953
5977
|
inject,
|
|
5978
|
+
isSenderAllowed,
|
|
4954
5979
|
parseAddress,
|
|
4955
5980
|
platformDef,
|
|
4956
5981
|
sha1Sorted,
|