@openclaw/feishu 2026.2.24 → 2026.3.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 (64) hide show
  1. package/index.ts +2 -0
  2. package/package.json +2 -1
  3. package/skills/feishu-doc/SKILL.md +109 -3
  4. package/src/accounts.test.ts +90 -0
  5. package/src/accounts.ts +11 -2
  6. package/src/async.ts +62 -0
  7. package/src/bitable.ts +189 -215
  8. package/src/bot.card-action.test.ts +63 -0
  9. package/src/bot.checkBotMentioned.test.ts +55 -0
  10. package/src/bot.test.ts +863 -9
  11. package/src/bot.ts +414 -200
  12. package/src/card-action.ts +79 -0
  13. package/src/channel.ts +6 -0
  14. package/src/chat-schema.ts +24 -0
  15. package/src/chat.test.ts +89 -0
  16. package/src/chat.ts +130 -0
  17. package/src/client.test.ts +107 -0
  18. package/src/client.ts +13 -0
  19. package/src/config-schema.test.ts +82 -1
  20. package/src/config-schema.ts +54 -3
  21. package/src/doc-schema.ts +141 -0
  22. package/src/docx-batch-insert.ts +190 -0
  23. package/src/docx-color-text.ts +149 -0
  24. package/src/docx-table-ops.ts +298 -0
  25. package/src/docx.account-selection.test.ts +76 -0
  26. package/src/docx.test.ts +470 -0
  27. package/src/docx.ts +996 -72
  28. package/src/drive.ts +38 -33
  29. package/src/media.test.ts +123 -6
  30. package/src/media.ts +31 -10
  31. package/src/monitor.account.ts +286 -0
  32. package/src/monitor.reaction.test.ts +235 -0
  33. package/src/monitor.startup.test.ts +187 -0
  34. package/src/monitor.startup.ts +51 -0
  35. package/src/monitor.state.ts +76 -0
  36. package/src/monitor.transport.ts +163 -0
  37. package/src/monitor.ts +44 -346
  38. package/src/monitor.webhook-security.test.ts +27 -1
  39. package/src/outbound.test.ts +181 -0
  40. package/src/outbound.ts +94 -7
  41. package/src/perm.ts +37 -30
  42. package/src/policy.test.ts +56 -1
  43. package/src/policy.ts +5 -1
  44. package/src/post.test.ts +105 -0
  45. package/src/post.ts +274 -0
  46. package/src/probe.test.ts +253 -0
  47. package/src/probe.ts +99 -7
  48. package/src/reply-dispatcher.test.ts +259 -0
  49. package/src/reply-dispatcher.ts +139 -45
  50. package/src/send.reply-fallback.test.ts +105 -0
  51. package/src/send.test.ts +168 -0
  52. package/src/send.ts +143 -18
  53. package/src/streaming-card.ts +131 -43
  54. package/src/targets.test.ts +26 -1
  55. package/src/targets.ts +11 -6
  56. package/src/tool-account-routing.test.ts +129 -0
  57. package/src/tool-account.ts +70 -0
  58. package/src/tool-factory-test-harness.ts +76 -0
  59. package/src/tools-config.test.ts +21 -0
  60. package/src/tools-config.ts +2 -1
  61. package/src/types.ts +1 -0
  62. package/src/typing.test.ts +144 -0
  63. package/src/typing.ts +140 -10
  64. package/src/wiki.ts +55 -50
@@ -0,0 +1,235 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import { describe, expect, it, vi } from "vitest";
3
+ import { resolveReactionSyntheticEvent, type FeishuReactionCreatedEvent } from "./monitor.js";
4
+
5
+ const cfg = {} as ClawdbotConfig;
6
+
7
+ function makeReactionEvent(
8
+ overrides: Partial<FeishuReactionCreatedEvent> = {},
9
+ ): FeishuReactionCreatedEvent {
10
+ return {
11
+ message_id: "om_msg1",
12
+ reaction_type: { emoji_type: "THUMBSUP" },
13
+ operator_type: "user",
14
+ user_id: { open_id: "ou_user1" },
15
+ ...overrides,
16
+ };
17
+ }
18
+
19
+ describe("resolveReactionSyntheticEvent", () => {
20
+ it("filters app self-reactions", async () => {
21
+ const event = makeReactionEvent({ operator_type: "app" });
22
+ const result = await resolveReactionSyntheticEvent({
23
+ cfg,
24
+ accountId: "default",
25
+ event,
26
+ botOpenId: "ou_bot",
27
+ });
28
+ expect(result).toBeNull();
29
+ });
30
+
31
+ it("filters Typing reactions", async () => {
32
+ const event = makeReactionEvent({ reaction_type: { emoji_type: "Typing" } });
33
+ const result = await resolveReactionSyntheticEvent({
34
+ cfg,
35
+ accountId: "default",
36
+ event,
37
+ botOpenId: "ou_bot",
38
+ });
39
+ expect(result).toBeNull();
40
+ });
41
+
42
+ it("fails closed when bot open_id is unavailable", async () => {
43
+ const event = makeReactionEvent();
44
+ const result = await resolveReactionSyntheticEvent({
45
+ cfg,
46
+ accountId: "default",
47
+ event,
48
+ });
49
+ expect(result).toBeNull();
50
+ });
51
+
52
+ it("drops reactions when reactionNotifications is off", async () => {
53
+ const event = makeReactionEvent();
54
+ const result = await resolveReactionSyntheticEvent({
55
+ cfg: {
56
+ channels: {
57
+ feishu: {
58
+ reactionNotifications: "off",
59
+ },
60
+ },
61
+ } as ClawdbotConfig,
62
+ accountId: "default",
63
+ event,
64
+ botOpenId: "ou_bot",
65
+ fetchMessage: async () => ({
66
+ messageId: "om_msg1",
67
+ chatId: "oc_group",
68
+ senderOpenId: "ou_bot",
69
+ senderType: "app",
70
+ content: "hello",
71
+ contentType: "text",
72
+ }),
73
+ });
74
+ expect(result).toBeNull();
75
+ });
76
+
77
+ it("filters reactions on non-bot messages", async () => {
78
+ const event = makeReactionEvent();
79
+ const result = await resolveReactionSyntheticEvent({
80
+ cfg,
81
+ accountId: "default",
82
+ event,
83
+ botOpenId: "ou_bot",
84
+ fetchMessage: async () => ({
85
+ messageId: "om_msg1",
86
+ chatId: "oc_group",
87
+ senderOpenId: "ou_other",
88
+ senderType: "user",
89
+ content: "hello",
90
+ contentType: "text",
91
+ }),
92
+ });
93
+ expect(result).toBeNull();
94
+ });
95
+
96
+ it("allows non-bot reactions when reactionNotifications is all", async () => {
97
+ const event = makeReactionEvent();
98
+ const result = await resolveReactionSyntheticEvent({
99
+ cfg: {
100
+ channels: {
101
+ feishu: {
102
+ reactionNotifications: "all",
103
+ },
104
+ },
105
+ } as ClawdbotConfig,
106
+ accountId: "default",
107
+ event,
108
+ botOpenId: "ou_bot",
109
+ fetchMessage: async () => ({
110
+ messageId: "om_msg1",
111
+ chatId: "oc_group",
112
+ senderOpenId: "ou_other",
113
+ senderType: "user",
114
+ content: "hello",
115
+ contentType: "text",
116
+ }),
117
+ uuid: () => "fixed-uuid",
118
+ });
119
+ expect(result?.message.message_id).toBe("om_msg1:reaction:THUMBSUP:fixed-uuid");
120
+ });
121
+
122
+ it("drops unverified reactions when sender verification times out", async () => {
123
+ const event = makeReactionEvent();
124
+ const result = await resolveReactionSyntheticEvent({
125
+ cfg,
126
+ accountId: "default",
127
+ event,
128
+ botOpenId: "ou_bot",
129
+ verificationTimeoutMs: 1,
130
+ fetchMessage: async () =>
131
+ await new Promise<never>(() => {
132
+ // Never resolves
133
+ }),
134
+ });
135
+ expect(result).toBeNull();
136
+ });
137
+
138
+ it("uses event chat context when provided", async () => {
139
+ const event = makeReactionEvent({
140
+ chat_id: "oc_group_from_event",
141
+ chat_type: "group",
142
+ });
143
+ const result = await resolveReactionSyntheticEvent({
144
+ cfg,
145
+ accountId: "default",
146
+ event,
147
+ botOpenId: "ou_bot",
148
+ fetchMessage: async () => ({
149
+ messageId: "om_msg1",
150
+ chatId: "oc_group_from_lookup",
151
+ senderOpenId: "ou_bot",
152
+ content: "hello",
153
+ contentType: "text",
154
+ }),
155
+ uuid: () => "fixed-uuid",
156
+ });
157
+
158
+ expect(result).toEqual({
159
+ sender: {
160
+ sender_id: { open_id: "ou_user1" },
161
+ sender_type: "user",
162
+ },
163
+ message: {
164
+ message_id: "om_msg1:reaction:THUMBSUP:fixed-uuid",
165
+ chat_id: "oc_group_from_event",
166
+ chat_type: "group",
167
+ message_type: "text",
168
+ content: JSON.stringify({
169
+ text: "[reacted with THUMBSUP to message om_msg1]",
170
+ }),
171
+ },
172
+ });
173
+ });
174
+
175
+ it("falls back to reacted message chat_id when event chat_id is absent", async () => {
176
+ const event = makeReactionEvent();
177
+ const result = await resolveReactionSyntheticEvent({
178
+ cfg,
179
+ accountId: "default",
180
+ event,
181
+ botOpenId: "ou_bot",
182
+ fetchMessage: async () => ({
183
+ messageId: "om_msg1",
184
+ chatId: "oc_group_from_lookup",
185
+ senderOpenId: "ou_bot",
186
+ content: "hello",
187
+ contentType: "text",
188
+ }),
189
+ uuid: () => "fixed-uuid",
190
+ });
191
+
192
+ expect(result?.message.chat_id).toBe("oc_group_from_lookup");
193
+ expect(result?.message.chat_type).toBe("p2p");
194
+ });
195
+
196
+ it("falls back to sender p2p chat when lookup returns empty chat_id", async () => {
197
+ const event = makeReactionEvent();
198
+ const result = await resolveReactionSyntheticEvent({
199
+ cfg,
200
+ accountId: "default",
201
+ event,
202
+ botOpenId: "ou_bot",
203
+ fetchMessage: async () => ({
204
+ messageId: "om_msg1",
205
+ chatId: "",
206
+ senderOpenId: "ou_bot",
207
+ content: "hello",
208
+ contentType: "text",
209
+ }),
210
+ uuid: () => "fixed-uuid",
211
+ });
212
+
213
+ expect(result?.message.chat_id).toBe("p2p:ou_user1");
214
+ expect(result?.message.chat_type).toBe("p2p");
215
+ });
216
+
217
+ it("logs and drops reactions when lookup throws", async () => {
218
+ const log = vi.fn();
219
+ const event = makeReactionEvent();
220
+ const result = await resolveReactionSyntheticEvent({
221
+ cfg,
222
+ accountId: "acct1",
223
+ event,
224
+ botOpenId: "ou_bot",
225
+ fetchMessage: async () => {
226
+ throw new Error("boom");
227
+ },
228
+ logger: log,
229
+ });
230
+ expect(result).toBeNull();
231
+ expect(log).toHaveBeenCalledWith(
232
+ expect.stringContaining("ignoring reaction on non-bot/unverified message om_msg1"),
233
+ );
234
+ });
235
+ });
@@ -0,0 +1,187 @@
1
+ import type { ClawdbotConfig } from "openclaw/plugin-sdk";
2
+ import { afterEach, describe, expect, it, vi } from "vitest";
3
+
4
+ const probeFeishuMock = vi.hoisted(() => vi.fn());
5
+
6
+ vi.mock("./probe.js", () => ({
7
+ probeFeishu: probeFeishuMock,
8
+ }));
9
+
10
+ vi.mock("./client.js", () => ({
11
+ createFeishuWSClient: vi.fn(() => ({ start: vi.fn() })),
12
+ createEventDispatcher: vi.fn(() => ({ register: vi.fn() })),
13
+ }));
14
+
15
+ import { monitorFeishuProvider, stopFeishuMonitor } from "./monitor.js";
16
+
17
+ function buildMultiAccountWebsocketConfig(accountIds: string[]): ClawdbotConfig {
18
+ return {
19
+ channels: {
20
+ feishu: {
21
+ enabled: true,
22
+ accounts: Object.fromEntries(
23
+ accountIds.map((accountId) => [
24
+ accountId,
25
+ {
26
+ enabled: true,
27
+ appId: `cli_${accountId}`,
28
+ appSecret: `secret_${accountId}`,
29
+ connectionMode: "websocket",
30
+ },
31
+ ]),
32
+ ),
33
+ },
34
+ },
35
+ } as ClawdbotConfig;
36
+ }
37
+
38
+ afterEach(() => {
39
+ stopFeishuMonitor();
40
+ });
41
+
42
+ describe("Feishu monitor startup preflight", () => {
43
+ it("starts account probes sequentially to avoid startup bursts", async () => {
44
+ let inFlight = 0;
45
+ let maxInFlight = 0;
46
+ const started: string[] = [];
47
+ let releaseProbes!: () => void;
48
+ const probesReleased = new Promise<void>((resolve) => {
49
+ releaseProbes = () => resolve();
50
+ });
51
+ probeFeishuMock.mockImplementation(async (account: { accountId: string }) => {
52
+ started.push(account.accountId);
53
+ inFlight += 1;
54
+ maxInFlight = Math.max(maxInFlight, inFlight);
55
+ await probesReleased;
56
+ inFlight -= 1;
57
+ return { ok: true, botOpenId: `bot_${account.accountId}` };
58
+ });
59
+
60
+ const abortController = new AbortController();
61
+ const monitorPromise = monitorFeishuProvider({
62
+ config: buildMultiAccountWebsocketConfig(["alpha", "beta", "gamma"]),
63
+ abortSignal: abortController.signal,
64
+ });
65
+
66
+ try {
67
+ await Promise.resolve();
68
+ await Promise.resolve();
69
+
70
+ expect(started).toEqual(["alpha"]);
71
+ expect(maxInFlight).toBe(1);
72
+ } finally {
73
+ releaseProbes();
74
+ abortController.abort();
75
+ await monitorPromise;
76
+ }
77
+ });
78
+
79
+ it("does not refetch bot info after a failed sequential preflight", async () => {
80
+ const started: string[] = [];
81
+ let releaseBetaProbe!: () => void;
82
+ const betaProbeReleased = new Promise<void>((resolve) => {
83
+ releaseBetaProbe = () => resolve();
84
+ });
85
+
86
+ probeFeishuMock.mockImplementation(async (account: { accountId: string }) => {
87
+ started.push(account.accountId);
88
+ if (account.accountId === "alpha") {
89
+ return { ok: false };
90
+ }
91
+ await betaProbeReleased;
92
+ return { ok: true, botOpenId: `bot_${account.accountId}` };
93
+ });
94
+
95
+ const abortController = new AbortController();
96
+ const monitorPromise = monitorFeishuProvider({
97
+ config: buildMultiAccountWebsocketConfig(["alpha", "beta"]),
98
+ abortSignal: abortController.signal,
99
+ });
100
+
101
+ try {
102
+ for (let i = 0; i < 10 && !started.includes("beta"); i += 1) {
103
+ await Promise.resolve();
104
+ }
105
+
106
+ expect(started).toEqual(["alpha", "beta"]);
107
+ expect(started.filter((accountId) => accountId === "alpha")).toHaveLength(1);
108
+ } finally {
109
+ releaseBetaProbe();
110
+ abortController.abort();
111
+ await monitorPromise;
112
+ }
113
+ });
114
+
115
+ it("continues startup when probe layer reports timeout", async () => {
116
+ const started: string[] = [];
117
+ let releaseBetaProbe!: () => void;
118
+ const betaProbeReleased = new Promise<void>((resolve) => {
119
+ releaseBetaProbe = () => resolve();
120
+ });
121
+
122
+ probeFeishuMock.mockImplementation((account: { accountId: string }) => {
123
+ started.push(account.accountId);
124
+ if (account.accountId === "alpha") {
125
+ return Promise.resolve({ ok: false, error: "probe timed out after 10000ms" });
126
+ }
127
+ return betaProbeReleased.then(() => ({ ok: true, botOpenId: `bot_${account.accountId}` }));
128
+ });
129
+
130
+ const abortController = new AbortController();
131
+ const runtime = { log: vi.fn(), error: vi.fn(), exit: vi.fn() };
132
+ const monitorPromise = monitorFeishuProvider({
133
+ config: buildMultiAccountWebsocketConfig(["alpha", "beta"]),
134
+ runtime,
135
+ abortSignal: abortController.signal,
136
+ });
137
+
138
+ try {
139
+ for (let i = 0; i < 10 && !started.includes("beta"); i += 1) {
140
+ await Promise.resolve();
141
+ }
142
+
143
+ expect(started).toEqual(["alpha", "beta"]);
144
+ expect(runtime.error).toHaveBeenCalledWith(
145
+ expect.stringContaining("bot info probe timed out"),
146
+ );
147
+ } finally {
148
+ releaseBetaProbe();
149
+ abortController.abort();
150
+ await monitorPromise;
151
+ }
152
+ });
153
+
154
+ it("stops sequential preflight when aborted during probe", async () => {
155
+ const started: string[] = [];
156
+ probeFeishuMock.mockImplementation(
157
+ (account: { accountId: string }, options: { abortSignal?: AbortSignal }) => {
158
+ started.push(account.accountId);
159
+ return new Promise((resolve) => {
160
+ options.abortSignal?.addEventListener(
161
+ "abort",
162
+ () => resolve({ ok: false, error: "probe aborted" }),
163
+ { once: true },
164
+ );
165
+ });
166
+ },
167
+ );
168
+
169
+ const abortController = new AbortController();
170
+ const monitorPromise = monitorFeishuProvider({
171
+ config: buildMultiAccountWebsocketConfig(["alpha", "beta"]),
172
+ abortSignal: abortController.signal,
173
+ });
174
+
175
+ try {
176
+ await Promise.resolve();
177
+ expect(started).toEqual(["alpha"]);
178
+
179
+ abortController.abort();
180
+ await monitorPromise;
181
+
182
+ expect(started).toEqual(["alpha"]);
183
+ } finally {
184
+ abortController.abort();
185
+ }
186
+ });
187
+ });
@@ -0,0 +1,51 @@
1
+ import type { RuntimeEnv } from "openclaw/plugin-sdk";
2
+ import { probeFeishu } from "./probe.js";
3
+ import type { ResolvedFeishuAccount } from "./types.js";
4
+
5
+ export const FEISHU_STARTUP_BOT_INFO_TIMEOUT_MS = 10_000;
6
+
7
+ type FetchBotOpenIdOptions = {
8
+ runtime?: RuntimeEnv;
9
+ abortSignal?: AbortSignal;
10
+ timeoutMs?: number;
11
+ };
12
+
13
+ function isTimeoutErrorMessage(message: string | undefined): boolean {
14
+ return message?.toLowerCase().includes("timeout") || message?.toLowerCase().includes("timed out")
15
+ ? true
16
+ : false;
17
+ }
18
+
19
+ function isAbortErrorMessage(message: string | undefined): boolean {
20
+ return message?.toLowerCase().includes("aborted") ?? false;
21
+ }
22
+
23
+ export async function fetchBotOpenIdForMonitor(
24
+ account: ResolvedFeishuAccount,
25
+ options: FetchBotOpenIdOptions = {},
26
+ ): Promise<string | undefined> {
27
+ if (options.abortSignal?.aborted) {
28
+ return undefined;
29
+ }
30
+
31
+ const timeoutMs = options.timeoutMs ?? FEISHU_STARTUP_BOT_INFO_TIMEOUT_MS;
32
+ const result = await probeFeishu(account, {
33
+ timeoutMs,
34
+ abortSignal: options.abortSignal,
35
+ });
36
+ if (result.ok) {
37
+ return result.botOpenId;
38
+ }
39
+
40
+ if (options.abortSignal?.aborted || isAbortErrorMessage(result.error)) {
41
+ return undefined;
42
+ }
43
+
44
+ if (isTimeoutErrorMessage(result.error)) {
45
+ const error = options.runtime?.error ?? console.error;
46
+ error(
47
+ `feishu[${account.accountId}]: bot info probe timed out after ${timeoutMs}ms; continuing startup`,
48
+ );
49
+ }
50
+ return undefined;
51
+ }
@@ -0,0 +1,76 @@
1
+ import * as http from "http";
2
+ import * as Lark from "@larksuiteoapi/node-sdk";
3
+ import {
4
+ createFixedWindowRateLimiter,
5
+ createWebhookAnomalyTracker,
6
+ type RuntimeEnv,
7
+ WEBHOOK_ANOMALY_COUNTER_DEFAULTS,
8
+ WEBHOOK_RATE_LIMIT_DEFAULTS,
9
+ } from "openclaw/plugin-sdk";
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
+
15
+ export const FEISHU_WEBHOOK_MAX_BODY_BYTES = 1024 * 1024;
16
+ export const FEISHU_WEBHOOK_BODY_TIMEOUT_MS = 30_000;
17
+
18
+ export const feishuWebhookRateLimiter = createFixedWindowRateLimiter({
19
+ windowMs: WEBHOOK_RATE_LIMIT_DEFAULTS.windowMs,
20
+ maxRequests: WEBHOOK_RATE_LIMIT_DEFAULTS.maxRequests,
21
+ maxTrackedKeys: WEBHOOK_RATE_LIMIT_DEFAULTS.maxTrackedKeys,
22
+ });
23
+
24
+ const feishuWebhookAnomalyTracker = createWebhookAnomalyTracker({
25
+ maxTrackedKeys: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.maxTrackedKeys,
26
+ ttlMs: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.ttlMs,
27
+ logEvery: WEBHOOK_ANOMALY_COUNTER_DEFAULTS.logEvery,
28
+ });
29
+
30
+ export function clearFeishuWebhookRateLimitStateForTest(): void {
31
+ feishuWebhookRateLimiter.clear();
32
+ feishuWebhookAnomalyTracker.clear();
33
+ }
34
+
35
+ export function getFeishuWebhookRateLimitStateSizeForTest(): number {
36
+ return feishuWebhookRateLimiter.size();
37
+ }
38
+
39
+ export function isWebhookRateLimitedForTest(key: string, nowMs: number): boolean {
40
+ return feishuWebhookRateLimiter.isRateLimited(key, nowMs);
41
+ }
42
+
43
+ export function recordWebhookStatus(
44
+ runtime: RuntimeEnv | undefined,
45
+ accountId: string,
46
+ path: string,
47
+ statusCode: number,
48
+ ): void {
49
+ feishuWebhookAnomalyTracker.record({
50
+ key: `${accountId}:${path}:${statusCode}`,
51
+ statusCode,
52
+ log: runtime?.log ?? console.log,
53
+ message: (count) =>
54
+ `feishu[${accountId}]: webhook anomaly path=${path} status=${statusCode} count=${count}`,
55
+ });
56
+ }
57
+
58
+ export function stopFeishuMonitorState(accountId?: string): void {
59
+ if (accountId) {
60
+ wsClients.delete(accountId);
61
+ const server = httpServers.get(accountId);
62
+ if (server) {
63
+ server.close();
64
+ httpServers.delete(accountId);
65
+ }
66
+ botOpenIds.delete(accountId);
67
+ return;
68
+ }
69
+
70
+ wsClients.clear();
71
+ for (const server of httpServers.values()) {
72
+ server.close();
73
+ }
74
+ httpServers.clear();
75
+ botOpenIds.clear();
76
+ }
@@ -0,0 +1,163 @@
1
+ import * as http from "http";
2
+ import * as Lark from "@larksuiteoapi/node-sdk";
3
+ import {
4
+ applyBasicWebhookRequestGuards,
5
+ type RuntimeEnv,
6
+ installRequestBodyLimitGuard,
7
+ } from "openclaw/plugin-sdk";
8
+ import { createFeishuWSClient } from "./client.js";
9
+ import {
10
+ botOpenIds,
11
+ FEISHU_WEBHOOK_BODY_TIMEOUT_MS,
12
+ FEISHU_WEBHOOK_MAX_BODY_BYTES,
13
+ feishuWebhookRateLimiter,
14
+ httpServers,
15
+ recordWebhookStatus,
16
+ wsClients,
17
+ } from "./monitor.state.js";
18
+ import type { ResolvedFeishuAccount } from "./types.js";
19
+
20
+ export type MonitorTransportParams = {
21
+ account: ResolvedFeishuAccount;
22
+ accountId: string;
23
+ runtime?: RuntimeEnv;
24
+ abortSignal?: AbortSignal;
25
+ eventDispatcher: Lark.EventDispatcher;
26
+ };
27
+
28
+ export async function monitorWebSocket({
29
+ account,
30
+ accountId,
31
+ runtime,
32
+ abortSignal,
33
+ eventDispatcher,
34
+ }: MonitorTransportParams): Promise<void> {
35
+ const log = runtime?.log ?? console.log;
36
+ log(`feishu[${accountId}]: starting WebSocket connection...`);
37
+
38
+ const wsClient = createFeishuWSClient(account);
39
+ wsClients.set(accountId, wsClient);
40
+
41
+ return new Promise((resolve, reject) => {
42
+ const cleanup = () => {
43
+ wsClients.delete(accountId);
44
+ botOpenIds.delete(accountId);
45
+ };
46
+
47
+ const handleAbort = () => {
48
+ log(`feishu[${accountId}]: abort signal received, stopping`);
49
+ cleanup();
50
+ resolve();
51
+ };
52
+
53
+ if (abortSignal?.aborted) {
54
+ cleanup();
55
+ resolve();
56
+ return;
57
+ }
58
+
59
+ abortSignal?.addEventListener("abort", handleAbort, { once: true });
60
+
61
+ try {
62
+ wsClient.start({ eventDispatcher });
63
+ log(`feishu[${accountId}]: WebSocket client started`);
64
+ } catch (err) {
65
+ cleanup();
66
+ abortSignal?.removeEventListener("abort", handleAbort);
67
+ reject(err);
68
+ }
69
+ });
70
+ }
71
+
72
+ export async function monitorWebhook({
73
+ account,
74
+ accountId,
75
+ runtime,
76
+ abortSignal,
77
+ eventDispatcher,
78
+ }: MonitorTransportParams): Promise<void> {
79
+ const log = runtime?.log ?? console.log;
80
+ const error = runtime?.error ?? console.error;
81
+
82
+ const port = account.config.webhookPort ?? 3000;
83
+ const path = account.config.webhookPath ?? "/feishu/events";
84
+ const host = account.config.webhookHost ?? "127.0.0.1";
85
+
86
+ log(`feishu[${accountId}]: starting Webhook server on ${host}:${port}, path ${path}...`);
87
+
88
+ const server = http.createServer();
89
+ const webhookHandler = Lark.adaptDefault(path, eventDispatcher, { autoChallenge: true });
90
+
91
+ server.on("request", (req, res) => {
92
+ res.on("finish", () => {
93
+ recordWebhookStatus(runtime, accountId, path, res.statusCode);
94
+ });
95
+
96
+ const rateLimitKey = `${accountId}:${path}:${req.socket.remoteAddress ?? "unknown"}`;
97
+ if (
98
+ !applyBasicWebhookRequestGuards({
99
+ req,
100
+ res,
101
+ rateLimiter: feishuWebhookRateLimiter,
102
+ rateLimitKey,
103
+ nowMs: Date.now(),
104
+ requireJsonContentType: true,
105
+ })
106
+ ) {
107
+ return;
108
+ }
109
+
110
+ const guard = installRequestBodyLimitGuard(req, res, {
111
+ maxBytes: FEISHU_WEBHOOK_MAX_BODY_BYTES,
112
+ timeoutMs: FEISHU_WEBHOOK_BODY_TIMEOUT_MS,
113
+ responseFormat: "text",
114
+ });
115
+ if (guard.isTripped()) {
116
+ return;
117
+ }
118
+
119
+ void Promise.resolve(webhookHandler(req, res))
120
+ .catch((err) => {
121
+ if (!guard.isTripped()) {
122
+ error(`feishu[${accountId}]: webhook handler error: ${String(err)}`);
123
+ }
124
+ })
125
+ .finally(() => {
126
+ guard.dispose();
127
+ });
128
+ });
129
+
130
+ httpServers.set(accountId, server);
131
+
132
+ return new Promise((resolve, reject) => {
133
+ const cleanup = () => {
134
+ server.close();
135
+ httpServers.delete(accountId);
136
+ botOpenIds.delete(accountId);
137
+ };
138
+
139
+ const handleAbort = () => {
140
+ log(`feishu[${accountId}]: abort signal received, stopping Webhook server`);
141
+ cleanup();
142
+ resolve();
143
+ };
144
+
145
+ if (abortSignal?.aborted) {
146
+ cleanup();
147
+ resolve();
148
+ return;
149
+ }
150
+
151
+ abortSignal?.addEventListener("abort", handleAbort, { once: true });
152
+
153
+ server.listen(port, host, () => {
154
+ log(`feishu[${accountId}]: Webhook server listening on ${host}:${port}`);
155
+ });
156
+
157
+ server.on("error", (err) => {
158
+ error(`feishu[${accountId}]: Webhook server error: ${err}`);
159
+ abortSignal?.removeEventListener("abort", handleAbort);
160
+ reject(err);
161
+ });
162
+ });
163
+ }