@openclaw/feishu 2026.5.2 → 2026.5.3-beta.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 (224) hide show
  1. package/dist/accounts-Ba3-WP1z.js +423 -0
  2. package/dist/api.js +2280 -0
  3. package/dist/app-registration-B8qc1MCM.js +184 -0
  4. package/dist/audio-preflight.runtime-BPlzkO3l.js +7 -0
  5. package/dist/card-interaction-BfRLgvw_.js +96 -0
  6. package/dist/channel-CSD_Jt8I.js +1668 -0
  7. package/dist/channel-entry.js +22 -0
  8. package/dist/channel-plugin-api.js +2 -0
  9. package/dist/channel.runtime-DYsXcD36.js +700 -0
  10. package/dist/client-DBVoQL5w.js +157 -0
  11. package/dist/contract-api.js +9 -0
  12. package/dist/conversation-id-DWS3Ep2A.js +139 -0
  13. package/dist/directory.static-f3EeoRJd.js +44 -0
  14. package/dist/drive-C5eJLJr7.js +883 -0
  15. package/dist/index.js +68 -0
  16. package/dist/monitor-CT189QfR.js +60 -0
  17. package/dist/monitor.account-dJV2jO8C.js +4990 -0
  18. package/dist/monitor.state-DYM02ipp.js +100 -0
  19. package/dist/policy-D6c-wMPl.js +118 -0
  20. package/dist/probe-BNzzU_uR.js +149 -0
  21. package/dist/rolldown-runtime-DUslC3ob.js +14 -0
  22. package/dist/runtime-CG0DuRCy.js +8 -0
  23. package/dist/runtime-api.js +14 -0
  24. package/dist/secret-contract-Dm4Z_zQN.js +119 -0
  25. package/dist/secret-contract-api.js +2 -0
  26. package/dist/security-audit-DqJdocrN.js +11 -0
  27. package/dist/security-audit-shared-ByuMx9cJ.js +38 -0
  28. package/dist/security-contract-api.js +2 -0
  29. package/dist/send-DowxxbpH.js +1218 -0
  30. package/dist/session-conversation-B4nrW-vo.js +27 -0
  31. package/dist/session-key-api.js +2 -0
  32. package/dist/setup-api.js +2 -0
  33. package/dist/setup-entry.js +15 -0
  34. package/dist/subagent-hooks-C3UhPVLV.js +227 -0
  35. package/dist/subagent-hooks-api.js +23 -0
  36. package/dist/targets-JMFJRKSe.js +48 -0
  37. package/dist/thread-bindings-BmS6TLes.js +222 -0
  38. package/package.json +15 -6
  39. package/api.ts +0 -31
  40. package/channel-entry.ts +0 -20
  41. package/channel-plugin-api.ts +0 -1
  42. package/contract-api.ts +0 -16
  43. package/index.ts +0 -82
  44. package/runtime-api.ts +0 -55
  45. package/secret-contract-api.ts +0 -5
  46. package/security-contract-api.ts +0 -1
  47. package/session-key-api.ts +0 -1
  48. package/setup-api.ts +0 -3
  49. package/setup-entry.test.ts +0 -14
  50. package/setup-entry.ts +0 -13
  51. package/src/accounts.test.ts +0 -459
  52. package/src/accounts.ts +0 -326
  53. package/src/app-registration.ts +0 -331
  54. package/src/approval-auth.test.ts +0 -24
  55. package/src/approval-auth.ts +0 -25
  56. package/src/async.test.ts +0 -35
  57. package/src/async.ts +0 -104
  58. package/src/audio-preflight.runtime.ts +0 -9
  59. package/src/bitable.test.ts +0 -131
  60. package/src/bitable.ts +0 -762
  61. package/src/bot-content.ts +0 -474
  62. package/src/bot-group-name.test.ts +0 -108
  63. package/src/bot-runtime-api.ts +0 -12
  64. package/src/bot-sender-name.ts +0 -125
  65. package/src/bot.broadcast.test.ts +0 -463
  66. package/src/bot.card-action.test.ts +0 -577
  67. package/src/bot.checkBotMentioned.test.ts +0 -265
  68. package/src/bot.helpers.test.ts +0 -118
  69. package/src/bot.stripBotMention.test.ts +0 -126
  70. package/src/bot.test.ts +0 -3040
  71. package/src/bot.ts +0 -1559
  72. package/src/card-action.ts +0 -447
  73. package/src/card-interaction.test.ts +0 -129
  74. package/src/card-interaction.ts +0 -159
  75. package/src/card-test-helpers.ts +0 -47
  76. package/src/card-ux-approval.ts +0 -65
  77. package/src/card-ux-launcher.test.ts +0 -99
  78. package/src/card-ux-launcher.ts +0 -121
  79. package/src/card-ux-shared.ts +0 -33
  80. package/src/channel-runtime-api.ts +0 -16
  81. package/src/channel.runtime.ts +0 -47
  82. package/src/channel.test.ts +0 -959
  83. package/src/channel.ts +0 -1313
  84. package/src/chat-schema.ts +0 -25
  85. package/src/chat.test.ts +0 -196
  86. package/src/chat.ts +0 -188
  87. package/src/client.test.ts +0 -433
  88. package/src/client.ts +0 -290
  89. package/src/comment-dispatcher-runtime-api.ts +0 -6
  90. package/src/comment-dispatcher.test.ts +0 -169
  91. package/src/comment-dispatcher.ts +0 -107
  92. package/src/comment-handler-runtime-api.ts +0 -3
  93. package/src/comment-handler.test.ts +0 -486
  94. package/src/comment-handler.ts +0 -309
  95. package/src/comment-reaction.test.ts +0 -166
  96. package/src/comment-reaction.ts +0 -259
  97. package/src/comment-shared.test.ts +0 -182
  98. package/src/comment-shared.ts +0 -406
  99. package/src/comment-target.ts +0 -44
  100. package/src/config-schema.test.ts +0 -309
  101. package/src/config-schema.ts +0 -333
  102. package/src/conversation-id.test.ts +0 -18
  103. package/src/conversation-id.ts +0 -199
  104. package/src/dedup-runtime-api.ts +0 -1
  105. package/src/dedup.ts +0 -141
  106. package/src/directory.static.ts +0 -61
  107. package/src/directory.test.ts +0 -136
  108. package/src/directory.ts +0 -124
  109. package/src/doc-schema.ts +0 -182
  110. package/src/docx-batch-insert.test.ts +0 -91
  111. package/src/docx-batch-insert.ts +0 -223
  112. package/src/docx-color-text.ts +0 -154
  113. package/src/docx-table-ops.test.ts +0 -53
  114. package/src/docx-table-ops.ts +0 -316
  115. package/src/docx-types.ts +0 -38
  116. package/src/docx.account-selection.test.ts +0 -79
  117. package/src/docx.test.ts +0 -685
  118. package/src/docx.ts +0 -1616
  119. package/src/drive-schema.ts +0 -92
  120. package/src/drive.test.ts +0 -1219
  121. package/src/drive.ts +0 -829
  122. package/src/dynamic-agent.ts +0 -137
  123. package/src/event-types.ts +0 -45
  124. package/src/external-keys.test.ts +0 -20
  125. package/src/external-keys.ts +0 -19
  126. package/src/lifecycle.test-support.ts +0 -220
  127. package/src/media.test.ts +0 -900
  128. package/src/media.ts +0 -861
  129. package/src/mention-target.types.ts +0 -5
  130. package/src/mention.ts +0 -114
  131. package/src/message-action-contract.ts +0 -13
  132. package/src/monitor-state-runtime-api.ts +0 -7
  133. package/src/monitor-transport-runtime-api.ts +0 -7
  134. package/src/monitor.account.ts +0 -468
  135. package/src/monitor.acp-init-failure.lifecycle.test-support.ts +0 -219
  136. package/src/monitor.bot-identity.ts +0 -86
  137. package/src/monitor.bot-menu-handler.ts +0 -165
  138. package/src/monitor.bot-menu.lifecycle.test-support.ts +0 -224
  139. package/src/monitor.bot-menu.test.ts +0 -178
  140. package/src/monitor.broadcast.reply-once.lifecycle.test-support.ts +0 -264
  141. package/src/monitor.card-action.lifecycle.test-support.ts +0 -373
  142. package/src/monitor.cleanup.test.ts +0 -376
  143. package/src/monitor.comment-notice-handler.ts +0 -105
  144. package/src/monitor.comment.test.ts +0 -937
  145. package/src/monitor.comment.ts +0 -1386
  146. package/src/monitor.lifecycle.test.ts +0 -4
  147. package/src/monitor.message-handler.ts +0 -339
  148. package/src/monitor.reaction.lifecycle.test-support.ts +0 -68
  149. package/src/monitor.reaction.test.ts +0 -713
  150. package/src/monitor.startup.test.ts +0 -192
  151. package/src/monitor.startup.ts +0 -74
  152. package/src/monitor.state.defaults.test.ts +0 -46
  153. package/src/monitor.state.ts +0 -170
  154. package/src/monitor.synthetic-error.ts +0 -18
  155. package/src/monitor.test-mocks.ts +0 -45
  156. package/src/monitor.transport.ts +0 -424
  157. package/src/monitor.ts +0 -100
  158. package/src/monitor.webhook-e2e.test.ts +0 -272
  159. package/src/monitor.webhook-security.test.ts +0 -264
  160. package/src/monitor.webhook.test-helpers.ts +0 -116
  161. package/src/outbound-runtime-api.ts +0 -1
  162. package/src/outbound.test.ts +0 -935
  163. package/src/outbound.ts +0 -718
  164. package/src/perm-schema.ts +0 -52
  165. package/src/perm.ts +0 -170
  166. package/src/pins.ts +0 -108
  167. package/src/policy.test.ts +0 -334
  168. package/src/policy.ts +0 -236
  169. package/src/post.test.ts +0 -105
  170. package/src/post.ts +0 -275
  171. package/src/probe.test.ts +0 -275
  172. package/src/probe.ts +0 -166
  173. package/src/processing-claims.ts +0 -59
  174. package/src/qr-terminal.ts +0 -1
  175. package/src/reactions.ts +0 -123
  176. package/src/reasoning-preview.test.ts +0 -59
  177. package/src/reasoning-preview.ts +0 -20
  178. package/src/reply-dispatcher-runtime-api.ts +0 -7
  179. package/src/reply-dispatcher.test.ts +0 -1144
  180. package/src/reply-dispatcher.ts +0 -650
  181. package/src/runtime.ts +0 -9
  182. package/src/secret-contract.ts +0 -145
  183. package/src/secret-input.ts +0 -1
  184. package/src/security-audit-shared.ts +0 -69
  185. package/src/security-audit.test.ts +0 -61
  186. package/src/security-audit.ts +0 -1
  187. package/src/send-result.ts +0 -29
  188. package/src/send-target.test.ts +0 -80
  189. package/src/send-target.ts +0 -35
  190. package/src/send.reply-fallback.test.ts +0 -292
  191. package/src/send.test.ts +0 -550
  192. package/src/send.ts +0 -800
  193. package/src/sequential-key.test.ts +0 -72
  194. package/src/sequential-key.ts +0 -28
  195. package/src/sequential-queue.test.ts +0 -92
  196. package/src/sequential-queue.ts +0 -16
  197. package/src/session-conversation.ts +0 -42
  198. package/src/session-route.ts +0 -48
  199. package/src/setup-core.ts +0 -51
  200. package/src/setup-surface.test.ts +0 -174
  201. package/src/setup-surface.ts +0 -581
  202. package/src/streaming-card.test.ts +0 -190
  203. package/src/streaming-card.ts +0 -490
  204. package/src/subagent-hooks.test.ts +0 -603
  205. package/src/subagent-hooks.ts +0 -397
  206. package/src/targets.ts +0 -97
  207. package/src/test-support/lifecycle-test-support.ts +0 -453
  208. package/src/thread-bindings.test.ts +0 -143
  209. package/src/thread-bindings.ts +0 -330
  210. package/src/tool-account-routing.test.ts +0 -187
  211. package/src/tool-account.test.ts +0 -44
  212. package/src/tool-account.ts +0 -93
  213. package/src/tool-factory-test-harness.ts +0 -79
  214. package/src/tool-result.test.ts +0 -32
  215. package/src/tool-result.ts +0 -16
  216. package/src/tools-config.test.ts +0 -21
  217. package/src/tools-config.ts +0 -22
  218. package/src/types.ts +0 -104
  219. package/src/typing.test.ts +0 -144
  220. package/src/typing.ts +0 -214
  221. package/src/wiki-schema.ts +0 -55
  222. package/src/wiki.ts +0 -227
  223. package/subagent-hooks-api.ts +0 -31
  224. package/tsconfig.json +0 -16
package/src/accounts.ts DELETED
@@ -1,326 +0,0 @@
1
- import {
2
- DEFAULT_ACCOUNT_ID,
3
- type OpenClawConfig as ClawdbotConfig,
4
- createAccountListHelpers,
5
- normalizeAccountId,
6
- normalizeOptionalAccountId,
7
- resolveMergedAccountConfig,
8
- } from "openclaw/plugin-sdk/account-resolution";
9
- import { coerceSecretRef } from "openclaw/plugin-sdk/provider-auth";
10
- import { normalizeString } from "./comment-shared.js";
11
- import type {
12
- FeishuConfig,
13
- FeishuAccountConfig,
14
- FeishuDefaultAccountSelectionSource,
15
- FeishuDomain,
16
- ResolvedFeishuAccount,
17
- } from "./types.js";
18
-
19
- const { listAccountIds: listFeishuAccountIds, resolveDefaultAccountId } = createAccountListHelpers(
20
- "feishu",
21
- {
22
- allowUnlistedDefaultAccount: true,
23
- },
24
- );
25
-
26
- export { listFeishuAccountIds };
27
-
28
- type FeishuCredentialResolutionMode = "inspect" | "strict";
29
- type FeishuResolvedSecretRef = NonNullable<ReturnType<typeof coerceSecretRef>>;
30
-
31
- function formatSecretRefLabel(ref: FeishuResolvedSecretRef): string {
32
- return `${ref.source}:${ref.provider}:${ref.id}`;
33
- }
34
-
35
- export class FeishuSecretRefUnavailableError extends Error {
36
- path: string;
37
-
38
- constructor(path: string, ref: FeishuResolvedSecretRef) {
39
- super(
40
- `${path}: unresolved SecretRef "${formatSecretRefLabel(ref)}". ` +
41
- "Resolve this command against an active gateway runtime snapshot before reading it.",
42
- );
43
- this.name = "FeishuSecretRefUnavailableError";
44
- this.path = path;
45
- }
46
- }
47
-
48
- export function isFeishuSecretRefUnavailableError(
49
- error: unknown,
50
- ): error is FeishuSecretRefUnavailableError {
51
- return error instanceof FeishuSecretRefUnavailableError;
52
- }
53
-
54
- function resolveFeishuSecretLike(params: {
55
- value: unknown;
56
- path: string;
57
- mode: FeishuCredentialResolutionMode;
58
- allowEnvSecretRefRead?: boolean;
59
- }): string | undefined {
60
- const asString = normalizeString(params.value);
61
- if (asString) {
62
- return asString;
63
- }
64
-
65
- const ref = coerceSecretRef(params.value);
66
- if (!ref) {
67
- return undefined;
68
- }
69
-
70
- if (params.mode === "inspect") {
71
- if (params.allowEnvSecretRefRead && ref.source === "env") {
72
- const envValue = normalizeString(process.env[ref.id]);
73
- if (envValue) {
74
- return envValue;
75
- }
76
- }
77
- return undefined;
78
- }
79
-
80
- throw new FeishuSecretRefUnavailableError(params.path, ref);
81
- }
82
-
83
- function resolveFeishuBaseCredentials(
84
- cfg: FeishuConfig | undefined,
85
- mode: FeishuCredentialResolutionMode,
86
- ): {
87
- appId: string;
88
- appSecret: string;
89
- domain: FeishuDomain;
90
- } | null {
91
- const appId = resolveFeishuSecretLike({
92
- value: cfg?.appId,
93
- path: "channels.feishu.appId",
94
- mode,
95
- allowEnvSecretRefRead: true,
96
- });
97
- const appSecret = resolveFeishuSecretLike({
98
- value: cfg?.appSecret,
99
- path: "channels.feishu.appSecret",
100
- mode,
101
- allowEnvSecretRefRead: true,
102
- });
103
-
104
- if (!appId || !appSecret) {
105
- return null;
106
- }
107
-
108
- return {
109
- appId,
110
- appSecret,
111
- domain: cfg?.domain ?? "feishu",
112
- };
113
- }
114
-
115
- function resolveFeishuEventSecrets(
116
- cfg: FeishuConfig | undefined,
117
- mode: FeishuCredentialResolutionMode,
118
- ): {
119
- encryptKey?: string;
120
- verificationToken?: string;
121
- } {
122
- return {
123
- encryptKey:
124
- (cfg?.connectionMode ?? "websocket") === "webhook"
125
- ? resolveFeishuSecretLike({
126
- value: cfg?.encryptKey,
127
- path: "channels.feishu.encryptKey",
128
- mode,
129
- allowEnvSecretRefRead: true,
130
- })
131
- : normalizeString(cfg?.encryptKey),
132
- verificationToken: resolveFeishuSecretLike({
133
- value: cfg?.verificationToken,
134
- path: "channels.feishu.verificationToken",
135
- mode,
136
- allowEnvSecretRefRead: true,
137
- }),
138
- };
139
- }
140
-
141
- /**
142
- * Resolve the default account selection and its source.
143
- */
144
- export function resolveDefaultFeishuAccountSelection(cfg: ClawdbotConfig): {
145
- accountId: string;
146
- source: FeishuDefaultAccountSelectionSource;
147
- } {
148
- const preferred = normalizeOptionalAccountId(
149
- (cfg.channels?.feishu as FeishuConfig | undefined)?.defaultAccount,
150
- );
151
- if (preferred) {
152
- return {
153
- accountId: preferred,
154
- source: "explicit-default",
155
- };
156
- }
157
- const ids = listFeishuAccountIds(cfg);
158
- if (ids.includes(DEFAULT_ACCOUNT_ID)) {
159
- return {
160
- accountId: DEFAULT_ACCOUNT_ID,
161
- source: "mapped-default",
162
- };
163
- }
164
- return {
165
- accountId: ids[0] ?? DEFAULT_ACCOUNT_ID,
166
- source: "fallback",
167
- };
168
- }
169
-
170
- /**
171
- * Resolve the default account ID.
172
- */
173
- export function resolveDefaultFeishuAccountId(cfg: ClawdbotConfig): string {
174
- return resolveDefaultAccountId(cfg);
175
- }
176
-
177
- /**
178
- * Merge top-level config with account-specific config.
179
- * Account-specific fields override top-level fields.
180
- */
181
- function mergeFeishuAccountConfig(cfg: ClawdbotConfig, accountId: string): FeishuConfig {
182
- const feishuCfg = cfg.channels?.feishu as FeishuConfig | undefined;
183
- return resolveMergedAccountConfig<FeishuConfig>({
184
- channelConfig: feishuCfg,
185
- accounts: feishuCfg?.accounts as Record<string, Partial<FeishuConfig>> | undefined,
186
- accountId,
187
- omitKeys: ["defaultAccount"],
188
- });
189
- }
190
-
191
- /**
192
- * Resolve Feishu credentials from a config.
193
- */
194
- export function resolveFeishuCredentials(cfg?: FeishuConfig): {
195
- appId: string;
196
- appSecret: string;
197
- encryptKey?: string;
198
- verificationToken?: string;
199
- domain: FeishuDomain;
200
- } | null;
201
- export function resolveFeishuCredentials(
202
- cfg: FeishuConfig | undefined,
203
- options: {
204
- mode?: FeishuCredentialResolutionMode;
205
- allowUnresolvedSecretRef?: boolean;
206
- },
207
- ): {
208
- appId: string;
209
- appSecret: string;
210
- encryptKey?: string;
211
- verificationToken?: string;
212
- domain: FeishuDomain;
213
- } | null;
214
- export function resolveFeishuCredentials(
215
- cfg?: FeishuConfig,
216
- options?: {
217
- mode?: FeishuCredentialResolutionMode;
218
- allowUnresolvedSecretRef?: boolean;
219
- },
220
- ): {
221
- appId: string;
222
- appSecret: string;
223
- encryptKey?: string;
224
- verificationToken?: string;
225
- domain: FeishuDomain;
226
- } | null {
227
- const mode = options?.mode ?? (options?.allowUnresolvedSecretRef ? "inspect" : "strict");
228
- const base = resolveFeishuBaseCredentials(cfg, mode);
229
- if (!base) {
230
- return null;
231
- }
232
- const eventSecrets = resolveFeishuEventSecrets(cfg, mode);
233
-
234
- return {
235
- ...base,
236
- ...eventSecrets,
237
- };
238
- }
239
-
240
- export function inspectFeishuCredentials(cfg?: FeishuConfig) {
241
- return resolveFeishuCredentials(cfg, { mode: "inspect" });
242
- }
243
-
244
- function buildResolvedFeishuAccount(params: {
245
- cfg: ClawdbotConfig;
246
- accountId?: string | null;
247
- baseMode: FeishuCredentialResolutionMode;
248
- eventSecretMode: FeishuCredentialResolutionMode;
249
- }): ResolvedFeishuAccount {
250
- const hasExplicitAccountId =
251
- typeof params.accountId === "string" && params.accountId.trim() !== "";
252
- const defaultSelection = hasExplicitAccountId
253
- ? null
254
- : resolveDefaultFeishuAccountSelection(params.cfg);
255
- const accountId = hasExplicitAccountId
256
- ? normalizeAccountId(params.accountId)
257
- : (defaultSelection?.accountId ?? DEFAULT_ACCOUNT_ID);
258
- const selectionSource = hasExplicitAccountId
259
- ? "explicit"
260
- : (defaultSelection?.source ?? "fallback");
261
- const feishuCfg = params.cfg.channels?.feishu as FeishuConfig | undefined;
262
-
263
- const baseEnabled = feishuCfg?.enabled !== false;
264
- const merged = mergeFeishuAccountConfig(params.cfg, accountId);
265
- const accountEnabled = merged.enabled !== false;
266
- const enabled = baseEnabled && accountEnabled;
267
- const baseCreds = resolveFeishuBaseCredentials(merged, params.baseMode);
268
- const eventSecrets = resolveFeishuEventSecrets(merged, params.eventSecretMode);
269
- const accountName = (merged as FeishuAccountConfig).name;
270
-
271
- return {
272
- accountId,
273
- selectionSource,
274
- enabled,
275
- configured: Boolean(baseCreds),
276
- name: typeof accountName === "string" ? accountName.trim() || undefined : undefined,
277
- appId: baseCreds?.appId,
278
- appSecret: baseCreds?.appSecret,
279
- encryptKey: eventSecrets.encryptKey,
280
- verificationToken: eventSecrets.verificationToken,
281
- domain: baseCreds?.domain ?? "feishu",
282
- config: merged,
283
- };
284
- }
285
-
286
- /**
287
- * Resolve a read-only Feishu account snapshot for CLI/config surfaces.
288
- * Unresolved SecretRefs are treated as unavailable instead of throwing.
289
- */
290
- export function resolveFeishuAccount(params: {
291
- cfg: ClawdbotConfig;
292
- accountId?: string | null;
293
- }): ResolvedFeishuAccount {
294
- return buildResolvedFeishuAccount({
295
- ...params,
296
- baseMode: "inspect",
297
- eventSecretMode: "inspect",
298
- });
299
- }
300
-
301
- /**
302
- * Resolve a runtime Feishu account.
303
- * Required app credentials stay strict; event-only secrets can be required by callers.
304
- */
305
- export function resolveFeishuRuntimeAccount(
306
- params: {
307
- cfg: ClawdbotConfig;
308
- accountId?: string | null;
309
- },
310
- options?: { requireEventSecrets?: boolean },
311
- ): ResolvedFeishuAccount {
312
- return buildResolvedFeishuAccount({
313
- ...params,
314
- baseMode: "strict",
315
- eventSecretMode: options?.requireEventSecrets ? "strict" : "inspect",
316
- });
317
- }
318
-
319
- /**
320
- * List all enabled and configured accounts.
321
- */
322
- export function listEnabledFeishuAccounts(cfg: ClawdbotConfig): ResolvedFeishuAccount[] {
323
- return listFeishuAccountIds(cfg)
324
- .map((accountId) => resolveFeishuAccount({ cfg, accountId }))
325
- .filter((account) => account.enabled && account.configured);
326
- }
@@ -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 openclaw WizardPrompter surface.
7
- */
8
- import { fetchWithSsrFGuard } from "openclaw/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: "ob_user" for user mode, "ob_app" for bot mode. */
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, { small: true });
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
- });
@@ -1,25 +0,0 @@
1
- import {
2
- createResolvedApproverActionAuthAdapter,
3
- resolveApprovalApprovers,
4
- } from "openclaw/plugin-sdk/approval-auth-runtime";
5
- import { normalizeOptionalLowercaseString } from "openclaw/plugin-sdk/text-runtime";
6
- import { resolveFeishuAccount } from "./accounts.js";
7
- import { normalizeFeishuTarget } from "./targets.js";
8
-
9
- function normalizeFeishuApproverId(value: string | number): string | undefined {
10
- const normalized = normalizeFeishuTarget(String(value));
11
- const trimmed = normalizeOptionalLowercaseString(normalized);
12
- return trimmed?.startsWith("ou_") ? trimmed : undefined;
13
- }
14
-
15
- export const feishuApprovalAuth = createResolvedApproverActionAuthAdapter({
16
- channelLabel: "Feishu",
17
- resolveApprovers: ({ cfg, accountId }) => {
18
- const account = resolveFeishuAccount({ cfg, accountId }).config;
19
- return resolveApprovalApprovers({
20
- allowFrom: account.allowFrom,
21
- normalizeApprover: normalizeFeishuApproverId,
22
- });
23
- },
24
- normalizeSenderId: (value) => normalizeFeishuApproverId(value),
25
- });