@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,213 +0,0 @@
1
- import { createNonExitingRuntimeEnv } from "klaw/plugin-sdk/plugin-test-runtime";
2
- import { afterAll, afterEach, describe, expect, it, vi } from "vitest";
3
- import type { ClawdbotConfig } from "../runtime-api.js";
4
- import { monitorFeishuProvider, stopFeishuMonitor } from "./monitor.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 { createFeishuClientMockModule } = await import("./monitor.test-mocks.js");
14
- return createFeishuClientMockModule();
15
- });
16
- vi.mock("./runtime.js", async () => {
17
- const { createFeishuRuntimeMockModule } = await import("./monitor.test-mocks.js");
18
- return createFeishuRuntimeMockModule();
19
- });
20
-
21
- function buildMultiAccountWebsocketConfig(accountIds: string[]): ClawdbotConfig {
22
- return {
23
- channels: {
24
- feishu: {
25
- enabled: true,
26
- accounts: Object.fromEntries(
27
- accountIds.map((accountId) => [
28
- accountId,
29
- {
30
- enabled: true,
31
- appId: `cli_${accountId}`,
32
- appSecret: `secret_${accountId}`, // pragma: allowlist secret
33
- connectionMode: "websocket",
34
- },
35
- ]),
36
- ),
37
- },
38
- },
39
- } as ClawdbotConfig;
40
- }
41
-
42
- async function waitForStartedAccount(started: string[], accountId: string) {
43
- await vi.waitFor(
44
- () => {
45
- expect(started).toContain(accountId);
46
- },
47
- { timeout: 10_000 },
48
- );
49
- }
50
-
51
- afterEach(() => {
52
- stopFeishuMonitor();
53
- });
54
-
55
- afterAll(() => {
56
- vi.doUnmock("./probe.js");
57
- vi.doUnmock("./client.js");
58
- vi.doUnmock("./runtime.js");
59
- vi.resetModules();
60
- });
61
-
62
- describe("Feishu monitor startup preflight", () => {
63
- it("starts account probes sequentially to avoid startup bursts", async () => {
64
- let inFlight = 0;
65
- let maxInFlight = 0;
66
- const started: string[] = [];
67
- let releaseProbes: (() => void) | undefined;
68
- const probesReleased = new Promise<void>((resolve) => {
69
- releaseProbes = () => resolve();
70
- });
71
- if (!releaseProbes) {
72
- throw new Error("Expected probe release callback to be initialized");
73
- }
74
- const releaseStartedProbes = releaseProbes;
75
- probeFeishuMock.mockImplementation(async (account: { accountId: string }) => {
76
- started.push(account.accountId);
77
- inFlight += 1;
78
- maxInFlight = Math.max(maxInFlight, inFlight);
79
- await probesReleased;
80
- inFlight -= 1;
81
- return { ok: true, botOpenId: `bot_${account.accountId}` };
82
- });
83
-
84
- const abortController = new AbortController();
85
- const monitorPromise = monitorFeishuProvider({
86
- config: buildMultiAccountWebsocketConfig(["alpha", "beta", "gamma"]),
87
- abortSignal: abortController.signal,
88
- });
89
-
90
- try {
91
- await waitForStartedAccount(started, "alpha");
92
- expect(started).toEqual(["alpha"]);
93
- expect(maxInFlight).toBe(1);
94
- } finally {
95
- releaseStartedProbes();
96
- abortController.abort();
97
- await monitorPromise;
98
- }
99
- });
100
-
101
- it("does not refetch bot info after a failed sequential preflight", async () => {
102
- const started: string[] = [];
103
- let releaseBetaProbe: (() => void) | undefined;
104
- const betaProbeReleased = new Promise<void>((resolve) => {
105
- releaseBetaProbe = () => resolve();
106
- });
107
- if (!releaseBetaProbe) {
108
- throw new Error("Expected beta probe release callback to be initialized");
109
- }
110
- const releaseStartedBetaProbe = releaseBetaProbe;
111
-
112
- probeFeishuMock.mockImplementation(async (account: { accountId: string }) => {
113
- started.push(account.accountId);
114
- if (account.accountId === "alpha") {
115
- return { ok: false };
116
- }
117
- await betaProbeReleased;
118
- return { ok: true, botOpenId: `bot_${account.accountId}` };
119
- });
120
-
121
- const abortController = new AbortController();
122
- const monitorPromise = monitorFeishuProvider({
123
- config: buildMultiAccountWebsocketConfig(["alpha", "beta"]),
124
- abortSignal: abortController.signal,
125
- });
126
-
127
- try {
128
- await waitForStartedAccount(started, "beta");
129
- expect(started).toEqual(["alpha", "beta"]);
130
- expect(started.reduce((count, accountId) => count + (accountId === "alpha" ? 1 : 0), 0)).toBe(
131
- 1,
132
- );
133
- } finally {
134
- releaseStartedBetaProbe();
135
- abortController.abort();
136
- await monitorPromise;
137
- }
138
- });
139
-
140
- it("continues startup when probe layer reports timeout", async () => {
141
- const started: string[] = [];
142
- let releaseBetaProbe: (() => void) | undefined;
143
- const betaProbeReleased = new Promise<void>((resolve) => {
144
- releaseBetaProbe = () => resolve();
145
- });
146
- if (!releaseBetaProbe) {
147
- throw new Error("Expected beta probe release callback to be initialized");
148
- }
149
- const releaseStartedBetaProbe = releaseBetaProbe;
150
-
151
- probeFeishuMock.mockImplementation((account: { accountId: string }) => {
152
- started.push(account.accountId);
153
- if (account.accountId === "alpha") {
154
- return Promise.resolve({ ok: false, error: "probe timed out after 10000ms" });
155
- }
156
- return betaProbeReleased.then(() => ({ ok: true, botOpenId: `bot_${account.accountId}` }));
157
- });
158
-
159
- const abortController = new AbortController();
160
- const runtime = createNonExitingRuntimeEnv();
161
- const monitorPromise = monitorFeishuProvider({
162
- config: buildMultiAccountWebsocketConfig(["alpha", "beta"]),
163
- runtime,
164
- abortSignal: abortController.signal,
165
- });
166
-
167
- try {
168
- await waitForStartedAccount(started, "beta");
169
- expect(started).toEqual(["alpha", "beta"]);
170
- expect(runtime.error).toHaveBeenCalledWith(
171
- "feishu[alpha]: bot info probe timed out after 30000ms; continuing startup",
172
- );
173
- } finally {
174
- releaseStartedBetaProbe();
175
- abortController.abort();
176
- await monitorPromise;
177
- }
178
- });
179
-
180
- it("stops sequential preflight when aborted during probe", async () => {
181
- const started: string[] = [];
182
- probeFeishuMock.mockImplementation(
183
- (account: { accountId: string }, options: { abortSignal?: AbortSignal }) => {
184
- started.push(account.accountId);
185
- return new Promise((resolve) => {
186
- options.abortSignal?.addEventListener(
187
- "abort",
188
- () => resolve({ ok: false, error: "probe aborted" }),
189
- { once: true },
190
- );
191
- });
192
- },
193
- );
194
-
195
- const abortController = new AbortController();
196
- const monitorPromise = monitorFeishuProvider({
197
- config: buildMultiAccountWebsocketConfig(["alpha", "beta"]),
198
- abortSignal: abortController.signal,
199
- });
200
-
201
- try {
202
- await waitForStartedAccount(started, "alpha");
203
- expect(started).toEqual(["alpha"]);
204
-
205
- abortController.abort();
206
- await monitorPromise;
207
-
208
- expect(started).toEqual(["alpha"]);
209
- } finally {
210
- abortController.abort();
211
- }
212
- });
213
- });
@@ -1,74 +0,0 @@
1
- import { normalizeLowercaseStringOrEmpty } from "klaw/plugin-sdk/string-coerce-runtime";
2
- import type { RuntimeEnv } from "../runtime-api.js";
3
- import { probeFeishu } from "./probe.js";
4
- import type { ResolvedFeishuAccount } from "./types.js";
5
-
6
- const FEISHU_STARTUP_BOT_INFO_TIMEOUT_DEFAULT_MS = 30_000;
7
- const FEISHU_STARTUP_BOT_INFO_TIMEOUT_ENV = "KLAW_FEISHU_STARTUP_PROBE_TIMEOUT_MS";
8
-
9
- function resolveStartupProbeTimeoutMs(): number {
10
- const raw = process.env[FEISHU_STARTUP_BOT_INFO_TIMEOUT_ENV];
11
- if (raw) {
12
- const parsed = Number(raw);
13
- if (Number.isFinite(parsed) && parsed > 0) {
14
- return Math.floor(parsed);
15
- }
16
- console.warn(
17
- `[feishu] ${FEISHU_STARTUP_BOT_INFO_TIMEOUT_ENV}="${raw}" is invalid; using default ${FEISHU_STARTUP_BOT_INFO_TIMEOUT_DEFAULT_MS}ms`,
18
- );
19
- }
20
- return FEISHU_STARTUP_BOT_INFO_TIMEOUT_DEFAULT_MS;
21
- }
22
-
23
- const FEISHU_STARTUP_BOT_INFO_TIMEOUT_MS = resolveStartupProbeTimeoutMs();
24
-
25
- type FetchBotOpenIdOptions = {
26
- runtime?: RuntimeEnv;
27
- abortSignal?: AbortSignal;
28
- timeoutMs?: number;
29
- };
30
-
31
- export type FeishuMonitorBotIdentity = {
32
- botOpenId?: string;
33
- botName?: string;
34
- };
35
-
36
- function isTimeoutErrorMessage(message: string | undefined): boolean {
37
- const lower = normalizeLowercaseStringOrEmpty(message);
38
- return lower.includes("timeout") || lower.includes("timed out");
39
- }
40
-
41
- function isAbortErrorMessage(message: string | undefined): boolean {
42
- return normalizeLowercaseStringOrEmpty(message).includes("aborted");
43
- }
44
-
45
- export async function fetchBotIdentityForMonitor(
46
- account: ResolvedFeishuAccount,
47
- options: FetchBotOpenIdOptions = {},
48
- ): Promise<FeishuMonitorBotIdentity> {
49
- if (options.abortSignal?.aborted) {
50
- return {};
51
- }
52
-
53
- const timeoutMs = options.timeoutMs ?? FEISHU_STARTUP_BOT_INFO_TIMEOUT_MS;
54
- const result = await probeFeishu(account, {
55
- timeoutMs,
56
- abortSignal: options.abortSignal,
57
- });
58
- if (result.ok) {
59
- return { botOpenId: result.botOpenId, botName: result.botName };
60
- }
61
-
62
- const probeError = result.error ?? undefined;
63
- if (options.abortSignal?.aborted || isAbortErrorMessage(probeError)) {
64
- return {};
65
- }
66
-
67
- if (isTimeoutErrorMessage(probeError)) {
68
- const error = options.runtime?.error ?? console.error;
69
- error(
70
- `feishu[${account.accountId}]: bot info probe timed out after ${timeoutMs}ms; continuing startup`,
71
- );
72
- }
73
- return {};
74
- }
@@ -1,46 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- resolveFeishuWebhookAnomalyDefaultsForTest,
4
- resolveFeishuWebhookRateLimitDefaultsForTest,
5
- } from "./monitor.state.js";
6
-
7
- describe("feishu monitor state defaults", () => {
8
- it("falls back to hard defaults when sdk defaults are missing", () => {
9
- expect(resolveFeishuWebhookRateLimitDefaultsForTest(undefined)).toEqual({
10
- windowMs: 60_000,
11
- maxRequests: 120,
12
- maxTrackedKeys: 4_096,
13
- });
14
- expect(resolveFeishuWebhookAnomalyDefaultsForTest(undefined)).toEqual({
15
- maxTrackedKeys: 4_096,
16
- ttlMs: 21_600_000,
17
- logEvery: 25,
18
- });
19
- });
20
-
21
- it("keeps valid sdk values and repairs invalid fields", () => {
22
- expect(
23
- resolveFeishuWebhookRateLimitDefaultsForTest({
24
- windowMs: 45_000,
25
- maxRequests: 0,
26
- maxTrackedKeys: -1,
27
- }),
28
- ).toEqual({
29
- windowMs: 45_000,
30
- maxRequests: 120,
31
- maxTrackedKeys: 4_096,
32
- });
33
-
34
- expect(
35
- resolveFeishuWebhookAnomalyDefaultsForTest({
36
- maxTrackedKeys: 2048,
37
- ttlMs: Number.NaN,
38
- logEvery: 10,
39
- }),
40
- ).toEqual({
41
- maxTrackedKeys: 2048,
42
- ttlMs: 21_600_000,
43
- logEvery: 10,
44
- });
45
- });
46
- });
@@ -1,170 +0,0 @@
1
- import * as http from "node:http";
2
- import type * as Lark from "@larksuiteoapi/node-sdk";
3
- import {
4
- createFixedWindowRateLimiter,
5
- createWebhookAnomalyTracker,
6
- type RuntimeEnv,
7
- WEBHOOK_ANOMALY_COUNTER_DEFAULTS as WEBHOOK_ANOMALY_COUNTER_DEFAULTS_FROM_SDK,
8
- WEBHOOK_RATE_LIMIT_DEFAULTS as WEBHOOK_RATE_LIMIT_DEFAULTS_FROM_SDK,
9
- } from "./monitor-state-runtime-api.js";
10
-
11
- export const wsClients = new Map<string, Lark.WSClient>();
12
- export const httpServers = new Map<string, http.Server>();
13
- export const botOpenIds = new Map<string, string>();
14
- export const botNames = new Map<string, string>();
15
-
16
- export const FEISHU_WEBHOOK_MAX_BODY_BYTES = 64 * 1024;
17
- export const FEISHU_WEBHOOK_BODY_TIMEOUT_MS = 5_000;
18
-
19
- type WebhookRateLimitDefaults = {
20
- windowMs: number;
21
- maxRequests: number;
22
- maxTrackedKeys: number;
23
- };
24
-
25
- type WebhookAnomalyDefaults = {
26
- maxTrackedKeys: number;
27
- ttlMs: number;
28
- logEvery: number;
29
- };
30
-
31
- const FEISHU_WEBHOOK_RATE_LIMIT_FALLBACK_DEFAULTS: WebhookRateLimitDefaults = {
32
- windowMs: 60_000,
33
- maxRequests: 120,
34
- maxTrackedKeys: 4_096,
35
- };
36
-
37
- const FEISHU_WEBHOOK_ANOMALY_FALLBACK_DEFAULTS: WebhookAnomalyDefaults = {
38
- maxTrackedKeys: 4_096,
39
- ttlMs: 6 * 60 * 60_000,
40
- logEvery: 25,
41
- };
42
-
43
- function coercePositiveInt(value: unknown, fallback: number): number {
44
- if (typeof value !== "number" || !Number.isFinite(value)) {
45
- return fallback;
46
- }
47
- const normalized = Math.floor(value);
48
- return normalized > 0 ? normalized : fallback;
49
- }
50
-
51
- export function resolveFeishuWebhookRateLimitDefaultsForTest(
52
- defaults: unknown,
53
- ): WebhookRateLimitDefaults {
54
- const resolved = defaults as Partial<WebhookRateLimitDefaults> | null | undefined;
55
- return {
56
- windowMs: coercePositiveInt(
57
- resolved?.windowMs,
58
- FEISHU_WEBHOOK_RATE_LIMIT_FALLBACK_DEFAULTS.windowMs,
59
- ),
60
- maxRequests: coercePositiveInt(
61
- resolved?.maxRequests,
62
- FEISHU_WEBHOOK_RATE_LIMIT_FALLBACK_DEFAULTS.maxRequests,
63
- ),
64
- maxTrackedKeys: coercePositiveInt(
65
- resolved?.maxTrackedKeys,
66
- FEISHU_WEBHOOK_RATE_LIMIT_FALLBACK_DEFAULTS.maxTrackedKeys,
67
- ),
68
- };
69
- }
70
-
71
- export function resolveFeishuWebhookAnomalyDefaultsForTest(
72
- defaults: unknown,
73
- ): WebhookAnomalyDefaults {
74
- const resolved = defaults as Partial<WebhookAnomalyDefaults> | null | undefined;
75
- return {
76
- maxTrackedKeys: coercePositiveInt(
77
- resolved?.maxTrackedKeys,
78
- FEISHU_WEBHOOK_ANOMALY_FALLBACK_DEFAULTS.maxTrackedKeys,
79
- ),
80
- ttlMs: coercePositiveInt(resolved?.ttlMs, FEISHU_WEBHOOK_ANOMALY_FALLBACK_DEFAULTS.ttlMs),
81
- logEvery: coercePositiveInt(
82
- resolved?.logEvery,
83
- FEISHU_WEBHOOK_ANOMALY_FALLBACK_DEFAULTS.logEvery,
84
- ),
85
- };
86
- }
87
-
88
- const feishuWebhookRateLimitDefaults = resolveFeishuWebhookRateLimitDefaultsForTest(
89
- WEBHOOK_RATE_LIMIT_DEFAULTS_FROM_SDK,
90
- );
91
- const feishuWebhookAnomalyDefaults = resolveFeishuWebhookAnomalyDefaultsForTest(
92
- WEBHOOK_ANOMALY_COUNTER_DEFAULTS_FROM_SDK,
93
- );
94
-
95
- export const feishuWebhookRateLimiter = createFixedWindowRateLimiter({
96
- windowMs: feishuWebhookRateLimitDefaults.windowMs,
97
- maxRequests: feishuWebhookRateLimitDefaults.maxRequests,
98
- maxTrackedKeys: feishuWebhookRateLimitDefaults.maxTrackedKeys,
99
- });
100
-
101
- const feishuWebhookAnomalyTracker = createWebhookAnomalyTracker({
102
- maxTrackedKeys: feishuWebhookAnomalyDefaults.maxTrackedKeys,
103
- ttlMs: feishuWebhookAnomalyDefaults.ttlMs,
104
- logEvery: feishuWebhookAnomalyDefaults.logEvery,
105
- });
106
-
107
- function closeWsClient(client: Lark.WSClient | undefined): void {
108
- if (!client) {
109
- return;
110
- }
111
- try {
112
- client.close();
113
- } catch {
114
- /* Best-effort cleanup */
115
- }
116
- }
117
-
118
- export function clearFeishuWebhookRateLimitStateForTest(): void {
119
- feishuWebhookRateLimiter.clear();
120
- feishuWebhookAnomalyTracker.clear();
121
- }
122
-
123
- export function getFeishuWebhookRateLimitStateSizeForTest(): number {
124
- return feishuWebhookRateLimiter.size();
125
- }
126
-
127
- export function isWebhookRateLimitedForTest(key: string, nowMs: number): boolean {
128
- return feishuWebhookRateLimiter.isRateLimited(key, nowMs);
129
- }
130
-
131
- export function recordWebhookStatus(
132
- runtime: RuntimeEnv | undefined,
133
- accountId: string,
134
- path: string,
135
- statusCode: number,
136
- ): void {
137
- feishuWebhookAnomalyTracker.record({
138
- key: `${accountId}:${path}:${statusCode}`,
139
- statusCode,
140
- log: runtime?.log ?? console.log,
141
- message: (count) =>
142
- `feishu[${accountId}]: webhook anomaly path=${path} status=${statusCode} count=${count}`,
143
- });
144
- }
145
-
146
- export function stopFeishuMonitorState(accountId?: string): void {
147
- if (accountId) {
148
- closeWsClient(wsClients.get(accountId));
149
- wsClients.delete(accountId);
150
- const server = httpServers.get(accountId);
151
- if (server) {
152
- server.close();
153
- httpServers.delete(accountId);
154
- }
155
- botOpenIds.delete(accountId);
156
- botNames.delete(accountId);
157
- return;
158
- }
159
-
160
- for (const client of wsClients.values()) {
161
- closeWsClient(client);
162
- }
163
- wsClients.clear();
164
- for (const server of httpServers.values()) {
165
- server.close();
166
- }
167
- httpServers.clear();
168
- botOpenIds.clear();
169
- botNames.clear();
170
- }
@@ -1,18 +0,0 @@
1
- export class FeishuRetryableSyntheticEventError extends Error {
2
- constructor(message: string, options?: ErrorOptions) {
3
- super(message, options);
4
- this.name = "FeishuRetryableSyntheticEventError";
5
- }
6
- }
7
-
8
- export function isFeishuRetryableSyntheticEventError(
9
- error: unknown,
10
- ): error is FeishuRetryableSyntheticEventError {
11
- return (
12
- error instanceof FeishuRetryableSyntheticEventError ||
13
- (typeof error === "object" &&
14
- error !== null &&
15
- "name" in error &&
16
- error.name === "FeishuRetryableSyntheticEventError")
17
- );
18
- }
@@ -1,46 +0,0 @@
1
- import { vi } from "vitest";
2
-
3
- export function createFeishuClientMockModule(): {
4
- createFeishuWSClient: () => { start: () => void; close: () => void };
5
- createEventDispatcher: () => { register: () => void };
6
- } {
7
- return {
8
- createFeishuWSClient: vi.fn(() => ({ start: vi.fn(), close: vi.fn() })),
9
- createEventDispatcher: vi.fn(() => ({ register: vi.fn() })),
10
- };
11
- }
12
-
13
- export function createFeishuRuntimeMockModule(): {
14
- getFeishuRuntime: () => {
15
- channel: {
16
- debounce: {
17
- resolveInboundDebounceMs: () => number;
18
- createInboundDebouncer: () => {
19
- enqueue: () => Promise<void>;
20
- flushKey: () => Promise<void>;
21
- };
22
- };
23
- text: {
24
- hasControlCommand: () => boolean;
25
- };
26
- };
27
- };
28
- } {
29
- return {
30
- getFeishuRuntime: () => ({
31
- channel: {
32
- debounce: {
33
- resolveInboundDebounceMs: () => 0,
34
- createInboundDebouncer: () => ({
35
- enqueue: async () => {},
36
- flushKey: async () => {},
37
- cancelKey: () => false,
38
- }),
39
- },
40
- text: {
41
- hasControlCommand: () => false,
42
- },
43
- },
44
- }),
45
- };
46
- }