@kodelyth/feishu 2026.5.42 → 2026.6.2

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 +19 -6
  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
package/src/accounts.ts DELETED
@@ -1,333 +0,0 @@
1
- import {
2
- DEFAULT_ACCOUNT_ID,
3
- type KlawConfig as ClawdbotConfig,
4
- createAccountListHelpers,
5
- hasConfiguredAccountValue,
6
- normalizeAccountId,
7
- normalizeOptionalAccountId,
8
- resolveMergedAccountConfig,
9
- } from "klaw/plugin-sdk/account-resolution";
10
- import { coerceSecretRef } from "klaw/plugin-sdk/provider-auth";
11
- import { normalizeString } from "./comment-shared.js";
12
- import type {
13
- FeishuConfig,
14
- FeishuAccountConfig,
15
- FeishuDefaultAccountSelectionSource,
16
- FeishuDomain,
17
- ResolvedFeishuAccount,
18
- } from "./types.js";
19
-
20
- const { listAccountIds: listFeishuAccountIds, resolveDefaultAccountId } = createAccountListHelpers(
21
- "feishu",
22
- {
23
- allowUnlistedDefaultAccount: true,
24
- hasImplicitDefaultAccount: (cfg) => {
25
- const feishu = cfg.channels?.feishu;
26
- return (
27
- hasConfiguredAccountValue(feishu?.appId) && hasConfiguredAccountValue(feishu?.appSecret)
28
- );
29
- },
30
- },
31
- );
32
-
33
- export { listFeishuAccountIds };
34
-
35
- type FeishuCredentialResolutionMode = "inspect" | "strict";
36
- type FeishuResolvedSecretRef = NonNullable<ReturnType<typeof coerceSecretRef>>;
37
-
38
- function formatSecretRefLabel(ref: FeishuResolvedSecretRef): string {
39
- return `${ref.source}:${ref.provider}:${ref.id}`;
40
- }
41
-
42
- export class FeishuSecretRefUnavailableError extends Error {
43
- path: string;
44
-
45
- constructor(path: string, ref: FeishuResolvedSecretRef) {
46
- super(
47
- `${path}: unresolved SecretRef "${formatSecretRefLabel(ref)}". ` +
48
- "Resolve this command against an active gateway runtime snapshot before reading it.",
49
- );
50
- this.name = "FeishuSecretRefUnavailableError";
51
- this.path = path;
52
- }
53
- }
54
-
55
- export function isFeishuSecretRefUnavailableError(
56
- error: unknown,
57
- ): error is FeishuSecretRefUnavailableError {
58
- return error instanceof FeishuSecretRefUnavailableError;
59
- }
60
-
61
- function resolveFeishuSecretLike(params: {
62
- value: unknown;
63
- path: string;
64
- mode: FeishuCredentialResolutionMode;
65
- allowEnvSecretRefRead?: boolean;
66
- }): string | undefined {
67
- const asString = normalizeString(params.value);
68
- if (asString) {
69
- return asString;
70
- }
71
-
72
- const ref = coerceSecretRef(params.value);
73
- if (!ref) {
74
- return undefined;
75
- }
76
-
77
- if (params.mode === "inspect") {
78
- if (params.allowEnvSecretRefRead && ref.source === "env") {
79
- const envValue = normalizeString(process.env[ref.id]);
80
- if (envValue) {
81
- return envValue;
82
- }
83
- }
84
- return undefined;
85
- }
86
-
87
- throw new FeishuSecretRefUnavailableError(params.path, ref);
88
- }
89
-
90
- function resolveFeishuBaseCredentials(
91
- cfg: FeishuConfig | undefined,
92
- mode: FeishuCredentialResolutionMode,
93
- ): {
94
- appId: string;
95
- appSecret: string;
96
- domain: FeishuDomain;
97
- } | null {
98
- const appId = resolveFeishuSecretLike({
99
- value: cfg?.appId,
100
- path: "channels.feishu.appId",
101
- mode,
102
- allowEnvSecretRefRead: true,
103
- });
104
- const appSecret = resolveFeishuSecretLike({
105
- value: cfg?.appSecret,
106
- path: "channels.feishu.appSecret",
107
- mode,
108
- allowEnvSecretRefRead: true,
109
- });
110
-
111
- if (!appId || !appSecret) {
112
- return null;
113
- }
114
-
115
- return {
116
- appId,
117
- appSecret,
118
- domain: cfg?.domain ?? "feishu",
119
- };
120
- }
121
-
122
- function resolveFeishuEventSecrets(
123
- cfg: FeishuConfig | undefined,
124
- mode: FeishuCredentialResolutionMode,
125
- ): {
126
- encryptKey?: string;
127
- verificationToken?: string;
128
- } {
129
- return {
130
- encryptKey:
131
- (cfg?.connectionMode ?? "websocket") === "webhook"
132
- ? resolveFeishuSecretLike({
133
- value: cfg?.encryptKey,
134
- path: "channels.feishu.encryptKey",
135
- mode,
136
- allowEnvSecretRefRead: true,
137
- })
138
- : normalizeString(cfg?.encryptKey),
139
- verificationToken: resolveFeishuSecretLike({
140
- value: cfg?.verificationToken,
141
- path: "channels.feishu.verificationToken",
142
- mode,
143
- allowEnvSecretRefRead: true,
144
- }),
145
- };
146
- }
147
-
148
- /**
149
- * Resolve the default account selection and its source.
150
- */
151
- export function resolveDefaultFeishuAccountSelection(cfg: ClawdbotConfig): {
152
- accountId: string;
153
- source: FeishuDefaultAccountSelectionSource;
154
- } {
155
- const preferred = normalizeOptionalAccountId(
156
- (cfg.channels?.feishu as FeishuConfig | undefined)?.defaultAccount,
157
- );
158
- if (preferred) {
159
- return {
160
- accountId: preferred,
161
- source: "explicit-default",
162
- };
163
- }
164
- const ids = listFeishuAccountIds(cfg);
165
- if (ids.includes(DEFAULT_ACCOUNT_ID)) {
166
- return {
167
- accountId: DEFAULT_ACCOUNT_ID,
168
- source: "mapped-default",
169
- };
170
- }
171
- return {
172
- accountId: ids[0] ?? DEFAULT_ACCOUNT_ID,
173
- source: "fallback",
174
- };
175
- }
176
-
177
- /**
178
- * Resolve the default account ID.
179
- */
180
- export function resolveDefaultFeishuAccountId(cfg: ClawdbotConfig): string {
181
- return resolveDefaultAccountId(cfg);
182
- }
183
-
184
- /**
185
- * Merge top-level config with account-specific config.
186
- * Account-specific fields override top-level fields.
187
- */
188
- function mergeFeishuAccountConfig(cfg: ClawdbotConfig, accountId: string): FeishuConfig {
189
- const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
190
- return resolveMergedAccountConfig<FeishuConfig>({
191
- channelConfig: feishuCfg,
192
- accounts: feishuCfg?.accounts as Record<string, Partial<FeishuConfig>> | undefined,
193
- accountId,
194
- omitKeys: ["defaultAccount"],
195
- });
196
- }
197
-
198
- /**
199
- * Resolve Feishu credentials from a config.
200
- */
201
- export function resolveFeishuCredentials(cfg?: FeishuConfig): {
202
- appId: string;
203
- appSecret: string;
204
- encryptKey?: string;
205
- verificationToken?: string;
206
- domain: FeishuDomain;
207
- } | null;
208
- export function resolveFeishuCredentials(
209
- cfg: FeishuConfig | undefined,
210
- options: {
211
- mode?: FeishuCredentialResolutionMode;
212
- allowUnresolvedSecretRef?: boolean;
213
- },
214
- ): {
215
- appId: string;
216
- appSecret: string;
217
- encryptKey?: string;
218
- verificationToken?: string;
219
- domain: FeishuDomain;
220
- } | null;
221
- export function resolveFeishuCredentials(
222
- cfg?: FeishuConfig,
223
- options?: {
224
- mode?: FeishuCredentialResolutionMode;
225
- allowUnresolvedSecretRef?: boolean;
226
- },
227
- ): {
228
- appId: string;
229
- appSecret: string;
230
- encryptKey?: string;
231
- verificationToken?: string;
232
- domain: FeishuDomain;
233
- } | null {
234
- const mode = options?.mode ?? (options?.allowUnresolvedSecretRef ? "inspect" : "strict");
235
- const base = resolveFeishuBaseCredentials(cfg, mode);
236
- if (!base) {
237
- return null;
238
- }
239
- const eventSecrets = resolveFeishuEventSecrets(cfg, mode);
240
-
241
- return {
242
- ...base,
243
- ...eventSecrets,
244
- };
245
- }
246
-
247
- export function inspectFeishuCredentials(cfg?: FeishuConfig) {
248
- return resolveFeishuCredentials(cfg, { mode: "inspect" });
249
- }
250
-
251
- function buildResolvedFeishuAccount(params: {
252
- cfg: ClawdbotConfig;
253
- accountId?: string | null;
254
- baseMode: FeishuCredentialResolutionMode;
255
- eventSecretMode: FeishuCredentialResolutionMode;
256
- }): ResolvedFeishuAccount {
257
- const hasExplicitAccountId =
258
- typeof params.accountId === "string" && params.accountId.trim() !== "";
259
- const defaultSelection = hasExplicitAccountId
260
- ? null
261
- : resolveDefaultFeishuAccountSelection(params.cfg);
262
- const accountId = hasExplicitAccountId
263
- ? normalizeAccountId(params.accountId)
264
- : (defaultSelection?.accountId ?? DEFAULT_ACCOUNT_ID);
265
- const selectionSource = hasExplicitAccountId
266
- ? "explicit"
267
- : (defaultSelection?.source ?? "fallback");
268
- const feishuCfg = params.cfg.channels?.feishu as FeishuConfig | undefined;
269
-
270
- const baseEnabled = feishuCfg?.enabled !== false;
271
- const merged = mergeFeishuAccountConfig(params.cfg, accountId);
272
- const accountEnabled = merged.enabled !== false;
273
- const enabled = baseEnabled && accountEnabled;
274
- const baseCreds = resolveFeishuBaseCredentials(merged, params.baseMode);
275
- const eventSecrets = resolveFeishuEventSecrets(merged, params.eventSecretMode);
276
- const accountName = (merged as FeishuAccountConfig).name;
277
-
278
- return {
279
- accountId,
280
- selectionSource,
281
- enabled,
282
- configured: Boolean(baseCreds),
283
- name: typeof accountName === "string" ? accountName.trim() || undefined : undefined,
284
- appId: baseCreds?.appId,
285
- appSecret: baseCreds?.appSecret,
286
- encryptKey: eventSecrets.encryptKey,
287
- verificationToken: eventSecrets.verificationToken,
288
- domain: baseCreds?.domain ?? "feishu",
289
- config: merged,
290
- };
291
- }
292
-
293
- /**
294
- * Resolve a read-only Feishu account snapshot for CLI/config surfaces.
295
- * Unresolved SecretRefs are treated as unavailable instead of throwing.
296
- */
297
- export function resolveFeishuAccount(params: {
298
- cfg: ClawdbotConfig;
299
- accountId?: string | null;
300
- }): ResolvedFeishuAccount {
301
- return buildResolvedFeishuAccount({
302
- ...params,
303
- baseMode: "inspect",
304
- eventSecretMode: "inspect",
305
- });
306
- }
307
-
308
- /**
309
- * Resolve a runtime Feishu account.
310
- * Required app credentials stay strict; event-only secrets can be required by callers.
311
- */
312
- export function resolveFeishuRuntimeAccount(
313
- params: {
314
- cfg: ClawdbotConfig;
315
- accountId?: string | null;
316
- },
317
- options?: { requireEventSecrets?: boolean },
318
- ): ResolvedFeishuAccount {
319
- return buildResolvedFeishuAccount({
320
- ...params,
321
- baseMode: "strict",
322
- eventSecretMode: options?.requireEventSecrets ? "strict" : "inspect",
323
- });
324
- }
325
-
326
- /**
327
- * List all enabled and configured accounts.
328
- */
329
- export function listEnabledFeishuAccounts(cfg: ClawdbotConfig): ResolvedFeishuAccount[] {
330
- return listFeishuAccountIds(cfg)
331
- .map((accountId) => resolveFeishuAccount({ cfg, accountId }))
332
- .filter((account) => account.enabled && account.configured);
333
- }
@@ -1,21 +0,0 @@
1
- import type { ClawdbotConfig } from "./bot-runtime-api.js";
2
-
3
- type ReasoningDefault = "on" | "stream" | "off";
4
-
5
- const DEFAULT_AGENT_ID = "main";
6
-
7
- function normalizeAgentId(value: string | undefined | null): string {
8
- const normalized = (value ?? "").trim().toLowerCase();
9
- return normalized || DEFAULT_AGENT_ID;
10
- }
11
-
12
- export function resolveFeishuConfigReasoningDefault(
13
- cfg: ClawdbotConfig,
14
- agentId: string,
15
- ): ReasoningDefault {
16
- const id = normalizeAgentId(agentId);
17
- const agentDefault = cfg.agents?.list?.find(
18
- (entry) => normalizeAgentId(entry?.id) === id,
19
- )?.reasoningDefault;
20
- return agentDefault ?? cfg.agents?.defaults?.reasoningDefault ?? "off";
21
- }
@@ -1,331 +0,0 @@
1
- /**
2
- * Feishu app registration via OAuth device-code flow.
3
- *
4
- * Migrated from feishu-plugin-cli's `feishu-auth.ts` and `install-prompts.ts`.
5
- * Replaces axios with native fetch, removes inquirer/ora/chalk in favor of
6
- * the klaw WizardPrompter surface.
7
- */
8
- import { fetchWithSsrFGuard } from "klaw/plugin-sdk/ssrf-runtime";
9
- import { renderQrTerminal } from "./qr-terminal.js";
10
- import type { FeishuDomain } from "./types.js";
11
-
12
- // ---------------------------------------------------------------------------
13
- // Constants
14
- // ---------------------------------------------------------------------------
15
-
16
- const FEISHU_ACCOUNTS_URL = "https://accounts.feishu.cn";
17
- const LARK_ACCOUNTS_URL = "https://accounts.larksuite.com";
18
-
19
- const REGISTRATION_PATH = "/oauth/v1/app/registration";
20
-
21
- const REQUEST_TIMEOUT_MS = 10_000;
22
-
23
- // ---------------------------------------------------------------------------
24
- // Types
25
- // ---------------------------------------------------------------------------
26
-
27
- export interface AppRegistrationResult {
28
- appId: string;
29
- appSecret: string;
30
- domain: FeishuDomain;
31
- openId?: string;
32
- }
33
-
34
- interface InitResponse {
35
- nonce: string;
36
- supported_auth_methods: string[];
37
- }
38
-
39
- export interface BeginResult {
40
- deviceCode: string;
41
- qrUrl: string;
42
- userCode: string;
43
- interval: number;
44
- expireIn: number;
45
- }
46
-
47
- interface RawBeginResponse {
48
- device_code: string;
49
- verification_uri: string;
50
- user_code: string;
51
- verification_uri_complete: string;
52
- interval: number;
53
- expire_in: number;
54
- }
55
-
56
- interface PollResponse {
57
- client_id?: string;
58
- client_secret?: string;
59
- user_info?: {
60
- open_id?: string;
61
- tenant_brand?: "feishu" | "lark";
62
- };
63
- error?: string;
64
- error_description?: string;
65
- }
66
-
67
- export type PollOutcome =
68
- | { status: "success"; result: AppRegistrationResult }
69
- | { status: "access_denied" }
70
- | { status: "expired" }
71
- | { status: "timeout" }
72
- | { status: "error"; message: string };
73
-
74
- // ---------------------------------------------------------------------------
75
- // Helpers
76
- // ---------------------------------------------------------------------------
77
-
78
- function accountsBaseUrl(domain: FeishuDomain): string {
79
- return domain === "lark" ? LARK_ACCOUNTS_URL : FEISHU_ACCOUNTS_URL;
80
- }
81
-
82
- async function postRegistration<T>(baseUrl: string, body: Record<string, string>): Promise<T> {
83
- return await fetchFeishuJson<T>({
84
- url: `${baseUrl}${REGISTRATION_PATH}`,
85
- init: {
86
- method: "POST",
87
- headers: { "Content-Type": "application/x-www-form-urlencoded" },
88
- body: new URLSearchParams(body).toString(),
89
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
90
- },
91
- auditContext: "feishu.app-registration.post",
92
- });
93
- }
94
-
95
- async function fetchFeishuJson<T>(params: {
96
- url: string;
97
- init: RequestInit;
98
- auditContext: string;
99
- }): Promise<T> {
100
- const { response, release } = await fetchWithSsrFGuard({
101
- url: params.url,
102
- init: params.init,
103
- policy: { allowedHostnames: [new URL(params.url).hostname] },
104
- auditContext: params.auditContext,
105
- });
106
- try {
107
- // Registration poll returns 4xx for pending/error states with a JSON body.
108
- return (await response.json()) as T;
109
- } finally {
110
- await release();
111
- }
112
- }
113
-
114
- // ---------------------------------------------------------------------------
115
- // Public API
116
- // ---------------------------------------------------------------------------
117
-
118
- /**
119
- * Step 1: Initialize registration and verify the environment supports
120
- * `client_secret` auth.
121
- *
122
- * @throws If the environment does not support `client_secret`.
123
- */
124
- export async function initAppRegistration(domain: FeishuDomain = "feishu"): Promise<void> {
125
- const baseUrl = accountsBaseUrl(domain);
126
- const res = await postRegistration<InitResponse>(baseUrl, { action: "init" });
127
-
128
- if (!res.supported_auth_methods?.includes("client_secret")) {
129
- throw new Error("Current environment does not support client_secret auth method");
130
- }
131
- }
132
-
133
- /**
134
- * Step 2: Begin the device-code flow. Returns a device code and a QR URL
135
- * that the user should scan with Feishu/Lark mobile app.
136
- */
137
- export async function beginAppRegistration(domain: FeishuDomain = "feishu"): Promise<BeginResult> {
138
- const baseUrl = accountsBaseUrl(domain);
139
- const res = await postRegistration<RawBeginResponse>(baseUrl, {
140
- action: "begin",
141
- archetype: "PersonalAgent",
142
- auth_method: "client_secret",
143
- request_user_info: "open_id",
144
- });
145
-
146
- const qrUrl = new URL(res.verification_uri_complete);
147
- qrUrl.searchParams.set("from", "oc_onboard");
148
- qrUrl.searchParams.set("tp", "ob_cli_app");
149
-
150
- return {
151
- deviceCode: res.device_code,
152
- qrUrl: qrUrl.toString(),
153
- userCode: res.user_code,
154
- interval: res.interval || 5,
155
- expireIn: res.expire_in || 600,
156
- };
157
- }
158
-
159
- /**
160
- * Step 3: Poll for authorization result until success, denial, expiry, or
161
- * timeout. Automatically handles domain switching when `tenant_brand` is
162
- * detected as "lark".
163
- */
164
- export async function pollAppRegistration(params: {
165
- deviceCode: string;
166
- interval: number;
167
- expireIn: number;
168
- initialDomain?: FeishuDomain;
169
- abortSignal?: AbortSignal;
170
- /** Registration type parameter. The CLI bot QR flow uses "ob_cli_app". */
171
- tp?: string;
172
- }): Promise<PollOutcome> {
173
- const { deviceCode, expireIn, initialDomain = "feishu", abortSignal, tp } = params;
174
- let currentInterval = params.interval;
175
- let domain: FeishuDomain = initialDomain;
176
- let domainSwitched = false;
177
-
178
- const deadline = Date.now() + expireIn * 1000;
179
-
180
- while (Date.now() < deadline) {
181
- if (abortSignal?.aborted) {
182
- return { status: "timeout" };
183
- }
184
-
185
- const baseUrl = accountsBaseUrl(domain);
186
-
187
- let pollRes: PollResponse;
188
- try {
189
- pollRes = await postRegistration<PollResponse>(baseUrl, {
190
- action: "poll",
191
- device_code: deviceCode,
192
- ...(tp ? { tp } : {}),
193
- });
194
- } catch {
195
- // Transient network error — keep polling.
196
- await sleep(currentInterval * 1000);
197
- continue;
198
- }
199
-
200
- // Domain auto-detection: switch to lark if tenant_brand says so.
201
- if (pollRes.user_info?.tenant_brand) {
202
- const isLark = pollRes.user_info.tenant_brand === "lark";
203
- if (!domainSwitched && isLark) {
204
- domain = "lark";
205
- domainSwitched = true;
206
- // Retry poll immediately with the correct domain.
207
- continue;
208
- }
209
- }
210
-
211
- // Success.
212
- if (pollRes.client_id && pollRes.client_secret) {
213
- return {
214
- status: "success",
215
- result: {
216
- appId: pollRes.client_id,
217
- appSecret: pollRes.client_secret,
218
- domain,
219
- openId: pollRes.user_info?.open_id,
220
- },
221
- };
222
- }
223
-
224
- // Error handling.
225
- if (pollRes.error) {
226
- if (pollRes.error === "authorization_pending") {
227
- // Continue waiting.
228
- } else if (pollRes.error === "slow_down") {
229
- currentInterval += 5;
230
- } else if (pollRes.error === "access_denied") {
231
- return { status: "access_denied" };
232
- } else if (pollRes.error === "expired_token") {
233
- return { status: "expired" };
234
- } else {
235
- return {
236
- status: "error",
237
- message: `${pollRes.error}: ${pollRes.error_description ?? "unknown"}`,
238
- };
239
- }
240
- }
241
-
242
- await sleep(currentInterval * 1000);
243
- }
244
-
245
- return { status: "timeout" };
246
- }
247
-
248
- /**
249
- * Print QR code directly to stdout.
250
- *
251
- * QR codes must be printed without any surrounding box/border decoration,
252
- * otherwise the pattern is corrupted and cannot be scanned.
253
- */
254
- export async function printQrCode(url: string): Promise<void> {
255
- const output = await renderQrTerminal(url);
256
- process.stdout.write(output.endsWith("\n") ? output : `${output}\n`);
257
- }
258
-
259
- /**
260
- * Fetch the app owner's open_id using the application.v6.application.get API.
261
- *
262
- * Used during setup to auto-populate security policy allowlists.
263
- * Returns undefined on any failure (fail-open).
264
- */
265
- export async function getAppOwnerOpenId(params: {
266
- appId: string;
267
- appSecret: string;
268
- domain?: FeishuDomain;
269
- }): Promise<string | undefined> {
270
- const baseUrl =
271
- params.domain === "lark" ? "https://open.larksuite.com" : "https://open.feishu.cn";
272
-
273
- try {
274
- // First, get a tenant_access_token.
275
- const tokenData = await fetchFeishuJson<{
276
- code?: number;
277
- tenant_access_token?: string;
278
- }>({
279
- url: `${baseUrl}/open-apis/auth/v3/tenant_access_token/internal`,
280
- init: {
281
- method: "POST",
282
- headers: { "Content-Type": "application/json" },
283
- body: JSON.stringify({ app_id: params.appId, app_secret: params.appSecret }),
284
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
285
- },
286
- auditContext: "feishu.app-registration.owner-token",
287
- });
288
- if (!tokenData.tenant_access_token) {
289
- return undefined;
290
- }
291
-
292
- // Query app info for the owner's open_id.
293
- const appData = await fetchFeishuJson<{
294
- code?: number;
295
- data?: {
296
- app?: {
297
- owner?: { owner_id?: string; owner_type?: number; type?: number };
298
- creator_id?: string;
299
- };
300
- };
301
- }>({
302
- url: `${baseUrl}/open-apis/application/v6/applications/${params.appId}?user_id_type=open_id`,
303
- init: {
304
- method: "GET",
305
- headers: {
306
- Authorization: `Bearer ${tokenData.tenant_access_token}`,
307
- "Content-Type": "application/json",
308
- },
309
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
310
- },
311
- auditContext: "feishu.app-registration.owner-app",
312
- });
313
- if (appData.code !== 0) {
314
- return undefined;
315
- }
316
-
317
- const app = appData.data?.app;
318
- const owner = app?.owner;
319
- const ownerType = owner?.owner_type ?? owner?.type;
320
- // owner_type=2 means enterprise member; use owner_id. Otherwise fallback to creator_id.
321
- return ownerType === 2 && owner?.owner_id
322
- ? owner.owner_id
323
- : (app?.creator_id ?? owner?.owner_id);
324
- } catch {
325
- return undefined;
326
- }
327
- }
328
-
329
- function sleep(ms: number): Promise<void> {
330
- return new Promise((resolve) => setTimeout(resolve, ms));
331
- }
@@ -1,24 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import { feishuApprovalAuth } from "./approval-auth.js";
3
-
4
- describe("feishuApprovalAuth", () => {
5
- it("authorizes open_id approvers and ignores user_id-only allowlists", () => {
6
- expect(
7
- feishuApprovalAuth.authorizeActorAction({
8
- cfg: { channels: { feishu: { allowFrom: ["ou_owner"] } } },
9
- senderId: "ou_owner",
10
- action: "approve",
11
- approvalKind: "exec",
12
- }),
13
- ).toEqual({ authorized: true });
14
-
15
- expect(
16
- feishuApprovalAuth.authorizeActorAction({
17
- cfg: { channels: { feishu: { allowFrom: ["user_123"] } } },
18
- senderId: "ou_attacker",
19
- action: "approve",
20
- approvalKind: "exec",
21
- }),
22
- ).toEqual({ authorized: true });
23
- });
24
- });