-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebhook.js
More file actions
284 lines (250 loc) · 8.97 KB
/
Copy pathwebhook.js
File metadata and controls
284 lines (250 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
import { WecomCrypto } from "./crypto.js";
import { logger } from "./logger.js";
import { MessageDeduplicator } from "./utils.js";
/**
* WeCom Self-built Application Webhook Handler.
*
* Key differences from the AI Bot (智能机器人) plugin:
* - Incoming messages are XML (not JSON)
* - The encrypted envelope is XML: <xml><Encrypt>...</Encrypt></xml>
* - Decrypted payload is also XML with standard WeCom fields
* - Responses are "success" (async reply via API), not stream JSON
*/
export class WecomAppWebhook {
config;
crypto;
deduplicator = new MessageDeduplicator();
static DUPLICATE = Symbol.for("wecom-app.duplicate");
constructor(config) {
this.config = config;
this.crypto = new WecomCrypto(config.token, config.encodingAesKey, config.corpId);
logger.debug("WecomAppWebhook initialized (self-built app mode)");
}
// =========================================================================
// URL Verification (GET request) — same mechanism as AI Bot
// =========================================================================
handleVerify(query) {
const signature = query.msg_signature;
const timestamp = query.timestamp;
const nonce = query.nonce;
const echostr = query.echostr;
if (!signature || !timestamp || !nonce || !echostr) {
logger.warn("Missing parameters in verify request", { query });
return null;
}
logger.debug("Handling verify request", { timestamp, nonce });
const calcSignature = this.crypto.getSignature(timestamp, nonce, echostr);
if (calcSignature !== signature) {
logger.error("Signature mismatch in verify", {
expected: signature,
calculated: calcSignature,
});
return null;
}
try {
const result = this.crypto.decrypt(echostr);
logger.info("URL verification successful");
return result.message;
} catch (e) {
logger.error("Decrypt failed in verify", {
error: e instanceof Error ? e.message : String(e),
});
return null;
}
}
// =========================================================================
// Message Handling (POST request)
// Self-built app uses XML format (outer envelope and inner message)
// =========================================================================
async handleMessage(query, body) {
const signature = query.msg_signature;
const timestamp = query.timestamp;
const nonce = query.nonce;
if (!signature || !timestamp || !nonce) {
logger.warn("Missing parameters in message request", { query });
return null;
}
// 1. Extract encrypted content from XML envelope
const encrypt = extractXmlField(body, "Encrypt");
if (!encrypt) {
logger.error("No Encrypt field in XML body");
return null;
}
// 2. Verify signature
const calcSignature = this.crypto.getSignature(timestamp, nonce, encrypt);
if (calcSignature !== signature) {
logger.error("Signature mismatch in message", {
expected: signature,
calculated: calcSignature,
});
return null;
}
// 3. Decrypt
let decryptedXml;
try {
const result = this.crypto.decrypt(encrypt);
decryptedXml = result.message;
logger.debug("Decrypted content", { content: decryptedXml.substring(0, 300) });
} catch (e) {
logger.error("Message decrypt failed", {
error: e instanceof Error ? e.message : String(e),
});
return null;
}
// 4. Parse XML message fields
const msgType = extractXmlField(decryptedXml, "MsgType");
if (!msgType) {
logger.warn("No MsgType in decrypted message");
return null;
}
if (msgType === "text") {
const content = extractXmlField(decryptedXml, "Content") || "";
const msgId = extractXmlField(decryptedXml, "MsgId") || `msg_${Date.now()}`;
const fromUser = extractXmlField(decryptedXml, "FromUserName") || "";
const agentId = extractXmlField(decryptedXml, "AgentID") || "";
const createTime = extractXmlField(decryptedXml, "CreateTime") || "";
if (this.deduplicator.isDuplicate(msgId)) {
logger.debug("Duplicate message ignored", { msgId });
return WecomAppWebhook.DUPLICATE;
}
logger.info("Received text message", {
fromUser,
agentId,
content: content.substring(0, 50),
});
return {
message: {
msgId,
msgType: "text",
content,
fromUser,
agentId,
createTime,
chatType: "single",
chatId: "",
},
};
} else if (msgType === "image") {
const picUrl = extractXmlField(decryptedXml, "PicUrl") || "";
const mediaId = extractXmlField(decryptedXml, "MediaId") || "";
const msgId = extractXmlField(decryptedXml, "MsgId") || `msg_${Date.now()}`;
const fromUser = extractXmlField(decryptedXml, "FromUserName") || "";
if (this.deduplicator.isDuplicate(msgId)) {
logger.debug("Duplicate image message ignored", { msgId });
return WecomAppWebhook.DUPLICATE;
}
logger.info("Received image message", { fromUser, picUrl: picUrl.substring(0, 80), mediaId });
return {
message: {
msgId,
msgType: "image",
picUrl,
mediaId,
fromUser,
chatType: "single",
chatId: "",
},
};
} else if (msgType === "voice") {
const recognition = extractXmlField(decryptedXml, "Recognition") || "";
const msgId = extractXmlField(decryptedXml, "MsgId") || `msg_${Date.now()}`;
const fromUser = extractXmlField(decryptedXml, "FromUserName") || "";
if (this.deduplicator.isDuplicate(msgId)) {
logger.debug("Duplicate voice message ignored", { msgId });
return WecomAppWebhook.DUPLICATE;
}
if (!recognition.trim()) {
logger.warn("Voice message without recognition", { msgId });
return null;
}
logger.info("Received voice message (transcribed)", {
fromUser,
preview: recognition.substring(0, 50),
});
return {
message: {
msgId,
msgType: "text",
content: recognition,
fromUser,
chatType: "single",
chatId: "",
},
};
} else if (msgType === "location") {
const lat = extractXmlField(decryptedXml, "Location_X") || "";
const lng = extractXmlField(decryptedXml, "Location_Y") || "";
const label = extractXmlField(decryptedXml, "Label") || "";
const msgId = extractXmlField(decryptedXml, "MsgId") || `msg_${Date.now()}`;
const fromUser = extractXmlField(decryptedXml, "FromUserName") || "";
if (this.deduplicator.isDuplicate(msgId)) {
return WecomAppWebhook.DUPLICATE;
}
const content = label
? `[位置] ${label} (${lat}, ${lng})`
: `[位置] ${lat}, ${lng}`;
return {
message: {
msgId,
msgType: "text",
content,
fromUser,
chatType: "single",
chatId: "",
},
};
} else if (msgType === "link") {
const title = extractXmlField(decryptedXml, "Title") || "";
const description = extractXmlField(decryptedXml, "Description") || "";
const url = extractXmlField(decryptedXml, "Url") || "";
const msgId = extractXmlField(decryptedXml, "MsgId") || `msg_${Date.now()}`;
const fromUser = extractXmlField(decryptedXml, "FromUserName") || "";
if (this.deduplicator.isDuplicate(msgId)) {
return WecomAppWebhook.DUPLICATE;
}
const parts = [];
if (title) parts.push(`[链接] ${title}`);
if (description) parts.push(description);
if (url) parts.push(url);
const content = parts.join("\n") || "[链接]";
return {
message: {
msgId,
msgType: "text",
content,
fromUser,
chatType: "single",
chatId: "",
},
};
} else if (msgType === "event") {
const event = extractXmlField(decryptedXml, "Event") || "";
const eventKey = extractXmlField(decryptedXml, "EventKey") || "";
const fromUser = extractXmlField(decryptedXml, "FromUserName") || "";
logger.info("Received event", { event, eventKey, fromUser });
return { event: { type: event, key: eventKey, fromUser } };
} else {
logger.warn("Unsupported message type", { msgType });
return null;
}
}
}
/**
* Extract a field value from XML using regex.
* Handles both CDATA and plain text values.
*/
function extractXmlField(xml, field) {
// Try CDATA first: <Field><![CDATA[value]]></Field>
const cdataRe = new RegExp(`<${field}><!\\[CDATA\\[([\\s\\S]*?)\\]\\]></${field}>`, "i");
const cdataMatch = xml.match(cdataRe);
if (cdataMatch) {
return cdataMatch[1];
}
// Fall back to plain text: <Field>value</Field>
const plainRe = new RegExp(`<${field}>([\\s\\S]*?)</${field}>`, "i");
const plainMatch = xml.match(plainRe);
if (plainMatch) {
return plainMatch[1].trim();
}
return null;
}