@kodelyth/feishu 2026.5.39 → 2026.5.42

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 (238) hide show
  1. package/api.ts +32 -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/dist/accounts-D0ow-lRb.js +429 -0
  6. package/dist/api.js +2308 -0
  7. package/dist/app-registration-DBSnysKJ.js +184 -0
  8. package/dist/audio-preflight.runtime-Dpjbn-7r.js +7 -0
  9. package/dist/channel-13WQvQ0u.js +2115 -0
  10. package/dist/channel-entry.js +22 -0
  11. package/dist/channel-plugin-api.js +2 -0
  12. package/dist/channel.runtime-JMJonrJ4.js +729 -0
  13. package/dist/client-D1pzbBGo.js +157 -0
  14. package/dist/contract-api.js +9 -0
  15. package/dist/conversation-id-_58ecqlx.js +139 -0
  16. package/dist/drive-CgHOluXx.js +883 -0
  17. package/dist/index.js +68 -0
  18. package/dist/monitor-oWptK0zL.js +60 -0
  19. package/dist/monitor.account-DHaWlslg.js +5207 -0
  20. package/dist/monitor.state-C211a4tX.js +100 -0
  21. package/dist/probe-CF4duEpK.js +149 -0
  22. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  23. package/dist/runtime-DSh5rL_d.js +8 -0
  24. package/dist/runtime-api.js +14 -0
  25. package/dist/secret-contract-NSee-WzN.js +119 -0
  26. package/dist/secret-contract-api.js +2 -0
  27. package/dist/security-audit-DWVC0vSK.js +11 -0
  28. package/dist/security-audit-shared-Dpcwxeft.js +38 -0
  29. package/dist/security-contract-api.js +2 -0
  30. package/dist/send-DfZuV4Fi.js +1212 -0
  31. package/dist/session-conversation-Duaukbnl.js +27 -0
  32. package/dist/session-key-api.js +2 -0
  33. package/dist/setup-api.js +2 -0
  34. package/dist/setup-entry.js +15 -0
  35. package/dist/subagent-hooks-Dtegs0kh.js +235 -0
  36. package/dist/subagent-hooks-api.js +23 -0
  37. package/dist/targets-DFskxX4p.js +48 -0
  38. package/dist/thread-bindings-DI7lVSOE.js +222 -0
  39. package/index.ts +82 -0
  40. package/klaw.plugin.json +47 -1712
  41. package/package.json +4 -4
  42. package/runtime-api.ts +52 -0
  43. package/secret-contract-api.ts +5 -0
  44. package/security-contract-api.ts +1 -0
  45. package/session-key-api.ts +1 -0
  46. package/setup-api.ts +3 -0
  47. package/setup-entry.test.ts +19 -0
  48. package/setup-entry.ts +13 -0
  49. package/src/accounts.test.ts +480 -0
  50. package/src/accounts.ts +333 -0
  51. package/src/agent-config.ts +21 -0
  52. package/src/app-registration.ts +331 -0
  53. package/src/approval-auth.test.ts +24 -0
  54. package/src/approval-auth.ts +25 -0
  55. package/src/async.test.ts +35 -0
  56. package/src/async.ts +104 -0
  57. package/src/audio-preflight.runtime.ts +9 -0
  58. package/src/bitable.test.ts +136 -0
  59. package/src/bitable.ts +762 -0
  60. package/src/bot-content.ts +485 -0
  61. package/src/bot-group-name.test.ts +116 -0
  62. package/src/bot-runtime-api.ts +12 -0
  63. package/src/bot-sender-name.ts +125 -0
  64. package/src/bot.broadcast.test.ts +523 -0
  65. package/src/bot.card-action.test.ts +552 -0
  66. package/src/bot.checkBotMentioned.test.ts +265 -0
  67. package/src/bot.helpers.test.ts +135 -0
  68. package/src/bot.stripBotMention.test.ts +126 -0
  69. package/src/bot.test.ts +3671 -0
  70. package/src/bot.ts +1703 -0
  71. package/src/card-action.ts +447 -0
  72. package/src/card-interaction.test.ts +131 -0
  73. package/src/card-interaction.ts +159 -0
  74. package/src/card-test-helpers.ts +54 -0
  75. package/src/card-ux-approval.ts +65 -0
  76. package/src/card-ux-launcher.test.ts +106 -0
  77. package/src/card-ux-launcher.ts +121 -0
  78. package/src/card-ux-shared.ts +33 -0
  79. package/src/channel-runtime-api.ts +16 -0
  80. package/src/channel.runtime.ts +47 -0
  81. package/src/channel.test.ts +1151 -0
  82. package/src/channel.ts +1423 -0
  83. package/src/chat-schema.ts +25 -0
  84. package/src/chat.test.ts +240 -0
  85. package/src/chat.ts +188 -0
  86. package/src/client-timeout.ts +42 -0
  87. package/src/client.test.ts +447 -0
  88. package/src/client.ts +262 -0
  89. package/src/comment-dispatcher-runtime-api.ts +6 -0
  90. package/src/comment-dispatcher.test.ts +185 -0
  91. package/src/comment-dispatcher.ts +107 -0
  92. package/src/comment-handler-runtime-api.ts +3 -0
  93. package/src/comment-handler.test.ts +592 -0
  94. package/src/comment-handler.ts +303 -0
  95. package/src/comment-reaction.test.ts +138 -0
  96. package/src/comment-reaction.ts +259 -0
  97. package/src/comment-shared.test.ts +183 -0
  98. package/src/comment-shared.ts +406 -0
  99. package/src/comment-target.ts +44 -0
  100. package/src/config-schema.test.ts +326 -0
  101. package/src/config-schema.ts +335 -0
  102. package/src/conversation-id.test.ts +18 -0
  103. package/src/conversation-id.ts +199 -0
  104. package/src/dedup-runtime-api.ts +1 -0
  105. package/src/dedup.ts +141 -0
  106. package/src/dedupe-key.ts +72 -0
  107. package/src/directory.static.ts +61 -0
  108. package/src/directory.test.ts +141 -0
  109. package/src/directory.ts +124 -0
  110. package/src/doc-schema.ts +182 -0
  111. package/src/docx-batch-insert.test.ts +116 -0
  112. package/src/docx-batch-insert.ts +223 -0
  113. package/src/docx-color-text.ts +154 -0
  114. package/src/docx-table-ops.test.ts +53 -0
  115. package/src/docx-table-ops.ts +316 -0
  116. package/src/docx-types.ts +38 -0
  117. package/src/docx.account-selection.test.ts +95 -0
  118. package/src/docx.test.ts +701 -0
  119. package/src/docx.ts +1596 -0
  120. package/src/drive-schema.ts +92 -0
  121. package/src/drive.test.ts +1237 -0
  122. package/src/drive.ts +829 -0
  123. package/src/dynamic-agent.test.ts +155 -0
  124. package/src/dynamic-agent.ts +143 -0
  125. package/src/event-types.ts +45 -0
  126. package/src/external-keys.test.ts +20 -0
  127. package/src/external-keys.ts +19 -0
  128. package/src/lifecycle.test-support.ts +220 -0
  129. package/src/media.test.ts +955 -0
  130. package/src/media.ts +1105 -0
  131. package/src/mention-target.types.ts +5 -0
  132. package/src/mention.ts +114 -0
  133. package/src/message-action-contract.ts +13 -0
  134. package/src/monitor-state-runtime-api.ts +7 -0
  135. package/src/monitor-transport-runtime-api.ts +10 -0
  136. package/src/monitor.account.ts +492 -0
  137. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +219 -0
  138. package/src/monitor.bot-identity.ts +86 -0
  139. package/src/monitor.bot-menu-handler.ts +165 -0
  140. package/src/monitor.bot-menu.lifecycle.test-support.ts +224 -0
  141. package/src/monitor.bot-menu.test.ts +188 -0
  142. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +264 -0
  143. package/src/monitor.card-action.lifecycle.test-support.ts +421 -0
  144. package/src/monitor.cleanup.test.ts +383 -0
  145. package/src/monitor.comment-notice-handler.ts +105 -0
  146. package/src/monitor.comment.test.ts +967 -0
  147. package/src/monitor.comment.ts +1386 -0
  148. package/src/monitor.lifecycle.test.ts +4 -0
  149. package/src/monitor.message-handler.ts +350 -0
  150. package/src/monitor.reaction.lifecycle.test-support.ts +68 -0
  151. package/src/monitor.reaction.test.ts +739 -0
  152. package/src/monitor.startup.test.ts +213 -0
  153. package/src/monitor.startup.ts +74 -0
  154. package/src/monitor.state.defaults.test.ts +46 -0
  155. package/src/monitor.state.ts +170 -0
  156. package/src/monitor.synthetic-error.ts +18 -0
  157. package/src/monitor.test-mocks.ts +46 -0
  158. package/src/monitor.transport.ts +451 -0
  159. package/src/monitor.ts +100 -0
  160. package/src/monitor.webhook-e2e.test.ts +279 -0
  161. package/src/monitor.webhook-security.test.ts +389 -0
  162. package/src/monitor.webhook.test-helpers.ts +116 -0
  163. package/src/outbound-runtime-api.ts +1 -0
  164. package/src/outbound.test.ts +1118 -0
  165. package/src/outbound.ts +785 -0
  166. package/src/perm-schema.ts +52 -0
  167. package/src/perm.ts +170 -0
  168. package/src/pins.ts +108 -0
  169. package/src/policy.test.ts +223 -0
  170. package/src/policy.ts +318 -0
  171. package/src/post.test.ts +105 -0
  172. package/src/post.ts +275 -0
  173. package/src/probe.test.ts +283 -0
  174. package/src/probe.ts +166 -0
  175. package/src/processing-claims.ts +59 -0
  176. package/src/qr-terminal.ts +1 -0
  177. package/src/reactions.ts +123 -0
  178. package/src/reasoning-preview.test.ts +113 -0
  179. package/src/reasoning-preview.ts +28 -0
  180. package/src/reply-dispatcher-runtime-api.ts +7 -0
  181. package/src/reply-dispatcher.test.ts +1513 -0
  182. package/src/reply-dispatcher.ts +748 -0
  183. package/src/runtime.ts +9 -0
  184. package/src/secret-contract.ts +145 -0
  185. package/src/secret-input.ts +1 -0
  186. package/src/security-audit-shared.ts +69 -0
  187. package/src/security-audit.test.ts +59 -0
  188. package/src/security-audit.ts +1 -0
  189. package/src/send-result.ts +80 -0
  190. package/src/send-target.test.ts +86 -0
  191. package/src/send-target.ts +35 -0
  192. package/src/send.reply-fallback.test.ts +417 -0
  193. package/src/send.test.ts +621 -0
  194. package/src/send.ts +861 -0
  195. package/src/sequential-key.test.ts +72 -0
  196. package/src/sequential-key.ts +25 -0
  197. package/src/sequential-queue.test.ts +165 -0
  198. package/src/sequential-queue.ts +86 -0
  199. package/src/session-conversation.ts +42 -0
  200. package/src/session-route.ts +48 -0
  201. package/src/setup-core.ts +51 -0
  202. package/src/setup-surface.test.ts +484 -0
  203. package/src/setup-surface.ts +618 -0
  204. package/src/streaming-card.test.ts +397 -0
  205. package/src/streaming-card.ts +571 -0
  206. package/src/subagent-hooks.test.ts +627 -0
  207. package/src/subagent-hooks.ts +413 -0
  208. package/src/targets.ts +97 -0
  209. package/src/test-support/lifecycle-test-support.ts +454 -0
  210. package/src/thread-bindings.test.ts +180 -0
  211. package/src/thread-bindings.ts +331 -0
  212. package/src/tool-account-routing.test.ts +250 -0
  213. package/src/tool-account.test.ts +44 -0
  214. package/src/tool-account.ts +93 -0
  215. package/src/tool-factory-test-harness.ts +79 -0
  216. package/src/tool-result.test.ts +32 -0
  217. package/src/tool-result.ts +16 -0
  218. package/src/tools-config.test.ts +21 -0
  219. package/src/tools-config.ts +22 -0
  220. package/src/types.ts +106 -0
  221. package/src/typing.test.ts +144 -0
  222. package/src/typing.ts +214 -0
  223. package/src/wiki-schema.ts +69 -0
  224. package/src/wiki.ts +270 -0
  225. package/subagent-hooks-api.ts +31 -0
  226. package/tsconfig.json +16 -0
  227. package/api.js +0 -7
  228. package/channel-entry.js +0 -7
  229. package/channel-plugin-api.js +0 -7
  230. package/contract-api.js +0 -7
  231. package/index.js +0 -7
  232. package/runtime-api.js +0 -7
  233. package/secret-contract-api.js +0 -7
  234. package/security-contract-api.js +0 -7
  235. package/session-key-api.js +0 -7
  236. package/setup-api.js +0 -7
  237. package/setup-entry.js +0 -7
  238. package/subagent-hooks-api.js +0 -7
@@ -0,0 +1,279 @@
1
+ import crypto from "node:crypto";
2
+ import { afterAll, 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
+ afterAll(() => {
67
+ vi.doUnmock("./probe.js");
68
+ vi.doUnmock("./client.js");
69
+ vi.doUnmock("./runtime.js");
70
+ vi.resetModules();
71
+ });
72
+
73
+ describe("Feishu webhook signed-request e2e", () => {
74
+ it("rejects invalid signatures with 401 instead of empty 200", async () => {
75
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
76
+
77
+ await withRunningWebhookMonitor(
78
+ {
79
+ accountId: "invalid-signature",
80
+ path: "/hook-e2e-invalid-signature",
81
+ verificationToken: "verify_token",
82
+ encryptKey: "encrypt_key",
83
+ },
84
+ monitorFeishuProvider,
85
+ async (url) => {
86
+ const payload = { type: "url_verification", challenge: "challenge-token" };
87
+ const rawBody = JSON.stringify(payload);
88
+ const response = await fetch(url, {
89
+ method: "POST",
90
+ headers: {
91
+ ...signFeishuPayload({ encryptKey: "wrong_key", rawBody }),
92
+ },
93
+ body: rawBody,
94
+ });
95
+
96
+ expect(response.status).toBe(401);
97
+ expect(await response.text()).toBe("Invalid signature");
98
+ },
99
+ );
100
+ });
101
+
102
+ it("rejects missing signature headers with 401", async () => {
103
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
104
+
105
+ await withRunningWebhookMonitor(
106
+ {
107
+ accountId: "missing-signature",
108
+ path: "/hook-e2e-missing-signature",
109
+ verificationToken: "verify_token",
110
+ encryptKey: "encrypt_key",
111
+ },
112
+ monitorFeishuProvider,
113
+ async (url) => {
114
+ const response = await fetch(url, {
115
+ method: "POST",
116
+ headers: { "content-type": "application/json" },
117
+ body: JSON.stringify({ type: "url_verification", challenge: "challenge-token" }),
118
+ });
119
+
120
+ expect(response.status).toBe(401);
121
+ expect(await response.text()).toBe("Invalid signature");
122
+ },
123
+ );
124
+ });
125
+
126
+ it("rejects malformed short signatures with 401", async () => {
127
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
128
+
129
+ await withRunningWebhookMonitor(
130
+ {
131
+ accountId: "short-signature",
132
+ path: "/hook-e2e-short-signature",
133
+ verificationToken: "verify_token",
134
+ encryptKey: "encrypt_key",
135
+ },
136
+ monitorFeishuProvider,
137
+ async (url) => {
138
+ const payload = { type: "url_verification", challenge: "challenge-token" };
139
+ const headers = signFeishuPayload({
140
+ encryptKey: "encrypt_key",
141
+ rawBody: JSON.stringify(payload),
142
+ });
143
+ headers["x-lark-signature"] = headers["x-lark-signature"].slice(0, 12);
144
+
145
+ const response = await fetch(url, {
146
+ method: "POST",
147
+ headers,
148
+ body: JSON.stringify(payload),
149
+ });
150
+
151
+ expect(response.status).toBe(401);
152
+ expect(await response.text()).toBe("Invalid signature");
153
+ },
154
+ );
155
+ });
156
+
157
+ it("returns 401 for unsigned invalid json before parsing", async () => {
158
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
159
+
160
+ await withRunningWebhookMonitor(
161
+ {
162
+ accountId: "invalid-json",
163
+ path: "/hook-e2e-invalid-json",
164
+ verificationToken: "verify_token",
165
+ encryptKey: "encrypt_key",
166
+ },
167
+ monitorFeishuProvider,
168
+ async (url) => {
169
+ const response = await fetch(url, {
170
+ method: "POST",
171
+ headers: { "content-type": "application/json" },
172
+ body: "{not-json",
173
+ });
174
+
175
+ expect(response.status).toBe(401);
176
+ expect(await response.text()).toBe("Invalid signature");
177
+ },
178
+ );
179
+ });
180
+
181
+ it("returns 400 for signed invalid json after signature validation", async () => {
182
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
183
+
184
+ await withRunningWebhookMonitor(
185
+ {
186
+ accountId: "signed-invalid-json",
187
+ path: "/hook-e2e-signed-invalid-json",
188
+ verificationToken: "verify_token",
189
+ encryptKey: "encrypt_key",
190
+ },
191
+ monitorFeishuProvider,
192
+ async (url) => {
193
+ const rawBody = "{not-json";
194
+ const response = await fetch(url, {
195
+ method: "POST",
196
+ headers: signFeishuPayload({ encryptKey: "encrypt_key", rawBody }),
197
+ body: rawBody,
198
+ });
199
+
200
+ expect(response.status).toBe(400);
201
+ expect(await response.text()).toBe("Invalid JSON");
202
+ },
203
+ );
204
+ });
205
+
206
+ it("accepts signed plaintext url_verification challenges end-to-end", async () => {
207
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
208
+
209
+ await withRunningWebhookMonitor(
210
+ {
211
+ accountId: "signed-challenge",
212
+ path: "/hook-e2e-signed-challenge",
213
+ verificationToken: "verify_token",
214
+ encryptKey: "encrypt_key",
215
+ },
216
+ monitorFeishuProvider,
217
+ async (url) => {
218
+ const payload = { type: "url_verification", challenge: "challenge-token" };
219
+ const response = await postSignedPayload(url, payload);
220
+
221
+ expect(response.status).toBe(200);
222
+ await expect(response.json()).resolves.toEqual({ challenge: "challenge-token" });
223
+ },
224
+ );
225
+ });
226
+
227
+ it("accepts signed non-challenge events and reaches the dispatcher", async () => {
228
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
229
+
230
+ await withRunningWebhookMonitor(
231
+ {
232
+ accountId: "signed-dispatch",
233
+ path: "/hook-e2e-signed-dispatch",
234
+ verificationToken: "verify_token",
235
+ encryptKey: "encrypt_key",
236
+ },
237
+ monitorFeishuProvider,
238
+ async (url) => {
239
+ const payload = {
240
+ schema: "2.0",
241
+ header: { event_type: "unknown.event" },
242
+ event: {},
243
+ };
244
+ const response = await postSignedPayload(url, payload);
245
+
246
+ expect(response.status).toBe(200);
247
+ expect(await response.text()).toContain("no unknown.event event handle");
248
+ },
249
+ );
250
+ });
251
+
252
+ it("accepts signed encrypted url_verification challenges end-to-end", async () => {
253
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
254
+
255
+ await withRunningWebhookMonitor(
256
+ {
257
+ accountId: "encrypted-challenge",
258
+ path: "/hook-e2e-encrypted-challenge",
259
+ verificationToken: "verify_token",
260
+ encryptKey: "encrypt_key",
261
+ },
262
+ monitorFeishuProvider,
263
+ async (url) => {
264
+ const payload = {
265
+ encrypt: encryptFeishuPayload("encrypt_key", {
266
+ type: "url_verification",
267
+ challenge: "encrypted-challenge-token",
268
+ }),
269
+ };
270
+ const response = await postSignedPayload(url, payload);
271
+
272
+ expect(response.status).toBe(200);
273
+ await expect(response.json()).resolves.toEqual({
274
+ challenge: "encrypted-challenge-token",
275
+ });
276
+ },
277
+ );
278
+ });
279
+ });
@@ -0,0 +1,389 @@
1
+ import type { IncomingMessage } from "node:http";
2
+ import { createConnection } from "node:net";
3
+ import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
4
+ import {
5
+ createFeishuClientMockModule,
6
+ createFeishuRuntimeMockModule,
7
+ } from "./monitor.test-mocks.js";
8
+ import {
9
+ buildWebhookConfig,
10
+ getFreePort,
11
+ withRunningWebhookMonitor,
12
+ } from "./monitor.webhook.test-helpers.js";
13
+
14
+ const probeFeishuMock = vi.hoisted(() => vi.fn());
15
+
16
+ vi.mock("./probe.js", () => ({
17
+ probeFeishu: probeFeishuMock,
18
+ }));
19
+
20
+ vi.mock("./client.js", () => createFeishuClientMockModule());
21
+ vi.mock("./runtime.js", () => createFeishuRuntimeMockModule());
22
+
23
+ vi.mock("@larksuiteoapi/node-sdk", () => ({
24
+ adaptDefault: vi.fn(
25
+ () => (_req: unknown, res: { statusCode?: number; end: (s: string) => void }) => {
26
+ res.statusCode = 200;
27
+ res.end("ok");
28
+ },
29
+ ),
30
+ }));
31
+
32
+ vi.mock("./monitor.state.js", async (importOriginal) => {
33
+ const actual = await importOriginal<typeof import("./monitor.state.js")>();
34
+ return {
35
+ ...actual,
36
+ FEISHU_WEBHOOK_BODY_TIMEOUT_MS: 50,
37
+ };
38
+ });
39
+
40
+ import type { RuntimeEnv } from "../runtime-api.js";
41
+ import { resolveRequestClientIp } from "./monitor-transport-runtime-api.js";
42
+ import {
43
+ clearFeishuWebhookRateLimitStateForTest,
44
+ getFeishuWebhookRateLimitStateSizeForTest,
45
+ isWebhookRateLimitedForTest,
46
+ monitorFeishuProvider,
47
+ stopFeishuMonitor,
48
+ } from "./monitor.js";
49
+ import { buildFeishuWebhookRateLimitKeyForTest, monitorWebhook } from "./monitor.transport.js";
50
+ import type { ResolvedFeishuAccount } from "./types.js";
51
+
52
+ async function waitForSlowBodyTimeoutResponse(
53
+ url: string,
54
+ timeoutMs: number,
55
+ ): Promise<{ body: string; elapsedMs: number }> {
56
+ return await new Promise<{ body: string; elapsedMs: number }>((resolve, reject) => {
57
+ const target = new URL(url);
58
+ const startedAt = Date.now();
59
+ let response = "";
60
+ const socket = createConnection(
61
+ {
62
+ host: target.hostname,
63
+ port: Number(target.port),
64
+ },
65
+ () => {
66
+ socket.write(`POST ${target.pathname} HTTP/1.1\r\n`);
67
+ socket.write(`Host: ${target.hostname}\r\n`);
68
+ socket.write("Content-Type: application/json\r\n");
69
+ socket.write("Content-Length: 65536\r\n");
70
+ socket.write("\r\n");
71
+ socket.write('{"type":"url_verification"');
72
+ },
73
+ );
74
+
75
+ socket.setEncoding("utf8");
76
+ socket.on("error", () => {});
77
+ socket.on("data", (chunk) => {
78
+ response += chunk;
79
+ if (response.includes("Request body timeout")) {
80
+ clearTimeout(failTimer);
81
+ socket.destroy();
82
+ resolve({ body: response, elapsedMs: Date.now() - startedAt });
83
+ }
84
+ });
85
+
86
+ const failTimer = setTimeout(() => {
87
+ socket.destroy();
88
+ reject(new Error(`timeout response did not arrive within ${timeoutMs}ms`));
89
+ }, timeoutMs);
90
+ });
91
+ }
92
+
93
+ async function waitForOversizedBodyResponse(url: string): Promise<string> {
94
+ return await new Promise<string>((resolve, reject) => {
95
+ const target = new URL(url);
96
+ const body = JSON.stringify({ payload: "x".repeat(70 * 1024) });
97
+ let response = "";
98
+ let settled = false;
99
+ const socket = createConnection(
100
+ {
101
+ host: target.hostname,
102
+ port: Number(target.port),
103
+ },
104
+ () => {
105
+ socket.write(`POST ${target.pathname} HTTP/1.1\r\n`);
106
+ socket.write(`Host: ${target.hostname}\r\n`);
107
+ socket.write("Content-Type: application/json\r\n");
108
+ socket.write(`Content-Length: ${Buffer.byteLength(body)}\r\n`);
109
+ socket.write("\r\n");
110
+ socket.write(body);
111
+ },
112
+ );
113
+
114
+ const finish = (result: string) => {
115
+ if (settled) {
116
+ return;
117
+ }
118
+ settled = true;
119
+ clearTimeout(failTimer);
120
+ socket.destroy();
121
+ resolve(result);
122
+ };
123
+
124
+ socket.setEncoding("utf8");
125
+ socket.on("data", (chunk) => {
126
+ response += chunk;
127
+ if (response.includes("Payload too large")) {
128
+ finish(response);
129
+ }
130
+ });
131
+ socket.on("close", () => {
132
+ if (response.includes("Payload too large")) {
133
+ finish(response);
134
+ }
135
+ });
136
+ socket.on("error", (error: NodeJS.ErrnoException) => {
137
+ if (response.includes("Payload too large")) {
138
+ finish(response);
139
+ return;
140
+ }
141
+ if (error.code === "ECONNRESET") {
142
+ finish("ECONNRESET");
143
+ return;
144
+ }
145
+ reject(error);
146
+ });
147
+
148
+ const failTimer = setTimeout(() => {
149
+ socket.destroy();
150
+ reject(new Error("payload-too-large response did not arrive within 1000ms"));
151
+ }, 1_000);
152
+ });
153
+ }
154
+
155
+ function resolveTestClientIp(remoteAddress: string | undefined): string | undefined {
156
+ return resolveRequestClientIp({
157
+ headers: {},
158
+ socket: { remoteAddress },
159
+ } as IncomingMessage);
160
+ }
161
+
162
+ afterEach(() => {
163
+ clearFeishuWebhookRateLimitStateForTest();
164
+ stopFeishuMonitor();
165
+ });
166
+
167
+ afterAll(() => {
168
+ vi.doUnmock("./probe.js");
169
+ vi.doUnmock("./client.js");
170
+ vi.doUnmock("./runtime.js");
171
+ vi.doUnmock("@larksuiteoapi/node-sdk");
172
+ vi.doUnmock("./monitor.state.js");
173
+ vi.resetModules();
174
+ });
175
+
176
+ describe("Feishu webhook security hardening", () => {
177
+ it("rejects webhook mode without verificationToken", async () => {
178
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
179
+
180
+ const cfg = buildWebhookConfig({
181
+ accountId: "missing-token",
182
+ path: "/hook-missing-token",
183
+ port: await getFreePort(),
184
+ });
185
+
186
+ await expect(monitorFeishuProvider({ config: cfg })).rejects.toThrow(
187
+ /requires verificationToken/i,
188
+ );
189
+ });
190
+
191
+ it("rejects webhook mode without encryptKey", async () => {
192
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
193
+
194
+ const cfg = buildWebhookConfig({
195
+ accountId: "missing-encrypt-key",
196
+ path: "/hook-missing-encrypt",
197
+ port: await getFreePort(),
198
+ verificationToken: "verify_token",
199
+ });
200
+
201
+ await expect(monitorFeishuProvider({ config: cfg })).rejects.toThrow(/requires encryptKey/i);
202
+ });
203
+
204
+ it("refuses to start the webhook transport without encryptKey", async () => {
205
+ const account = {
206
+ accountId: "transport-missing-encrypt-key",
207
+ config: {
208
+ enabled: true,
209
+ connectionMode: "webhook",
210
+ webhookHost: "127.0.0.1",
211
+ webhookPort: await getFreePort(),
212
+ webhookPath: "/hook-transport-missing-encrypt",
213
+ },
214
+ } as ResolvedFeishuAccount;
215
+
216
+ await expect(
217
+ monitorWebhook({
218
+ account,
219
+ accountId: account.accountId,
220
+ runtime: {
221
+ log: vi.fn(),
222
+ error: vi.fn(),
223
+ exit: vi.fn(),
224
+ } as RuntimeEnv,
225
+ abortSignal: new AbortController().signal,
226
+ eventDispatcher: {} as never,
227
+ }),
228
+ ).rejects.toThrow(/requires encryptKey/i);
229
+ });
230
+
231
+ it("returns 415 for POST requests without json content type", async () => {
232
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
233
+ await withRunningWebhookMonitor(
234
+ {
235
+ accountId: "content-type",
236
+ path: "/hook-content-type",
237
+ verificationToken: "verify_token",
238
+ encryptKey: "encrypt_key",
239
+ },
240
+ monitorFeishuProvider,
241
+ async (url) => {
242
+ const response = await fetch(url, {
243
+ method: "POST",
244
+ headers: { "content-type": "text/plain" },
245
+ body: "{}",
246
+ });
247
+
248
+ expect(response.status).toBe(415);
249
+ expect(await response.text()).toBe("Unsupported Media Type");
250
+ },
251
+ );
252
+ });
253
+
254
+ it("rejects oversized unsigned webhook bodies with 413 before signature verification", async () => {
255
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
256
+ await withRunningWebhookMonitor(
257
+ {
258
+ accountId: "payload-too-large",
259
+ path: "/hook-payload-too-large",
260
+ verificationToken: "verify_token",
261
+ encryptKey: "encrypt_key",
262
+ },
263
+ monitorFeishuProvider,
264
+ async (url) => {
265
+ const response = await waitForOversizedBodyResponse(url);
266
+
267
+ if (response === "ECONNRESET") {
268
+ expect(response).toBe("ECONNRESET");
269
+ } else {
270
+ expect(response).toContain("413 Payload Too Large");
271
+ expect(response).toContain("Payload too large");
272
+ }
273
+ },
274
+ );
275
+ });
276
+
277
+ it("drops slow-body webhook requests within the tightened pre-auth timeout", async () => {
278
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
279
+ await withRunningWebhookMonitor(
280
+ {
281
+ accountId: "slow-body-timeout",
282
+ path: "/hook-slow-body-timeout",
283
+ verificationToken: "verify_token",
284
+ encryptKey: "encrypt_key",
285
+ },
286
+ monitorFeishuProvider,
287
+ async (url) => {
288
+ const result = await waitForSlowBodyTimeoutResponse(url, 1_000);
289
+ expect(result.body).toContain("408 Request Timeout");
290
+ expect(result.body).toContain("Request body timeout");
291
+ expect(result.elapsedMs).toBeLessThan(500);
292
+ },
293
+ );
294
+ });
295
+
296
+ it("rate limits webhook burst traffic with 429", async () => {
297
+ probeFeishuMock.mockResolvedValue({ ok: true, botOpenId: "bot_open_id" });
298
+ await withRunningWebhookMonitor(
299
+ {
300
+ accountId: "rate-limit",
301
+ path: "/hook-rate-limit",
302
+ verificationToken: "verify_token",
303
+ encryptKey: "encrypt_key",
304
+ },
305
+ monitorFeishuProvider,
306
+ async (url) => {
307
+ let saw429 = false;
308
+ for (let i = 0; i < 130; i += 1) {
309
+ const response = await fetch(url, {
310
+ method: "POST",
311
+ headers: { "content-type": "text/plain" },
312
+ body: "{}",
313
+ });
314
+ if (response.status === 429) {
315
+ saw429 = true;
316
+ expect(await response.text()).toBe("Too Many Requests");
317
+ break;
318
+ }
319
+ }
320
+
321
+ expect(saw429).toBe(true);
322
+ },
323
+ );
324
+ });
325
+
326
+ it("uses one webhook rate-limit key for loopback address-family variants", () => {
327
+ const base = {
328
+ accountId: "rate-limit-key",
329
+ path: "/hook-rate-limit-key",
330
+ };
331
+
332
+ expect([
333
+ buildFeishuWebhookRateLimitKeyForTest({
334
+ ...base,
335
+ clientIp: resolveTestClientIp("127.0.0.1"),
336
+ }),
337
+ buildFeishuWebhookRateLimitKeyForTest({
338
+ ...base,
339
+ clientIp: resolveTestClientIp("127.0.0.42"),
340
+ }),
341
+ buildFeishuWebhookRateLimitKeyForTest({
342
+ ...base,
343
+ clientIp: resolveTestClientIp("::ffff:127.0.0.1"),
344
+ }),
345
+ buildFeishuWebhookRateLimitKeyForTest({
346
+ ...base,
347
+ clientIp: resolveTestClientIp("::1"),
348
+ }),
349
+ ]).toEqual([
350
+ "rate-limit-key:/hook-rate-limit-key:loopback",
351
+ "rate-limit-key:/hook-rate-limit-key:loopback",
352
+ "rate-limit-key:/hook-rate-limit-key:loopback",
353
+ "rate-limit-key:/hook-rate-limit-key:loopback",
354
+ ]);
355
+ });
356
+
357
+ it("keeps non-loopback and unknown webhook rate-limit key suffixes distinct", () => {
358
+ const base = {
359
+ accountId: "rate-limit-key",
360
+ path: "/hook-rate-limit-key",
361
+ };
362
+
363
+ expect(buildFeishuWebhookRateLimitKeyForTest({ ...base, clientIp: "10.0.0.1" })).toBe(
364
+ "rate-limit-key:/hook-rate-limit-key:10.0.0.1",
365
+ );
366
+ expect(buildFeishuWebhookRateLimitKeyForTest(base)).toBe(
367
+ "rate-limit-key:/hook-rate-limit-key:unknown",
368
+ );
369
+ });
370
+
371
+ it("caps tracked webhook rate-limit keys to prevent unbounded growth", () => {
372
+ const now = 1_000_000;
373
+ for (let i = 0; i < 4_500; i += 1) {
374
+ isWebhookRateLimitedForTest(`/feishu-rate-limit:key-${i}`, now);
375
+ }
376
+ expect(getFeishuWebhookRateLimitStateSizeForTest()).toBeLessThanOrEqual(4_096);
377
+ });
378
+
379
+ it("prunes stale webhook rate-limit state after window elapses", () => {
380
+ const now = 2_000_000;
381
+ for (let i = 0; i < 100; i += 1) {
382
+ isWebhookRateLimitedForTest(`/feishu-rate-limit-stale:key-${i}`, now);
383
+ }
384
+ expect(getFeishuWebhookRateLimitStateSizeForTest()).toBe(100);
385
+
386
+ isWebhookRateLimitedForTest("/feishu-rate-limit-stale:fresh", now + 60_001);
387
+ expect(getFeishuWebhookRateLimitStateSizeForTest()).toBe(1);
388
+ });
389
+ });