@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,279 +0,0 @@
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
- });
@@ -1,389 +0,0 @@
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
- });