@kodelyth/feishu 2026.5.42 → 2026.6.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 (192) hide show
  1. package/klaw.plugin.json +1712 -47
  2. package/package.json +17 -4
  3. package/api.ts +0 -32
  4. package/channel-entry.ts +0 -20
  5. package/channel-plugin-api.ts +0 -1
  6. package/contract-api.ts +0 -16
  7. package/index.ts +0 -82
  8. package/runtime-api.ts +0 -52
  9. package/secret-contract-api.ts +0 -5
  10. package/security-contract-api.ts +0 -1
  11. package/session-key-api.ts +0 -1
  12. package/setup-api.ts +0 -3
  13. package/setup-entry.test.ts +0 -19
  14. package/setup-entry.ts +0 -13
  15. package/src/accounts.test.ts +0 -480
  16. package/src/accounts.ts +0 -333
  17. package/src/agent-config.ts +0 -21
  18. package/src/app-registration.ts +0 -331
  19. package/src/approval-auth.test.ts +0 -24
  20. package/src/approval-auth.ts +0 -25
  21. package/src/async.test.ts +0 -35
  22. package/src/async.ts +0 -104
  23. package/src/audio-preflight.runtime.ts +0 -9
  24. package/src/bitable.test.ts +0 -136
  25. package/src/bitable.ts +0 -762
  26. package/src/bot-content.ts +0 -485
  27. package/src/bot-group-name.test.ts +0 -116
  28. package/src/bot-runtime-api.ts +0 -12
  29. package/src/bot-sender-name.ts +0 -125
  30. package/src/bot.broadcast.test.ts +0 -523
  31. package/src/bot.card-action.test.ts +0 -552
  32. package/src/bot.checkBotMentioned.test.ts +0 -265
  33. package/src/bot.helpers.test.ts +0 -135
  34. package/src/bot.stripBotMention.test.ts +0 -126
  35. package/src/bot.test.ts +0 -3671
  36. package/src/bot.ts +0 -1703
  37. package/src/card-action.ts +0 -447
  38. package/src/card-interaction.test.ts +0 -131
  39. package/src/card-interaction.ts +0 -159
  40. package/src/card-test-helpers.ts +0 -54
  41. package/src/card-ux-approval.ts +0 -65
  42. package/src/card-ux-launcher.test.ts +0 -106
  43. package/src/card-ux-launcher.ts +0 -121
  44. package/src/card-ux-shared.ts +0 -33
  45. package/src/channel-runtime-api.ts +0 -16
  46. package/src/channel.runtime.ts +0 -47
  47. package/src/channel.test.ts +0 -1151
  48. package/src/channel.ts +0 -1423
  49. package/src/chat-schema.ts +0 -25
  50. package/src/chat.test.ts +0 -240
  51. package/src/chat.ts +0 -188
  52. package/src/client-timeout.ts +0 -42
  53. package/src/client.test.ts +0 -447
  54. package/src/client.ts +0 -262
  55. package/src/comment-dispatcher-runtime-api.ts +0 -6
  56. package/src/comment-dispatcher.test.ts +0 -185
  57. package/src/comment-dispatcher.ts +0 -107
  58. package/src/comment-handler-runtime-api.ts +0 -3
  59. package/src/comment-handler.test.ts +0 -592
  60. package/src/comment-handler.ts +0 -303
  61. package/src/comment-reaction.test.ts +0 -138
  62. package/src/comment-reaction.ts +0 -259
  63. package/src/comment-shared.test.ts +0 -183
  64. package/src/comment-shared.ts +0 -406
  65. package/src/comment-target.ts +0 -44
  66. package/src/config-schema.test.ts +0 -326
  67. package/src/config-schema.ts +0 -335
  68. package/src/conversation-id.test.ts +0 -18
  69. package/src/conversation-id.ts +0 -199
  70. package/src/dedup-runtime-api.ts +0 -1
  71. package/src/dedup.ts +0 -141
  72. package/src/dedupe-key.ts +0 -72
  73. package/src/directory.static.ts +0 -61
  74. package/src/directory.test.ts +0 -141
  75. package/src/directory.ts +0 -124
  76. package/src/doc-schema.ts +0 -182
  77. package/src/docx-batch-insert.test.ts +0 -116
  78. package/src/docx-batch-insert.ts +0 -223
  79. package/src/docx-color-text.ts +0 -154
  80. package/src/docx-table-ops.test.ts +0 -53
  81. package/src/docx-table-ops.ts +0 -316
  82. package/src/docx-types.ts +0 -38
  83. package/src/docx.account-selection.test.ts +0 -95
  84. package/src/docx.test.ts +0 -701
  85. package/src/docx.ts +0 -1596
  86. package/src/drive-schema.ts +0 -92
  87. package/src/drive.test.ts +0 -1237
  88. package/src/drive.ts +0 -829
  89. package/src/dynamic-agent.test.ts +0 -155
  90. package/src/dynamic-agent.ts +0 -143
  91. package/src/event-types.ts +0 -45
  92. package/src/external-keys.test.ts +0 -20
  93. package/src/external-keys.ts +0 -19
  94. package/src/lifecycle.test-support.ts +0 -220
  95. package/src/media.test.ts +0 -955
  96. package/src/media.ts +0 -1105
  97. package/src/mention-target.types.ts +0 -5
  98. package/src/mention.ts +0 -114
  99. package/src/message-action-contract.ts +0 -13
  100. package/src/monitor-state-runtime-api.ts +0 -7
  101. package/src/monitor-transport-runtime-api.ts +0 -10
  102. package/src/monitor.account.ts +0 -492
  103. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  104. package/src/monitor.bot-identity.ts +0 -86
  105. package/src/monitor.bot-menu-handler.ts +0 -165
  106. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  107. package/src/monitor.bot-menu.test.ts +0 -188
  108. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  109. package/src/monitor.card-action.lifecycle.test-support.ts +0 -421
  110. package/src/monitor.cleanup.test.ts +0 -383
  111. package/src/monitor.comment-notice-handler.ts +0 -105
  112. package/src/monitor.comment.test.ts +0 -967
  113. package/src/monitor.comment.ts +0 -1386
  114. package/src/monitor.lifecycle.test.ts +0 -4
  115. package/src/monitor.message-handler.ts +0 -350
  116. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  117. package/src/monitor.reaction.test.ts +0 -739
  118. package/src/monitor.startup.test.ts +0 -213
  119. package/src/monitor.startup.ts +0 -74
  120. package/src/monitor.state.defaults.test.ts +0 -46
  121. package/src/monitor.state.ts +0 -170
  122. package/src/monitor.synthetic-error.ts +0 -18
  123. package/src/monitor.test-mocks.ts +0 -46
  124. package/src/monitor.transport.ts +0 -451
  125. package/src/monitor.ts +0 -100
  126. package/src/monitor.webhook-e2e.test.ts +0 -279
  127. package/src/monitor.webhook-security.test.ts +0 -389
  128. package/src/monitor.webhook.test-helpers.ts +0 -116
  129. package/src/outbound-runtime-api.ts +0 -1
  130. package/src/outbound.test.ts +0 -1118
  131. package/src/outbound.ts +0 -785
  132. package/src/perm-schema.ts +0 -52
  133. package/src/perm.ts +0 -170
  134. package/src/pins.ts +0 -108
  135. package/src/policy.test.ts +0 -223
  136. package/src/policy.ts +0 -318
  137. package/src/post.test.ts +0 -105
  138. package/src/post.ts +0 -275
  139. package/src/probe.test.ts +0 -283
  140. package/src/probe.ts +0 -166
  141. package/src/processing-claims.ts +0 -59
  142. package/src/qr-terminal.ts +0 -1
  143. package/src/reactions.ts +0 -123
  144. package/src/reasoning-preview.test.ts +0 -113
  145. package/src/reasoning-preview.ts +0 -28
  146. package/src/reply-dispatcher-runtime-api.ts +0 -7
  147. package/src/reply-dispatcher.test.ts +0 -1513
  148. package/src/reply-dispatcher.ts +0 -748
  149. package/src/runtime.ts +0 -9
  150. package/src/secret-contract.ts +0 -145
  151. package/src/secret-input.ts +0 -1
  152. package/src/security-audit-shared.ts +0 -69
  153. package/src/security-audit.test.ts +0 -59
  154. package/src/security-audit.ts +0 -1
  155. package/src/send-result.ts +0 -80
  156. package/src/send-target.test.ts +0 -86
  157. package/src/send-target.ts +0 -35
  158. package/src/send.reply-fallback.test.ts +0 -417
  159. package/src/send.test.ts +0 -621
  160. package/src/send.ts +0 -861
  161. package/src/sequential-key.test.ts +0 -72
  162. package/src/sequential-key.ts +0 -25
  163. package/src/sequential-queue.test.ts +0 -165
  164. package/src/sequential-queue.ts +0 -86
  165. package/src/session-conversation.ts +0 -42
  166. package/src/session-route.ts +0 -48
  167. package/src/setup-core.ts +0 -51
  168. package/src/setup-surface.test.ts +0 -484
  169. package/src/setup-surface.ts +0 -618
  170. package/src/streaming-card.test.ts +0 -397
  171. package/src/streaming-card.ts +0 -571
  172. package/src/subagent-hooks.test.ts +0 -627
  173. package/src/subagent-hooks.ts +0 -413
  174. package/src/targets.ts +0 -97
  175. package/src/test-support/lifecycle-test-support.ts +0 -454
  176. package/src/thread-bindings.test.ts +0 -180
  177. package/src/thread-bindings.ts +0 -331
  178. package/src/tool-account-routing.test.ts +0 -250
  179. package/src/tool-account.test.ts +0 -44
  180. package/src/tool-account.ts +0 -93
  181. package/src/tool-factory-test-harness.ts +0 -79
  182. package/src/tool-result.test.ts +0 -32
  183. package/src/tool-result.ts +0 -16
  184. package/src/tools-config.test.ts +0 -21
  185. package/src/tools-config.ts +0 -22
  186. package/src/types.ts +0 -106
  187. package/src/typing.test.ts +0 -144
  188. package/src/typing.ts +0 -214
  189. package/src/wiki-schema.ts +0 -69
  190. package/src/wiki.ts +0 -270
  191. package/subagent-hooks-api.ts +0 -31
  192. package/tsconfig.json +0 -16
@@ -1,451 +0,0 @@
1
- import crypto from "node:crypto";
2
- import * as http from "node:http";
3
- import * as Lark from "@larksuiteoapi/node-sdk";
4
- import { waitForAbortableDelay } from "./async.js";
5
- import { createFeishuWSClient } from "./client.js";
6
- import {
7
- applyBasicWebhookRequestGuards,
8
- installRequestBodyLimitGuard,
9
- readWebhookBodyOrReject,
10
- resolveRequestClientIp,
11
- safeEqualSecret,
12
- type RuntimeEnv,
13
- } from "./monitor-transport-runtime-api.js";
14
- import {
15
- botNames,
16
- botOpenIds,
17
- FEISHU_WEBHOOK_BODY_TIMEOUT_MS,
18
- FEISHU_WEBHOOK_MAX_BODY_BYTES,
19
- feishuWebhookRateLimiter,
20
- httpServers,
21
- recordWebhookStatus,
22
- wsClients,
23
- } from "./monitor.state.js";
24
- import type { ResolvedFeishuAccount } from "./types.js";
25
-
26
- type MonitorTransportParams = {
27
- account: ResolvedFeishuAccount;
28
- accountId: string;
29
- runtime?: RuntimeEnv;
30
- abortSignal?: AbortSignal;
31
- eventDispatcher: Lark.EventDispatcher;
32
- };
33
-
34
- const FEISHU_WS_RECONNECT_INITIAL_DELAY_MS = 1_000;
35
- const FEISHU_WS_RECONNECT_MAX_DELAY_MS = 30_000;
36
- const FEISHU_WS_LOG_ERROR_MAX_LENGTH = 500;
37
- const FEISHU_WS_RECONNECT_EXHAUSTED_RE = /^WebSocket reconnect exhausted after \d+ attempts?/;
38
- const FEISHU_WS_AUTORECONNECT_DISABLED_ERROR =
39
- "WebSocket connect failed and autoReconnect is disabled";
40
-
41
- function isFeishuWebhookPayload(value: unknown): value is Record<string, unknown> {
42
- return !!value && typeof value === "object" && !Array.isArray(value);
43
- }
44
-
45
- function buildFeishuWebhookEnvelope(
46
- req: http.IncomingMessage,
47
- payload: Record<string, unknown>,
48
- ): Record<string, unknown> {
49
- return Object.assign(Object.create({ headers: req.headers }), payload) as Record<string, unknown>;
50
- }
51
-
52
- function parseFeishuWebhookPayload(rawBody: string): Record<string, unknown> | null {
53
- try {
54
- const parsed = JSON.parse(rawBody) as unknown;
55
- return isFeishuWebhookPayload(parsed) ? parsed : null;
56
- } catch {
57
- return null;
58
- }
59
- }
60
-
61
- function isFeishuWebhookSignatureValid(params: {
62
- headers: http.IncomingHttpHeaders;
63
- rawBody: string;
64
- encryptKey?: string;
65
- }): boolean {
66
- const encryptKey = params.encryptKey?.trim();
67
- if (!encryptKey) {
68
- return false;
69
- }
70
-
71
- const timestampHeader = params.headers["x-lark-request-timestamp"];
72
- const nonceHeader = params.headers["x-lark-request-nonce"];
73
- const signatureHeader = params.headers["x-lark-signature"];
74
- const timestamp = Array.isArray(timestampHeader) ? timestampHeader[0] : timestampHeader;
75
- const nonce = Array.isArray(nonceHeader) ? nonceHeader[0] : nonceHeader;
76
- const signature = Array.isArray(signatureHeader) ? signatureHeader[0] : signatureHeader;
77
- if (!timestamp || !nonce || !signature) {
78
- return false;
79
- }
80
-
81
- const computedSignature = crypto
82
- .createHash("sha256")
83
- .update(timestamp + nonce + encryptKey + params.rawBody)
84
- .digest("hex");
85
- return safeEqualSecret(computedSignature, signature);
86
- }
87
-
88
- function respondText(res: http.ServerResponse, statusCode: number, body: string): void {
89
- res.statusCode = statusCode;
90
- res.setHeader("Content-Type", "text/plain; charset=utf-8");
91
- res.end(body);
92
- }
93
-
94
- function normalizeFeishuWebhookRateLimitClient(clientIp: string | undefined): string {
95
- if (!clientIp) {
96
- return "unknown";
97
- }
98
- if (clientIp === "::1" || clientIp.startsWith("127.")) {
99
- return "loopback";
100
- }
101
- return clientIp;
102
- }
103
-
104
- function buildFeishuWebhookRateLimitKey(params: {
105
- accountId: string;
106
- path: string;
107
- clientIp?: string;
108
- }): string {
109
- return `${params.accountId}:${params.path}:${normalizeFeishuWebhookRateLimitClient(
110
- params.clientIp,
111
- )}`;
112
- }
113
-
114
- export { buildFeishuWebhookRateLimitKey as buildFeishuWebhookRateLimitKeyForTest };
115
-
116
- function getFeishuWsReconnectDelayMs(attempt: number): number {
117
- return Math.min(
118
- FEISHU_WS_RECONNECT_INITIAL_DELAY_MS * 2 ** Math.max(0, attempt - 1),
119
- FEISHU_WS_RECONNECT_MAX_DELAY_MS,
120
- );
121
- }
122
-
123
- function formatFeishuWsErrorForLog(err: unknown): string {
124
- const raw = err instanceof Error ? err.message || err.name : String(err);
125
- const singleLine = Array.from(raw, (char) => {
126
- const code = char.charCodeAt(0);
127
- return code <= 31 || code === 127 ? " " : char;
128
- }).join("");
129
- const redacted = singleLine
130
- .replace(/:\/\/[^:@/\s]+:[^@/\s]+@/g, "://[redacted]@")
131
- .replace(/\b(authorization\s*[:=]\s*Bearer\s+)[^\s,;]+/gi, "$1[redacted]")
132
- .replace(/\b(Bearer\s+)[A-Za-z0-9._~+/-]+=*/g, "$1[redacted]")
133
- .replace(
134
- /\b((?:app[_-]?secret|tenant[_-]?access[_-]?token|access[_-]?token|refresh[_-]?token|token|secret|password)\s*[:=]\s*)[^\s&;,]+/gi,
135
- "$1[redacted]",
136
- )
137
- .replace(/\s+/g, " ")
138
- .trim();
139
-
140
- if (!redacted) {
141
- return "unknown error";
142
- }
143
- if (redacted.length <= FEISHU_WS_LOG_ERROR_MAX_LENGTH) {
144
- return redacted;
145
- }
146
- return `${redacted.slice(0, FEISHU_WS_LOG_ERROR_MAX_LENGTH)}...`;
147
- }
148
-
149
- function isFeishuWsTerminalError(err: Error): boolean {
150
- const message = err.message.trim();
151
- return (
152
- FEISHU_WS_RECONNECT_EXHAUSTED_RE.test(message) ||
153
- message.startsWith(FEISHU_WS_AUTORECONNECT_DISABLED_ERROR)
154
- );
155
- }
156
-
157
- function cleanupFeishuWsClient(params: {
158
- accountId: string;
159
- wsClient?: Lark.WSClient;
160
- error: (message: string) => void;
161
- clearIdentity: boolean;
162
- }): void {
163
- const { accountId, wsClient, error, clearIdentity } = params;
164
- if (wsClient) {
165
- try {
166
- wsClient.close();
167
- } catch (err) {
168
- error(
169
- `feishu[${accountId}]: error closing WebSocket client: ${formatFeishuWsErrorForLog(err)}`,
170
- );
171
- }
172
- }
173
- wsClients.delete(accountId);
174
- if (clearIdentity) {
175
- botOpenIds.delete(accountId);
176
- botNames.delete(accountId);
177
- }
178
- }
179
-
180
- function waitForFeishuWsCycleEnd(params: {
181
- abortSignal?: AbortSignal;
182
- terminalError: Promise<Error>;
183
- }): Promise<"abort" | Error> {
184
- if (params.abortSignal?.aborted) {
185
- return Promise.resolve("abort");
186
- }
187
-
188
- return new Promise((resolve) => {
189
- let settled = false;
190
- let handleAbort: (() => void) | undefined;
191
-
192
- const finish = (result: "abort" | Error) => {
193
- if (settled) {
194
- return;
195
- }
196
- settled = true;
197
- if (handleAbort) {
198
- params.abortSignal?.removeEventListener("abort", handleAbort);
199
- }
200
- resolve(result);
201
- };
202
-
203
- handleAbort = () => finish("abort");
204
- params.abortSignal?.addEventListener("abort", handleAbort, { once: true });
205
- if (params.abortSignal?.aborted) {
206
- finish("abort");
207
- return;
208
- }
209
-
210
- void params.terminalError.then(finish);
211
- });
212
- }
213
-
214
- export async function monitorWebSocket({
215
- account,
216
- accountId,
217
- runtime,
218
- abortSignal,
219
- eventDispatcher,
220
- }: MonitorTransportParams): Promise<void> {
221
- const log = runtime?.log ?? console.log;
222
- const error = runtime?.error ?? console.error;
223
-
224
- let attempt = 0;
225
- while (true) {
226
- if (abortSignal?.aborted) {
227
- break;
228
- }
229
-
230
- let wsClient: Lark.WSClient | undefined;
231
- try {
232
- let reportTerminalError: (err: Error) => void = () => {};
233
- const terminalError = new Promise<Error>((resolve) => {
234
- reportTerminalError = resolve;
235
- });
236
- const handleWsError = (err: Error) => {
237
- if (isFeishuWsTerminalError(err)) {
238
- reportTerminalError(err);
239
- return;
240
- }
241
-
242
- error(
243
- `feishu[${accountId}]: WebSocket SDK reported recoverable error: ${formatFeishuWsErrorForLog(err)}`,
244
- );
245
- };
246
- log(`feishu[${accountId}]: starting WebSocket connection...`);
247
- wsClient = await createFeishuWSClient(account, {
248
- onError: handleWsError,
249
- });
250
- if (abortSignal?.aborted) {
251
- cleanupFeishuWsClient({ accountId, wsClient, error, clearIdentity: true });
252
- break;
253
- }
254
- wsClients.set(accountId, wsClient);
255
- await wsClient.start({ eventDispatcher });
256
- attempt = 0;
257
- log(`feishu[${accountId}]: WebSocket client started`);
258
- const cycleEnd = await waitForFeishuWsCycleEnd({ abortSignal, terminalError });
259
- if (cycleEnd === "abort") {
260
- log(`feishu[${accountId}]: abort signal received, stopping`);
261
- cleanupFeishuWsClient({ accountId, wsClient, error, clearIdentity: true });
262
- return;
263
- }
264
-
265
- cleanupFeishuWsClient({ accountId, wsClient, error, clearIdentity: false });
266
- if (abortSignal?.aborted) {
267
- break;
268
- }
269
-
270
- attempt += 1;
271
- const delayMs = getFeishuWsReconnectDelayMs(attempt);
272
- error(
273
- `feishu[${accountId}]: WebSocket connection ended, recreating client in ${delayMs}ms: ${formatFeishuWsErrorForLog(cycleEnd)}`,
274
- );
275
- const shouldRetry = await waitForAbortableDelay(delayMs, abortSignal);
276
- if (!shouldRetry) {
277
- break;
278
- }
279
- } catch (err) {
280
- cleanupFeishuWsClient({ accountId, wsClient, error, clearIdentity: false });
281
- if (abortSignal?.aborted) {
282
- break;
283
- }
284
-
285
- attempt += 1;
286
- const delayMs = getFeishuWsReconnectDelayMs(attempt);
287
- error(
288
- `feishu[${accountId}]: WebSocket start failed, retrying in ${delayMs}ms: ${formatFeishuWsErrorForLog(err)}`,
289
- );
290
- const shouldRetry = await waitForAbortableDelay(delayMs, abortSignal);
291
- if (!shouldRetry) {
292
- break;
293
- }
294
- }
295
- }
296
- cleanupFeishuWsClient({ accountId, wsClient: undefined, error, clearIdentity: true });
297
- }
298
-
299
- export async function monitorWebhook({
300
- account,
301
- accountId,
302
- runtime,
303
- abortSignal,
304
- eventDispatcher,
305
- }: MonitorTransportParams): Promise<void> {
306
- const log = runtime?.log ?? console.log;
307
- const error = runtime?.error ?? console.error;
308
- const encryptKey = account.encryptKey?.trim();
309
- if (!encryptKey) {
310
- throw new Error(`Feishu account "${accountId}" webhook mode requires encryptKey`);
311
- }
312
-
313
- const port = account.config.webhookPort ?? 3000;
314
- const path = account.config.webhookPath ?? "/feishu/events";
315
- const host = account.config.webhookHost ?? "127.0.0.1";
316
-
317
- log(`feishu[${accountId}]: starting Webhook server on ${host}:${port}, path ${path}...`);
318
-
319
- const server = http.createServer();
320
-
321
- server.on("request", (req, res) => {
322
- res.on("finish", () => {
323
- recordWebhookStatus(runtime, accountId, path, res.statusCode);
324
- });
325
-
326
- const rateLimitKey = buildFeishuWebhookRateLimitKey({
327
- accountId,
328
- path,
329
- clientIp: resolveRequestClientIp(req),
330
- });
331
- if (
332
- !applyBasicWebhookRequestGuards({
333
- req,
334
- res,
335
- rateLimiter: feishuWebhookRateLimiter,
336
- rateLimitKey,
337
- nowMs: Date.now(),
338
- requireJsonContentType: true,
339
- })
340
- ) {
341
- return;
342
- }
343
-
344
- const guard = installRequestBodyLimitGuard(req, res, {
345
- maxBytes: FEISHU_WEBHOOK_MAX_BODY_BYTES,
346
- timeoutMs: FEISHU_WEBHOOK_BODY_TIMEOUT_MS,
347
- responseFormat: "text",
348
- });
349
- if (guard.isTripped()) {
350
- return;
351
- }
352
-
353
- void (async () => {
354
- try {
355
- const body = await readWebhookBodyOrReject({
356
- req,
357
- res,
358
- maxBytes: FEISHU_WEBHOOK_MAX_BODY_BYTES,
359
- timeoutMs: FEISHU_WEBHOOK_BODY_TIMEOUT_MS,
360
- profile: "pre-auth",
361
- });
362
- if (!body.ok || res.writableEnded) {
363
- return;
364
- }
365
- if (guard.isTripped()) {
366
- return;
367
- }
368
- const rawBody = body.value;
369
-
370
- // Reject invalid signatures before any JSON parsing to keep the auth boundary strict.
371
- if (
372
- !isFeishuWebhookSignatureValid({
373
- headers: req.headers,
374
- rawBody,
375
- encryptKey,
376
- })
377
- ) {
378
- respondText(res, 401, "Invalid signature");
379
- return;
380
- }
381
-
382
- const payload = parseFeishuWebhookPayload(rawBody);
383
- if (!payload) {
384
- respondText(res, 400, "Invalid JSON");
385
- return;
386
- }
387
-
388
- const { isChallenge, challenge } = Lark.generateChallenge(payload, {
389
- encryptKey,
390
- });
391
- if (isChallenge) {
392
- res.statusCode = 200;
393
- res.setHeader("Content-Type", "application/json; charset=utf-8");
394
- res.end(JSON.stringify(challenge));
395
- return;
396
- }
397
-
398
- const value = await eventDispatcher.invoke(buildFeishuWebhookEnvelope(req, payload), {
399
- needCheck: false,
400
- });
401
- if (!res.headersSent) {
402
- res.statusCode = 200;
403
- res.setHeader("Content-Type", "application/json; charset=utf-8");
404
- res.end(JSON.stringify(value));
405
- }
406
- } catch (err) {
407
- error(`feishu[${accountId}]: webhook handler error: ${String(err)}`);
408
- if (!res.headersSent) {
409
- respondText(res, 500, "Internal Server Error");
410
- }
411
- } finally {
412
- guard.dispose();
413
- }
414
- })();
415
- });
416
-
417
- httpServers.set(accountId, server);
418
-
419
- return new Promise((resolve, reject) => {
420
- const cleanup = () => {
421
- server.close();
422
- httpServers.delete(accountId);
423
- botOpenIds.delete(accountId);
424
- botNames.delete(accountId);
425
- };
426
-
427
- const handleAbort = () => {
428
- log(`feishu[${accountId}]: abort signal received, stopping Webhook server`);
429
- cleanup();
430
- resolve();
431
- };
432
-
433
- if (abortSignal?.aborted) {
434
- cleanup();
435
- resolve();
436
- return;
437
- }
438
-
439
- abortSignal?.addEventListener("abort", handleAbort, { once: true });
440
-
441
- server.listen(port, host, () => {
442
- log(`feishu[${accountId}]: Webhook server listening on ${host}:${port}`);
443
- });
444
-
445
- server.on("error", (err) => {
446
- error(`feishu[${accountId}]: Webhook server error: ${err}`);
447
- abortSignal?.removeEventListener("abort", handleAbort);
448
- reject(err);
449
- });
450
- });
451
- }
package/src/monitor.ts DELETED
@@ -1,100 +0,0 @@
1
- import type { ClawdbotConfig, RuntimeEnv } from "../runtime-api.js";
2
- import { listEnabledFeishuAccounts, resolveFeishuRuntimeAccount } from "./accounts.js";
3
- import { fetchBotIdentityForMonitor } from "./monitor.startup.js";
4
- import {
5
- clearFeishuWebhookRateLimitStateForTest,
6
- getFeishuWebhookRateLimitStateSizeForTest,
7
- isWebhookRateLimitedForTest,
8
- stopFeishuMonitorState,
9
- } from "./monitor.state.js";
10
-
11
- export type MonitorFeishuOpts = {
12
- config?: ClawdbotConfig;
13
- runtime?: RuntimeEnv;
14
- abortSignal?: AbortSignal;
15
- accountId?: string;
16
- };
17
-
18
- let monitorAccountRuntimePromise: Promise<typeof import("./monitor.account.js")> | undefined;
19
-
20
- async function loadMonitorAccountRuntime() {
21
- monitorAccountRuntimePromise ??= import("./monitor.account.js");
22
- return await monitorAccountRuntimePromise;
23
- }
24
-
25
- export {
26
- clearFeishuWebhookRateLimitStateForTest,
27
- getFeishuWebhookRateLimitStateSizeForTest,
28
- isWebhookRateLimitedForTest,
29
- };
30
-
31
- export async function monitorFeishuProvider(opts: MonitorFeishuOpts = {}): Promise<void> {
32
- const cfg = opts.config;
33
- if (!cfg) {
34
- throw new Error("Config is required for Feishu monitor");
35
- }
36
-
37
- const log = opts.runtime?.log ?? console.log;
38
-
39
- if (opts.accountId) {
40
- const account = resolveFeishuRuntimeAccount(
41
- { cfg, accountId: opts.accountId },
42
- { requireEventSecrets: true },
43
- );
44
- if (!account.enabled || !account.configured) {
45
- throw new Error(`Feishu account "${opts.accountId}" not configured or disabled`);
46
- }
47
- const { monitorSingleAccount } = await loadMonitorAccountRuntime();
48
- return monitorSingleAccount({
49
- cfg,
50
- account,
51
- runtime: opts.runtime,
52
- abortSignal: opts.abortSignal,
53
- });
54
- }
55
-
56
- const accounts = listEnabledFeishuAccounts(cfg);
57
- if (accounts.length === 0) {
58
- throw new Error("No enabled Feishu accounts configured");
59
- }
60
-
61
- log(
62
- `feishu: starting ${accounts.length} account(s): ${accounts.map((a) => a.accountId).join(", ")}`,
63
- );
64
-
65
- const { monitorSingleAccount } = await loadMonitorAccountRuntime();
66
- const monitorPromises: Promise<void>[] = [];
67
- for (const account of accounts) {
68
- if (opts.abortSignal?.aborted) {
69
- log("feishu: abort signal received during startup preflight; stopping startup");
70
- break;
71
- }
72
-
73
- // Probe sequentially so large multi-account startups do not burst Feishu's bot-info endpoint.
74
- const { botOpenId, botName } = await fetchBotIdentityForMonitor(account, {
75
- runtime: opts.runtime,
76
- abortSignal: opts.abortSignal,
77
- });
78
-
79
- if (opts.abortSignal?.aborted) {
80
- log("feishu: abort signal received during startup preflight; stopping startup");
81
- break;
82
- }
83
-
84
- monitorPromises.push(
85
- monitorSingleAccount({
86
- cfg,
87
- account,
88
- runtime: opts.runtime,
89
- abortSignal: opts.abortSignal,
90
- botOpenIdSource: { kind: "prefetched", botOpenId, botName },
91
- }),
92
- );
93
- }
94
-
95
- await Promise.all(monitorPromises);
96
- }
97
-
98
- export function stopFeishuMonitor(accountId?: string): void {
99
- stopFeishuMonitorState(accountId);
100
- }