@openclaw/feishu 2026.3.12 → 2026.5.1-beta.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 (188) hide show
  1. package/api.ts +31 -0
  2. package/channel-entry.ts +20 -0
  3. package/channel-plugin-api.ts +1 -0
  4. package/contract-api.ts +16 -0
  5. package/index.ts +70 -53
  6. package/openclaw.plugin.json +1653 -4
  7. package/package.json +32 -7
  8. package/runtime-api.ts +55 -0
  9. package/secret-contract-api.ts +5 -0
  10. package/security-contract-api.ts +1 -0
  11. package/session-key-api.ts +1 -0
  12. package/setup-api.ts +3 -0
  13. package/setup-entry.test.ts +14 -0
  14. package/setup-entry.ts +13 -0
  15. package/src/accounts.test.ts +115 -22
  16. package/src/accounts.ts +199 -117
  17. package/src/app-registration.ts +331 -0
  18. package/src/approval-auth.test.ts +24 -0
  19. package/src/approval-auth.ts +25 -0
  20. package/src/async.test.ts +35 -0
  21. package/src/async.ts +43 -1
  22. package/src/audio-preflight.runtime.ts +9 -0
  23. package/src/bitable.test.ts +131 -0
  24. package/src/bitable.ts +59 -22
  25. package/src/bot-content.ts +474 -0
  26. package/src/bot-group-name.test.ts +108 -0
  27. package/src/bot-runtime-api.ts +12 -0
  28. package/src/bot-sender-name.ts +125 -0
  29. package/src/bot.broadcast.test.ts +463 -0
  30. package/src/bot.card-action.test.ts +519 -5
  31. package/src/bot.checkBotMentioned.test.ts +92 -20
  32. package/src/bot.helpers.test.ts +118 -0
  33. package/src/bot.stripBotMention.test.ts +13 -21
  34. package/src/bot.test.ts +1334 -401
  35. package/src/bot.ts +798 -786
  36. package/src/card-action.ts +408 -40
  37. package/src/card-interaction.test.ts +129 -0
  38. package/src/card-interaction.ts +159 -0
  39. package/src/card-test-helpers.ts +47 -0
  40. package/src/card-ux-approval.ts +65 -0
  41. package/src/card-ux-launcher.test.ts +99 -0
  42. package/src/card-ux-launcher.ts +121 -0
  43. package/src/card-ux-shared.ts +33 -0
  44. package/src/channel-runtime-api.ts +16 -0
  45. package/src/channel.runtime.ts +47 -0
  46. package/src/channel.test.ts +914 -3
  47. package/src/channel.ts +1252 -309
  48. package/src/chat-schema.ts +5 -4
  49. package/src/chat.test.ts +84 -28
  50. package/src/chat.ts +68 -10
  51. package/src/client.test.ts +212 -103
  52. package/src/client.ts +115 -21
  53. package/src/comment-dispatcher-runtime-api.ts +6 -0
  54. package/src/comment-dispatcher.test.ts +169 -0
  55. package/src/comment-dispatcher.ts +107 -0
  56. package/src/comment-handler-runtime-api.ts +3 -0
  57. package/src/comment-handler.test.ts +486 -0
  58. package/src/comment-handler.ts +309 -0
  59. package/src/comment-reaction.test.ts +166 -0
  60. package/src/comment-reaction.ts +259 -0
  61. package/src/comment-shared.test.ts +182 -0
  62. package/src/comment-shared.ts +365 -0
  63. package/src/comment-target.ts +44 -0
  64. package/src/config-schema.test.ts +77 -25
  65. package/src/config-schema.ts +31 -4
  66. package/src/conversation-id.test.ts +18 -0
  67. package/src/conversation-id.ts +199 -0
  68. package/src/dedup-runtime-api.ts +1 -0
  69. package/src/dedup.ts +76 -35
  70. package/src/directory.static.ts +61 -0
  71. package/src/directory.test.ts +119 -20
  72. package/src/directory.ts +61 -91
  73. package/src/doc-schema.ts +1 -1
  74. package/src/docx-batch-insert.test.ts +39 -38
  75. package/src/docx-batch-insert.ts +55 -19
  76. package/src/docx-color-text.ts +9 -4
  77. package/src/docx-table-ops.test.ts +53 -0
  78. package/src/docx-table-ops.ts +52 -34
  79. package/src/docx-types.ts +38 -0
  80. package/src/docx.account-selection.test.ts +12 -3
  81. package/src/docx.test.ts +314 -74
  82. package/src/docx.ts +278 -122
  83. package/src/drive-schema.ts +47 -1
  84. package/src/drive.test.ts +1219 -0
  85. package/src/drive.ts +614 -13
  86. package/src/dynamic-agent.ts +10 -4
  87. package/src/event-types.ts +45 -0
  88. package/src/external-keys.ts +1 -1
  89. package/src/lifecycle.test-support.ts +220 -0
  90. package/src/media.test.ts +413 -87
  91. package/src/media.ts +488 -154
  92. package/src/mention-target.types.ts +5 -0
  93. package/src/mention.ts +32 -51
  94. package/src/message-action-contract.ts +13 -0
  95. package/src/monitor-state-runtime-api.ts +7 -0
  96. package/src/monitor-transport-runtime-api.ts +7 -0
  97. package/src/monitor.account.ts +220 -313
  98. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  99. package/src/monitor.bot-identity.ts +86 -0
  100. package/src/monitor.bot-menu-handler.ts +165 -0
  101. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  102. package/src/monitor.bot-menu.test.ts +178 -0
  103. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  104. package/src/monitor.card-action.lifecycle.test-support.ts +373 -0
  105. package/src/monitor.cleanup.test.ts +376 -0
  106. package/src/monitor.comment-notice-handler.ts +105 -0
  107. package/src/monitor.comment.test.ts +937 -0
  108. package/src/monitor.comment.ts +1386 -0
  109. package/src/monitor.lifecycle.test.ts +4 -0
  110. package/src/monitor.message-handler.ts +339 -0
  111. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  112. package/src/monitor.reaction.test.ts +194 -92
  113. package/src/monitor.reply-once.lifecycle.test-support.ts +190 -0
  114. package/src/monitor.startup.test.ts +24 -36
  115. package/src/monitor.startup.ts +26 -16
  116. package/src/monitor.state.ts +20 -5
  117. package/src/monitor.synthetic-error.ts +18 -0
  118. package/src/monitor.test-mocks.ts +2 -2
  119. package/src/monitor.transport.ts +297 -39
  120. package/src/monitor.ts +15 -10
  121. package/src/monitor.webhook-e2e.test.ts +272 -0
  122. package/src/monitor.webhook-security.test.ts +125 -91
  123. package/src/monitor.webhook.test-helpers.ts +116 -0
  124. package/src/outbound-runtime-api.ts +1 -0
  125. package/src/outbound.test.ts +627 -53
  126. package/src/outbound.ts +623 -81
  127. package/src/perm-schema.ts +1 -1
  128. package/src/perm.ts +1 -7
  129. package/src/pins.ts +108 -0
  130. package/src/policy.test.ts +297 -117
  131. package/src/policy.ts +142 -29
  132. package/src/post.ts +7 -6
  133. package/src/probe.test.ts +122 -118
  134. package/src/probe.ts +26 -16
  135. package/src/processing-claims.ts +59 -0
  136. package/src/qr-terminal.ts +1 -0
  137. package/src/reactions.ts +23 -60
  138. package/src/reasoning-preview.test.ts +59 -0
  139. package/src/reasoning-preview.ts +20 -0
  140. package/src/reply-dispatcher-runtime-api.ts +7 -0
  141. package/src/reply-dispatcher.test.ts +721 -168
  142. package/src/reply-dispatcher.ts +422 -172
  143. package/src/runtime.ts +6 -3
  144. package/src/secret-contract.ts +145 -0
  145. package/src/secret-input.ts +1 -13
  146. package/src/security-audit-shared.ts +69 -0
  147. package/src/security-audit.test.ts +61 -0
  148. package/src/security-audit.ts +1 -0
  149. package/src/send-result.ts +1 -1
  150. package/src/send-target.test.ts +9 -3
  151. package/src/send-target.ts +10 -4
  152. package/src/send.reply-fallback.test.ts +127 -42
  153. package/src/send.test.ts +386 -4
  154. package/src/send.ts +486 -164
  155. package/src/sequential-key.test.ts +72 -0
  156. package/src/sequential-key.ts +28 -0
  157. package/src/sequential-queue.test.ts +92 -0
  158. package/src/sequential-queue.ts +16 -0
  159. package/src/session-conversation.ts +42 -0
  160. package/src/session-route.ts +48 -0
  161. package/src/setup-core.ts +51 -0
  162. package/src/{onboarding.test.ts → setup-surface.test.ts} +52 -21
  163. package/src/setup-surface.ts +581 -0
  164. package/src/streaming-card.test.ts +138 -2
  165. package/src/streaming-card.ts +134 -18
  166. package/src/subagent-hooks.test.ts +603 -0
  167. package/src/subagent-hooks.ts +397 -0
  168. package/src/targets.ts +3 -13
  169. package/src/test-support/lifecycle-test-support.ts +479 -0
  170. package/src/thread-bindings.test.ts +143 -0
  171. package/src/thread-bindings.ts +330 -0
  172. package/src/tool-account-routing.test.ts +66 -8
  173. package/src/tool-account.test.ts +44 -0
  174. package/src/tool-account.ts +40 -17
  175. package/src/tool-factory-test-harness.ts +11 -8
  176. package/src/tool-result.ts +3 -1
  177. package/src/tools-config.ts +1 -1
  178. package/src/types.ts +16 -15
  179. package/src/typing.ts +10 -6
  180. package/src/wiki-schema.ts +1 -1
  181. package/src/wiki.ts +1 -7
  182. package/subagent-hooks-api.ts +31 -0
  183. package/tsconfig.json +16 -0
  184. package/src/feishu-command-handler.ts +0 -59
  185. package/src/onboarding.status.test.ts +0 -25
  186. package/src/onboarding.ts +0 -489
  187. package/src/send-message.ts +0 -71
  188. package/src/targets.test.ts +0 -70
package/src/monitor.ts CHANGED
@@ -1,10 +1,5 @@
1
- import type { ClawdbotConfig, RuntimeEnv } from "openclaw/plugin-sdk/feishu";
2
- import { listEnabledFeishuAccounts, resolveFeishuAccount } from "./accounts.js";
3
- import {
4
- monitorSingleAccount,
5
- resolveReactionSyntheticEvent,
6
- type FeishuReactionCreatedEvent,
7
- } from "./monitor.account.js";
1
+ import type { ClawdbotConfig, RuntimeEnv } from "../runtime-api.js";
2
+ import { listEnabledFeishuAccounts, resolveFeishuRuntimeAccount } from "./accounts.js";
8
3
  import { fetchBotIdentityForMonitor } from "./monitor.startup.js";
9
4
  import {
10
5
  clearFeishuWebhookRateLimitStateForTest,
@@ -20,13 +15,18 @@ export type MonitorFeishuOpts = {
20
15
  accountId?: string;
21
16
  };
22
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
+
23
25
  export {
24
26
  clearFeishuWebhookRateLimitStateForTest,
25
27
  getFeishuWebhookRateLimitStateSizeForTest,
26
28
  isWebhookRateLimitedForTest,
27
- resolveReactionSyntheticEvent,
28
29
  };
29
- export type { FeishuReactionCreatedEvent };
30
30
 
31
31
  export async function monitorFeishuProvider(opts: MonitorFeishuOpts = {}): Promise<void> {
32
32
  const cfg = opts.config;
@@ -37,10 +37,14 @@ export async function monitorFeishuProvider(opts: MonitorFeishuOpts = {}): Promi
37
37
  const log = opts.runtime?.log ?? console.log;
38
38
 
39
39
  if (opts.accountId) {
40
- const account = resolveFeishuAccount({ cfg, accountId: opts.accountId });
40
+ const account = resolveFeishuRuntimeAccount(
41
+ { cfg, accountId: opts.accountId },
42
+ { requireEventSecrets: true },
43
+ );
41
44
  if (!account.enabled || !account.configured) {
42
45
  throw new Error(`Feishu account "${opts.accountId}" not configured or disabled`);
43
46
  }
47
+ const { monitorSingleAccount } = await loadMonitorAccountRuntime();
44
48
  return monitorSingleAccount({
45
49
  cfg,
46
50
  account,
@@ -58,6 +62,7 @@ export async function monitorFeishuProvider(opts: MonitorFeishuOpts = {}): Promi
58
62
  `feishu: starting ${accounts.length} account(s): ${accounts.map((a) => a.accountId).join(", ")}`,
59
63
  );
60
64
 
65
+ const { monitorSingleAccount } = await loadMonitorAccountRuntime();
61
66
  const monitorPromises: Promise<void>[] = [];
62
67
  for (const account of accounts) {
63
68
  if (opts.abortSignal?.aborted) {
@@ -0,0 +1,272 @@
1
+ import crypto from "node:crypto";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+ import { createFeishuRuntimeMockModule } from "./monitor.test-mocks.js";
4
+ import { withRunningWebhookMonitor } from "./monitor.webhook.test-helpers.js";
5
+
6
+ const probeFeishuMock = vi.hoisted(() => vi.fn());
7
+
8
+ vi.mock("./probe.js", () => ({
9
+ probeFeishu: probeFeishuMock,
10
+ }));
11
+
12
+ vi.mock("./client.js", async () => {
13
+ const actual = await vi.importActual<typeof import("./client.js")>("./client.js");
14
+ return {
15
+ ...actual,
16
+ createFeishuWSClient: vi.fn(() => ({ start: vi.fn() })),
17
+ };
18
+ });
19
+
20
+ vi.mock("./runtime.js", () => createFeishuRuntimeMockModule());
21
+
22
+ import { monitorFeishuProvider, stopFeishuMonitor } from "./monitor.js";
23
+
24
+ function signFeishuPayload(params: {
25
+ encryptKey: string;
26
+ rawBody: string;
27
+ timestamp?: string;
28
+ nonce?: string;
29
+ }): Record<string, string> {
30
+ const timestamp = params.timestamp ?? "1711111111";
31
+ const nonce = params.nonce ?? "nonce-test";
32
+ const signature = crypto
33
+ .createHash("sha256")
34
+ .update(timestamp + nonce + params.encryptKey + params.rawBody)
35
+ .digest("hex");
36
+ return {
37
+ "content-type": "application/json",
38
+ "x-lark-request-timestamp": timestamp,
39
+ "x-lark-request-nonce": nonce,
40
+ "x-lark-signature": signature,
41
+ };
42
+ }
43
+
44
+ function encryptFeishuPayload(encryptKey: string, payload: Record<string, unknown>): string {
45
+ const iv = crypto.randomBytes(16);
46
+ const key = crypto.createHash("sha256").update(encryptKey).digest();
47
+ const cipher = crypto.createCipheriv("aes-256-cbc", key, iv);
48
+ const plaintext = Buffer.from(JSON.stringify(payload), "utf8");
49
+ const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
50
+ return Buffer.concat([iv, encrypted]).toString("base64");
51
+ }
52
+
53
+ async function postSignedPayload(url: string, payload: Record<string, unknown>) {
54
+ const rawBody = JSON.stringify(payload);
55
+ return await fetch(url, {
56
+ method: "POST",
57
+ headers: signFeishuPayload({ encryptKey: "encrypt_key", rawBody }),
58
+ body: rawBody,
59
+ });
60
+ }
61
+
62
+ afterEach(() => {
63
+ stopFeishuMonitor();
64
+ });
65
+
66
+ describe("Feishu webhook signed-request e2e", () => {
67
+ it("rejects invalid signatures with 401 instead of empty 200", async () => {
68
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
69
+
70
+ await withRunningWebhookMonitor(
71
+ {
72
+ accountId: "invalid-signature",
73
+ path: "/hook-e2e-invalid-signature",
74
+ verificationToken: "verify_token",
75
+ encryptKey: "encrypt_key",
76
+ },
77
+ monitorFeishuProvider,
78
+ async (url) => {
79
+ const payload = { type: "url_verification", challenge: "challenge-token" };
80
+ const rawBody = JSON.stringify(payload);
81
+ const response = await fetch(url, {
82
+ method: "POST",
83
+ headers: {
84
+ ...signFeishuPayload({ encryptKey: "wrong_key", rawBody }),
85
+ },
86
+ body: rawBody,
87
+ });
88
+
89
+ expect(response.status).toBe(401);
90
+ expect(await response.text()).toBe("Invalid signature");
91
+ },
92
+ );
93
+ });
94
+
95
+ it("rejects missing signature headers with 401", async () => {
96
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
97
+
98
+ await withRunningWebhookMonitor(
99
+ {
100
+ accountId: "missing-signature",
101
+ path: "/hook-e2e-missing-signature",
102
+ verificationToken: "verify_token",
103
+ encryptKey: "encrypt_key",
104
+ },
105
+ monitorFeishuProvider,
106
+ async (url) => {
107
+ const response = await fetch(url, {
108
+ method: "POST",
109
+ headers: { "content-type": "application/json" },
110
+ body: JSON.stringify({ type: "url_verification", challenge: "challenge-token" }),
111
+ });
112
+
113
+ expect(response.status).toBe(401);
114
+ expect(await response.text()).toBe("Invalid signature");
115
+ },
116
+ );
117
+ });
118
+
119
+ it("rejects malformed short signatures with 401", async () => {
120
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
121
+
122
+ await withRunningWebhookMonitor(
123
+ {
124
+ accountId: "short-signature",
125
+ path: "/hook-e2e-short-signature",
126
+ verificationToken: "verify_token",
127
+ encryptKey: "encrypt_key",
128
+ },
129
+ monitorFeishuProvider,
130
+ async (url) => {
131
+ const payload = { type: "url_verification", challenge: "challenge-token" };
132
+ const headers = signFeishuPayload({
133
+ encryptKey: "encrypt_key",
134
+ rawBody: JSON.stringify(payload),
135
+ });
136
+ headers["x-lark-signature"] = headers["x-lark-signature"].slice(0, 12);
137
+
138
+ const response = await fetch(url, {
139
+ method: "POST",
140
+ headers,
141
+ body: JSON.stringify(payload),
142
+ });
143
+
144
+ expect(response.status).toBe(401);
145
+ expect(await response.text()).toBe("Invalid signature");
146
+ },
147
+ );
148
+ });
149
+
150
+ it("returns 401 for unsigned invalid json before parsing", async () => {
151
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
152
+
153
+ await withRunningWebhookMonitor(
154
+ {
155
+ accountId: "invalid-json",
156
+ path: "/hook-e2e-invalid-json",
157
+ verificationToken: "verify_token",
158
+ encryptKey: "encrypt_key",
159
+ },
160
+ monitorFeishuProvider,
161
+ async (url) => {
162
+ const response = await fetch(url, {
163
+ method: "POST",
164
+ headers: { "content-type": "application/json" },
165
+ body: "{not-json",
166
+ });
167
+
168
+ expect(response.status).toBe(401);
169
+ expect(await response.text()).toBe("Invalid signature");
170
+ },
171
+ );
172
+ });
173
+
174
+ it("returns 400 for signed invalid json after signature validation", async () => {
175
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
176
+
177
+ await withRunningWebhookMonitor(
178
+ {
179
+ accountId: "signed-invalid-json",
180
+ path: "/hook-e2e-signed-invalid-json",
181
+ verificationToken: "verify_token",
182
+ encryptKey: "encrypt_key",
183
+ },
184
+ monitorFeishuProvider,
185
+ async (url) => {
186
+ const rawBody = "{not-json";
187
+ const response = await fetch(url, {
188
+ method: "POST",
189
+ headers: signFeishuPayload({ encryptKey: "encrypt_key", rawBody }),
190
+ body: rawBody,
191
+ });
192
+
193
+ expect(response.status).toBe(400);
194
+ expect(await response.text()).toBe("Invalid JSON");
195
+ },
196
+ );
197
+ });
198
+
199
+ it("accepts signed plaintext url_verification challenges end-to-end", async () => {
200
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
201
+
202
+ await withRunningWebhookMonitor(
203
+ {
204
+ accountId: "signed-challenge",
205
+ path: "/hook-e2e-signed-challenge",
206
+ verificationToken: "verify_token",
207
+ encryptKey: "encrypt_key",
208
+ },
209
+ monitorFeishuProvider,
210
+ async (url) => {
211
+ const payload = { type: "url_verification", challenge: "challenge-token" };
212
+ const response = await postSignedPayload(url, payload);
213
+
214
+ expect(response.status).toBe(200);
215
+ await expect(response.json()).resolves.toEqual({ challenge: "challenge-token" });
216
+ },
217
+ );
218
+ });
219
+
220
+ it("accepts signed non-challenge events and reaches the dispatcher", async () => {
221
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
222
+
223
+ await withRunningWebhookMonitor(
224
+ {
225
+ accountId: "signed-dispatch",
226
+ path: "/hook-e2e-signed-dispatch",
227
+ verificationToken: "verify_token",
228
+ encryptKey: "encrypt_key",
229
+ },
230
+ monitorFeishuProvider,
231
+ async (url) => {
232
+ const payload = {
233
+ schema: "2.0",
234
+ header: { event_type: "unknown.event" },
235
+ event: {},
236
+ };
237
+ const response = await postSignedPayload(url, payload);
238
+
239
+ expect(response.status).toBe(200);
240
+ expect(await response.text()).toContain("no unknown.event event handle");
241
+ },
242
+ );
243
+ });
244
+
245
+ it("accepts signed encrypted url_verification challenges end-to-end", async () => {
246
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
247
+
248
+ await withRunningWebhookMonitor(
249
+ {
250
+ accountId: "encrypted-challenge",
251
+ path: "/hook-e2e-encrypted-challenge",
252
+ verificationToken: "verify_token",
253
+ encryptKey: "encrypt_key",
254
+ },
255
+ monitorFeishuProvider,
256
+ async (url) => {
257
+ const payload = {
258
+ encrypt: encryptFeishuPayload("encrypt_key", {
259
+ type: "url_verification",
260
+ challenge: "encrypted-challenge-token",
261
+ }),
262
+ };
263
+ const response = await postSignedPayload(url, payload);
264
+
265
+ expect(response.status).toBe(200);
266
+ await expect(response.json()).resolves.toEqual({
267
+ challenge: "encrypted-challenge-token",
268
+ });
269
+ },
270
+ );
271
+ });
272
+ });
@@ -1,11 +1,14 @@
1
- import { createServer } from "node:http";
2
- import type { AddressInfo } from "node:net";
3
- import type { ClawdbotConfig } from "openclaw/plugin-sdk/feishu";
1
+ import { createConnection } from "node:net";
4
2
  import { afterEach, describe, expect, it, vi } from "vitest";
5
3
  import {
6
4
  createFeishuClientMockModule,
7
5
  createFeishuRuntimeMockModule,
8
6
  } from "./monitor.test-mocks.js";
7
+ import {
8
+ buildWebhookConfig,
9
+ getFreePort,
10
+ withRunningWebhookMonitor,
11
+ } from "./monitor.webhook.test-helpers.js";
9
12
 
10
13
  const probeFeishuMock = vi.hoisted(() => vi.fn());
11
14
 
@@ -25,6 +28,15 @@ vi.mock("@larksuiteoapi/node-sdk", () => ({
25
28
  ),
26
29
  }));
27
30
 
31
+ vi.mock("./monitor.state.js", async (importOriginal) => {
32
+ const actual = await importOriginal<typeof import("./monitor.state.js")>();
33
+ return {
34
+ ...actual,
35
+ FEISHU_WEBHOOK_BODY_TIMEOUT_MS: 50,
36
+ };
37
+ });
38
+
39
+ import type { RuntimeEnv } from "../runtime-api.js";
28
40
  import {
29
41
  clearFeishuWebhookRateLimitStateForTest,
30
42
  getFeishuWebhookRateLimitStateSizeForTest,
@@ -32,97 +44,48 @@ import {
32
44
  monitorFeishuProvider,
33
45
  stopFeishuMonitor,
34
46
  } from "./monitor.js";
47
+ import { monitorWebhook } from "./monitor.transport.js";
48
+ import type { ResolvedFeishuAccount } from "./types.js";
35
49
 
36
- async function getFreePort(): Promise<number> {
37
- const server = createServer();
38
- await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", () => resolve()));
39
- const address = server.address() as AddressInfo | null;
40
- if (!address) {
41
- throw new Error("missing server address");
42
- }
43
- await new Promise<void>((resolve) => server.close(() => resolve()));
44
- return address.port;
45
- }
46
-
47
- async function waitUntilServerReady(url: string): Promise<void> {
48
- for (let i = 0; i < 50; i += 1) {
49
- try {
50
- const response = await fetch(url, { method: "GET" });
51
- if (response.status >= 200 && response.status < 500) {
52
- return;
53
- }
54
- } catch {
55
- // retry
56
- }
57
- await new Promise((resolve) => setTimeout(resolve, 20));
58
- }
59
- throw new Error(`server did not start: ${url}`);
60
- }
61
-
62
- function buildConfig(params: {
63
- accountId: string;
64
- path: string;
65
- port: number;
66
- verificationToken?: string;
67
- encryptKey?: string;
68
- }): ClawdbotConfig {
69
- return {
70
- channels: {
71
- feishu: {
72
- enabled: true,
73
- accounts: {
74
- [params.accountId]: {
75
- enabled: true,
76
- appId: "cli_test",
77
- appSecret: "secret_test", // pragma: allowlist secret
78
- connectionMode: "webhook",
79
- webhookHost: "127.0.0.1",
80
- webhookPort: params.port,
81
- webhookPath: params.path,
82
- encryptKey: params.encryptKey,
83
- verificationToken: params.verificationToken,
84
- },
85
- },
50
+ async function waitForSlowBodyTimeoutResponse(
51
+ url: string,
52
+ timeoutMs: number,
53
+ ): Promise<{ body: string; elapsedMs: number }> {
54
+ return await new Promise<{ body: string; elapsedMs: number }>((resolve, reject) => {
55
+ const target = new URL(url);
56
+ const startedAt = Date.now();
57
+ let response = "";
58
+ const socket = createConnection(
59
+ {
60
+ host: target.hostname,
61
+ port: Number(target.port),
86
62
  },
87
- },
88
- } as ClawdbotConfig;
89
- }
63
+ () => {
64
+ socket.write(`POST ${target.pathname} HTTP/1.1\r\n`);
65
+ socket.write(`Host: ${target.hostname}\r\n`);
66
+ socket.write("Content-Type: application/json\r\n");
67
+ socket.write("Content-Length: 65536\r\n");
68
+ socket.write("\r\n");
69
+ socket.write('{"type":"url_verification"');
70
+ },
71
+ );
90
72
 
91
- async function withRunningWebhookMonitor(
92
- params: {
93
- accountId: string;
94
- path: string;
95
- verificationToken: string;
96
- encryptKey: string;
97
- },
98
- run: (url: string) => Promise<void>,
99
- ) {
100
- const port = await getFreePort();
101
- const cfg = buildConfig({
102
- accountId: params.accountId,
103
- path: params.path,
104
- port,
105
- encryptKey: params.encryptKey,
106
- verificationToken: params.verificationToken,
107
- });
73
+ socket.setEncoding("utf8");
74
+ socket.on("error", () => {});
75
+ socket.on("data", (chunk) => {
76
+ response += chunk;
77
+ if (response.includes("Request body timeout")) {
78
+ clearTimeout(failTimer);
79
+ socket.destroy();
80
+ resolve({ body: response, elapsedMs: Date.now() - startedAt });
81
+ }
82
+ });
108
83
 
109
- const abortController = new AbortController();
110
- const runtime = { log: vi.fn(), error: vi.fn(), exit: vi.fn() };
111
- const monitorPromise = monitorFeishuProvider({
112
- config: cfg,
113
- runtime,
114
- abortSignal: abortController.signal,
84
+ const failTimer = setTimeout(() => {
85
+ socket.destroy();
86
+ reject(new Error(`timeout response did not arrive within ${timeoutMs}ms`));
87
+ }, timeoutMs);
115
88
  });
116
-
117
- const url = `http://127.0.0.1:${port}${params.path}`;
118
- await waitUntilServerReady(url);
119
-
120
- try {
121
- await run(url);
122
- } finally {
123
- abortController.abort();
124
- await monitorPromise;
125
- }
126
89
  }
127
90
 
128
91
  afterEach(() => {
@@ -134,7 +97,7 @@ describe("Feishu webhook security hardening", () => {
134
97
  it("rejects webhook mode without verificationToken", async () => {
135
98
  probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
136
99
 
137
- const cfg = buildConfig({
100
+ const cfg = buildWebhookConfig({
138
101
  accountId: "missing-token",
139
102
  path: "/hook-missing-token",
140
103
  port: await getFreePort(),
@@ -148,7 +111,7 @@ describe("Feishu webhook security hardening", () => {
148
111
  it("rejects webhook mode without encryptKey", async () => {
149
112
  probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
150
113
 
151
- const cfg = buildConfig({
114
+ const cfg = buildWebhookConfig({
152
115
  accountId: "missing-encrypt-key",
153
116
  path: "/hook-missing-encrypt",
154
117
  port: await getFreePort(),
@@ -158,6 +121,33 @@ describe("Feishu webhook security hardening", () => {
158
121
  await expect(monitorFeishuProvider({ config: cfg })).rejects.toThrow(/requires encryptKey/i);
159
122
  });
160
123
 
124
+ it("refuses to start the webhook transport without encryptKey", async () => {
125
+ const account = {
126
+ accountId: "transport-missing-encrypt-key",
127
+ config: {
128
+ enabled: true,
129
+ connectionMode: "webhook",
130
+ webhookHost: "127.0.0.1",
131
+ webhookPort: await getFreePort(),
132
+ webhookPath: "/hook-transport-missing-encrypt",
133
+ },
134
+ } as ResolvedFeishuAccount;
135
+
136
+ await expect(
137
+ monitorWebhook({
138
+ account,
139
+ accountId: account.accountId,
140
+ runtime: {
141
+ log: vi.fn(),
142
+ error: vi.fn(),
143
+ exit: vi.fn(),
144
+ } as RuntimeEnv,
145
+ abortSignal: new AbortController().signal,
146
+ eventDispatcher: {} as never,
147
+ }),
148
+ ).rejects.toThrow(/requires encryptKey/i);
149
+ });
150
+
161
151
  it("returns 415 for POST requests without json content type", async () => {
162
152
  probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
163
153
  await withRunningWebhookMonitor(
@@ -167,6 +157,7 @@ describe("Feishu webhook security hardening", () => {
167
157
  verificationToken: "verify_token",
168
158
  encryptKey: "encrypt_key",
169
159
  },
160
+ monitorFeishuProvider,
170
161
  async (url) => {
171
162
  const response = await fetch(url, {
172
163
  method: "POST",
@@ -180,6 +171,48 @@ describe("Feishu webhook security hardening", () => {
180
171
  );
181
172
  });
182
173
 
174
+ it("rejects oversized unsigned webhook bodies with 413 before signature verification", async () => {
175
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
176
+ await withRunningWebhookMonitor(
177
+ {
178
+ accountId: "payload-too-large",
179
+ path: "/hook-payload-too-large",
180
+ verificationToken: "verify_token",
181
+ encryptKey: "encrypt_key",
182
+ },
183
+ monitorFeishuProvider,
184
+ async (url) => {
185
+ const response = await fetch(url, {
186
+ method: "POST",
187
+ headers: { "content-type": "application/json" },
188
+ body: JSON.stringify({ payload: "x".repeat(70 * 1024) }),
189
+ });
190
+
191
+ expect(response.status).toBe(413);
192
+ expect(await response.text()).toBe("Payload too large");
193
+ },
194
+ );
195
+ });
196
+
197
+ it("drops slow-body webhook requests within the tightened pre-auth timeout", async () => {
198
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
199
+ await withRunningWebhookMonitor(
200
+ {
201
+ accountId: "slow-body-timeout",
202
+ path: "/hook-slow-body-timeout",
203
+ verificationToken: "verify_token",
204
+ encryptKey: "encrypt_key",
205
+ },
206
+ monitorFeishuProvider,
207
+ async (url) => {
208
+ const result = await waitForSlowBodyTimeoutResponse(url, 1_000);
209
+ expect(result.body).toContain("408 Request Timeout");
210
+ expect(result.body).toContain("Request body timeout");
211
+ expect(result.elapsedMs).toBeLessThan(500);
212
+ },
213
+ );
214
+ });
215
+
183
216
  it("rate limits webhook burst traffic with 429", async () => {
184
217
  probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
185
218
  await withRunningWebhookMonitor(
@@ -189,6 +222,7 @@ describe("Feishu webhook security hardening", () => {
189
222
  verificationToken: "verify_token",
190
223
  encryptKey: "encrypt_key",
191
224
  },
225
+ monitorFeishuProvider,
192
226
  async (url) => {
193
227
  let saw429 = false;
194
228
  for (let i = 0; i < 130; i += 1) {