@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
package/src/docx.test.ts DELETED
@@ -1,701 +0,0 @@
1
- import { mkdirSync, rmSync, writeFileSync } from "node:fs";
2
- import path from "node:path";
3
- import { afterAll, beforeEach, describe, expect, it, vi } from "vitest";
4
- import { createToolFactoryHarness, type ToolLike } from "./tool-factory-test-harness.js";
5
-
6
- const createFeishuClientMock = vi.hoisted(() => vi.fn());
7
- const resolveFeishuToolAccountMock = vi.hoisted(() => vi.fn());
8
- const readRemoteMediaBufferMock = vi.hoisted(() => vi.fn());
9
- const loadWebMediaMock = vi.hoisted(() => vi.fn());
10
- const convertMock = vi.hoisted(() => vi.fn());
11
- const documentCreateMock = vi.hoisted(() => vi.fn());
12
- const blockListMock = vi.hoisted(() => vi.fn());
13
- const blockChildrenCreateMock = vi.hoisted(() => vi.fn());
14
- const blockChildrenGetMock = vi.hoisted(() => vi.fn());
15
- const blockChildrenBatchDeleteMock = vi.hoisted(() => vi.fn());
16
- const blockDescendantCreateMock = vi.hoisted(() => vi.fn());
17
- const driveUploadAllMock = vi.hoisted(() => vi.fn());
18
- const permissionMemberCreateMock = vi.hoisted(() => vi.fn());
19
- const blockPatchMock = vi.hoisted(() => vi.fn());
20
- const scopeListMock = vi.hoisted(() => vi.fn());
21
- const toolAccountModule = await import("./tool-account.js");
22
- const runtimeModule = await import("./runtime.js");
23
-
24
- vi.spyOn(toolAccountModule, "createFeishuToolClient").mockImplementation(() =>
25
- createFeishuClientMock(),
26
- );
27
- vi.spyOn(toolAccountModule, "resolveAnyEnabledFeishuToolsConfig").mockReturnValue({
28
- doc: true,
29
- chat: false,
30
- wiki: false,
31
- drive: false,
32
- perm: false,
33
- scopes: false,
34
- });
35
- vi.spyOn(toolAccountModule, "resolveFeishuToolAccount").mockImplementation((...args) =>
36
- resolveFeishuToolAccountMock(...args),
37
- );
38
- vi.spyOn(runtimeModule, "getFeishuRuntime").mockImplementation(
39
- () =>
40
- ({
41
- channel: {
42
- media: {
43
- readRemoteMediaBuffer: readRemoteMediaBufferMock,
44
- saveMediaBuffer: vi.fn(),
45
- },
46
- },
47
- media: {
48
- loadWebMedia: loadWebMediaMock,
49
- detectMime: vi.fn(async () => "application/octet-stream"),
50
- mediaKindFromMime: vi.fn(() => "image"),
51
- isVoiceCompatibleAudio: vi.fn(() => false),
52
- getImageMetadata: vi.fn(async () => null),
53
- resizeToJpeg: vi.fn(async () => Buffer.alloc(0)),
54
- },
55
- }) as unknown as ReturnType<typeof runtimeModule.getFeishuRuntime>,
56
- );
57
-
58
- const { registerFeishuDocTools } = await import("./docx.js");
59
-
60
- type ToolResultWithDetails = {
61
- details: Record<string, unknown>;
62
- };
63
-
64
- const WORKSPACE_ROOT = path.resolve("/workspace");
65
-
66
- function requireRecord(value: unknown, label: string): Record<string, unknown> {
67
- if (!value || typeof value !== "object") {
68
- throw new Error(`expected ${label}`);
69
- }
70
- return value as Record<string, unknown>;
71
- }
72
-
73
- function callArg(mock: unknown, callIndex: number, argIndex: number, label: string) {
74
- const calls = (mock as { mock?: { calls?: Array<Array<unknown>> } }).mock?.calls ?? [];
75
- const call = calls.at(callIndex);
76
- if (!call) {
77
- throw new Error(`Expected ${label}`);
78
- }
79
- return call[argIndex];
80
- }
81
-
82
- function expectLoadWebMediaCall(fileName: string, localRoots: unknown[] | undefined) {
83
- const source = callArg(loadWebMediaMock, 0, 0, "loadWebMedia source");
84
- const options = requireRecord(
85
- callArg(loadWebMediaMock, 0, 1, "loadWebMedia options"),
86
- "loadWebMedia options",
87
- );
88
- expect(String(source)).toContain(fileName);
89
- expect(options.optimizeImages).toBe(false);
90
- expect(options.localRoots).toEqual(localRoots);
91
- }
92
-
93
- describe("feishu_doc image fetch hardening", () => {
94
- afterAll(() => {
95
- vi.restoreAllMocks();
96
- vi.resetModules();
97
- });
98
-
99
- beforeEach(() => {
100
- vi.clearAllMocks();
101
-
102
- createFeishuClientMock.mockReturnValue({
103
- docx: {
104
- document: {
105
- convert: convertMock,
106
- create: documentCreateMock,
107
- },
108
- documentBlock: {
109
- list: blockListMock,
110
- patch: blockPatchMock,
111
- },
112
- documentBlockChildren: {
113
- create: blockChildrenCreateMock,
114
- get: blockChildrenGetMock,
115
- batchDelete: blockChildrenBatchDeleteMock,
116
- },
117
- documentBlockDescendant: {
118
- create: blockDescendantCreateMock,
119
- },
120
- },
121
- drive: {
122
- media: {
123
- uploadAll: driveUploadAllMock,
124
- },
125
- permissionMember: {
126
- create: permissionMemberCreateMock,
127
- },
128
- },
129
- application: {
130
- scope: {
131
- list: scopeListMock,
132
- },
133
- },
134
- });
135
- resolveFeishuToolAccountMock.mockReturnValue({
136
- config: { mediaMaxMb: 30 },
137
- });
138
-
139
- convertMock.mockResolvedValue({
140
- code: 0,
141
- data: {
142
- blocks: [{ block_type: 27 }],
143
- first_level_block_ids: [],
144
- },
145
- });
146
-
147
- blockListMock.mockResolvedValue({
148
- code: 0,
149
- data: {
150
- items: [],
151
- },
152
- });
153
-
154
- blockChildrenCreateMock.mockResolvedValue({
155
- code: 0,
156
- data: {
157
- children: [{ block_type: 27, block_id: "img_block_1" }],
158
- },
159
- });
160
-
161
- blockChildrenGetMock.mockResolvedValue({
162
- code: 0,
163
- data: { items: [{ block_id: "placeholder_block_1" }] },
164
- });
165
- blockChildrenBatchDeleteMock.mockResolvedValue({ code: 0 });
166
- // write/append use Descendant API; return image block so processImages runs
167
- blockDescendantCreateMock.mockResolvedValue({
168
- code: 0,
169
- data: { children: [{ block_type: 27, block_id: "img_block_1" }] },
170
- });
171
- driveUploadAllMock.mockResolvedValue({ file_token: "token_1" });
172
- documentCreateMock.mockResolvedValue({
173
- code: 0,
174
- data: { document: { document_id: "doc_created", title: "Created Doc" } },
175
- });
176
- permissionMemberCreateMock.mockResolvedValue({ code: 0 });
177
- blockPatchMock.mockResolvedValue({ code: 0 });
178
- scopeListMock.mockResolvedValue({ code: 0, data: { scopes: [] } });
179
- });
180
-
181
- function resolveFeishuDocTool(context: Record<string, unknown> = {}) {
182
- const harness = createToolFactoryHarness({
183
- channels: {
184
- feishu: {
185
- enabled: true,
186
- appId: "app_id",
187
- appSecret: "app_secret",
188
- },
189
- },
190
- });
191
- registerFeishuDocTools(harness.api);
192
- const tool = harness.resolveTool("feishu_doc", context);
193
- if (!tool) {
194
- throw new Error("expected Feishu doc tool");
195
- }
196
- return tool;
197
- }
198
-
199
- async function executeFeishuDocTool(
200
- tool: ToolLike,
201
- params: Record<string, unknown>,
202
- ): Promise<ToolResultWithDetails> {
203
- return (await tool.execute("tool-call", params)) as ToolResultWithDetails;
204
- }
205
-
206
- it("inserts blocks sequentially to preserve document order", async () => {
207
- const blocks = [
208
- { block_type: 3, block_id: "h1" },
209
- { block_type: 2, block_id: "t1" },
210
- { block_type: 3, block_id: "h2" },
211
- ];
212
- convertMock.mockResolvedValue({
213
- code: 0,
214
- data: {
215
- blocks,
216
- first_level_block_ids: ["h1", "t1", "h2"],
217
- },
218
- });
219
-
220
- blockListMock.mockResolvedValue({ code: 0, data: { items: [] } });
221
-
222
- blockDescendantCreateMock.mockResolvedValueOnce({
223
- code: 0,
224
- data: { children: [{ block_type: 3, block_id: "h1" }] },
225
- });
226
-
227
- const feishuDocTool = resolveFeishuDocTool();
228
-
229
- const result = await executeFeishuDocTool(feishuDocTool, {
230
- action: "append",
231
- doc_token: "doc_1",
232
- content: "plain text body",
233
- });
234
-
235
- expect(blockDescendantCreateMock).toHaveBeenCalledTimes(1);
236
- const call = blockDescendantCreateMock.mock.calls[0]?.[0];
237
- expect(call?.data.children_id).toEqual(["h1", "t1", "h2"]);
238
- expect(call?.data.descendants).toEqual(blocks);
239
-
240
- expect(result.details.blocks_added).toBe(3);
241
- });
242
-
243
- it("reorders convert output by document tree instead of raw block array order", async () => {
244
- const blocks = [
245
- { block_type: 13, block_id: "li2", parent_id: "list1" },
246
- { block_type: 4, block_id: "h2" },
247
- { block_type: 13, block_id: "li1", parent_id: "list1" },
248
- { block_type: 3, block_id: "h1" },
249
- { block_type: 12, block_id: "list1", children: ["li1", "li2"] },
250
- { block_type: 2, block_id: "p1" },
251
- ];
252
- convertMock.mockResolvedValue({
253
- code: 0,
254
- data: {
255
- blocks,
256
- first_level_block_ids: ["h1", "p1", "h2", "list1"],
257
- },
258
- });
259
-
260
- blockDescendantCreateMock.mockImplementationOnce(async ({ data }) => ({
261
- code: 0,
262
- data: {
263
- children: (data.children_id as string[]).map((id) => ({ block_id: id })),
264
- },
265
- }));
266
-
267
- const feishuDocTool = resolveFeishuDocTool();
268
-
269
- await feishuDocTool.execute("tool-call", {
270
- action: "append",
271
- doc_token: "doc_1",
272
- content: "tree reorder",
273
- });
274
-
275
- const call = blockDescendantCreateMock.mock.calls[0]?.[0];
276
- expect(call?.data.children_id).toEqual(["h1", "p1", "h2", "list1"]);
277
- expect((call?.data.descendants as Array<{ block_id: string }>).map((b) => b.block_id)).toEqual([
278
- "h1",
279
- "p1",
280
- "h2",
281
- "list1",
282
- "li1",
283
- "li2",
284
- ]);
285
- });
286
-
287
- it("falls back to size-based convert chunking for long no-heading markdown", async () => {
288
- let successChunkCount = 0;
289
- convertMock.mockImplementation(async ({ data }) => {
290
- const content = data.content as string;
291
- if (content.length > 280) {
292
- return { code: 999, msg: "content too large" };
293
- }
294
- successChunkCount++;
295
- const blockId = `b_${successChunkCount}`;
296
- return {
297
- code: 0,
298
- data: {
299
- blocks: [{ block_type: 2, block_id: blockId }],
300
- first_level_block_ids: [blockId],
301
- },
302
- };
303
- });
304
-
305
- blockDescendantCreateMock.mockImplementation(async ({ data }) => ({
306
- code: 0,
307
- data: {
308
- children: (data.children_id as string[]).map((id) => ({
309
- block_id: id,
310
- })),
311
- },
312
- }));
313
-
314
- const feishuDocTool = resolveFeishuDocTool();
315
-
316
- const longMarkdown = Array.from(
317
- { length: 120 },
318
- (_, i) => `line ${i} with enough content to trigger fallback chunking`,
319
- ).join("\n");
320
-
321
- const result = await executeFeishuDocTool(feishuDocTool, {
322
- action: "append",
323
- doc_token: "doc_1",
324
- content: longMarkdown,
325
- });
326
-
327
- expect(convertMock.mock.calls.length).toBeGreaterThan(1);
328
- expect(successChunkCount).toBeGreaterThan(1);
329
- expect(result.details.blocks_added).toBe(successChunkCount);
330
- });
331
-
332
- it("keeps fenced code blocks balanced when size fallback split is needed", async () => {
333
- const convertedChunks: string[] = [];
334
- let successChunkCount = 0;
335
- let failFirstConvert = true;
336
- convertMock.mockImplementation(async ({ data }) => {
337
- const content = data.content as string;
338
- convertedChunks.push(content);
339
- if (failFirstConvert) {
340
- failFirstConvert = false;
341
- return { code: 999, msg: "content too large" };
342
- }
343
- successChunkCount++;
344
- const blockId = `c_${successChunkCount}`;
345
- return {
346
- code: 0,
347
- data: {
348
- blocks: [{ block_type: 2, block_id: blockId }],
349
- first_level_block_ids: [blockId],
350
- },
351
- };
352
- });
353
-
354
- blockChildrenCreateMock.mockImplementation(async ({ data }) => ({
355
- code: 0,
356
- data: { children: data.children },
357
- }));
358
-
359
- const feishuDocTool = resolveFeishuDocTool();
360
-
361
- const fencedMarkdown = [
362
- "## Section",
363
- "```ts",
364
- "const alpha = 1;",
365
- "const beta = 2;",
366
- "const gamma = alpha + beta;",
367
- "console.log(gamma);",
368
- "```",
369
- "",
370
- "Tail paragraph one with enough text to exceed API limits when combined. ".repeat(8),
371
- "Tail paragraph two with enough text to exceed API limits when combined. ".repeat(8),
372
- "Tail paragraph three with enough text to exceed API limits when combined. ".repeat(8),
373
- ].join("\n");
374
-
375
- const result = await executeFeishuDocTool(feishuDocTool, {
376
- action: "append",
377
- doc_token: "doc_1",
378
- content: fencedMarkdown,
379
- });
380
-
381
- expect(convertMock.mock.calls.length).toBeGreaterThan(1);
382
- expect(successChunkCount).toBeGreaterThan(1);
383
- for (const chunk of convertedChunks) {
384
- const fenceCount = chunk.match(/```/g)?.length ?? 0;
385
- expect(fenceCount % 2).toBe(0);
386
- }
387
- expect(result.details.blocks_added).toBe(successChunkCount);
388
- });
389
-
390
- it("skips image upload when markdown image URL is blocked", async () => {
391
- const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
392
- readRemoteMediaBufferMock.mockRejectedValueOnce(
393
- new Error("Blocked: resolves to private/internal IP address"),
394
- );
395
-
396
- const feishuDocTool = resolveFeishuDocTool();
397
-
398
- const result = await executeFeishuDocTool(feishuDocTool, {
399
- action: "write",
400
- doc_token: "doc_1",
401
- content: "![x](https://x.test/image.png)",
402
- });
403
-
404
- expect(readRemoteMediaBufferMock).toHaveBeenCalled();
405
- expect(driveUploadAllMock).not.toHaveBeenCalled();
406
- expect(blockPatchMock).not.toHaveBeenCalled();
407
- expect(result.details.images_processed).toBe(0);
408
- expect(consoleErrorSpy).toHaveBeenCalled();
409
- consoleErrorSpy.mockRestore();
410
- });
411
-
412
- it("create grants permission only to trusted Feishu requester", async () => {
413
- const feishuDocTool = resolveFeishuDocTool({
414
- messageChannel: "feishu",
415
- requesterSenderId: "ou_123",
416
- });
417
-
418
- const result = await executeFeishuDocTool(feishuDocTool, {
419
- action: "create",
420
- title: "Demo",
421
- });
422
-
423
- expect(result.details.document_id).toBe("doc_created");
424
- expect(result.details.requester_permission_added).toBe(true);
425
- expect(result.details.requester_open_id).toBe("ou_123");
426
- expect(result.details.requester_perm_type).toBe("edit");
427
- const permissionPayload = requireRecord(
428
- callArg(permissionMemberCreateMock, 0, 0, "permission create payload"),
429
- "permission create payload",
430
- );
431
- const permissionData = requireRecord(permissionPayload.data, "permission data");
432
- expect(permissionData.member_type).toBe("openid");
433
- expect(permissionData.member_id).toBe("ou_123");
434
- expect(permissionData.perm).toBe("edit");
435
- });
436
-
437
- it("create skips requester grant when trusted requester identity is unavailable", async () => {
438
- const feishuDocTool = resolveFeishuDocTool({
439
- messageChannel: "feishu",
440
- });
441
-
442
- const result = await executeFeishuDocTool(feishuDocTool, {
443
- action: "create",
444
- title: "Demo",
445
- });
446
-
447
- expect(permissionMemberCreateMock).not.toHaveBeenCalled();
448
- expect(result.details.requester_permission_added).toBe(false);
449
- expect(result.details.requester_permission_skipped_reason).toContain("trusted requester");
450
- });
451
-
452
- it("create never grants permissions when grant_to_requester is false", async () => {
453
- const feishuDocTool = resolveFeishuDocTool({
454
- messageChannel: "feishu",
455
- requesterSenderId: "ou_123",
456
- });
457
-
458
- const result = await executeFeishuDocTool(feishuDocTool, {
459
- action: "create",
460
- title: "Demo",
461
- grant_to_requester: false,
462
- });
463
-
464
- expect(permissionMemberCreateMock).not.toHaveBeenCalled();
465
- expect(result.details.requester_permission_added).toBeUndefined();
466
- });
467
-
468
- it("returns an error when create response omits document_id", async () => {
469
- documentCreateMock.mockResolvedValueOnce({
470
- code: 0,
471
- data: { document: { title: "Created Doc" } },
472
- });
473
-
474
- const feishuDocTool = resolveFeishuDocTool();
475
-
476
- const result = await executeFeishuDocTool(feishuDocTool, {
477
- action: "create",
478
- title: "Demo",
479
- });
480
-
481
- expect(result.details.error).toContain("no document_id");
482
- });
483
-
484
- it("uploads local file to doc via upload_file action", async () => {
485
- blockChildrenCreateMock.mockResolvedValueOnce({
486
- code: 0,
487
- data: {
488
- children: [{ block_type: 23, block_id: "file_block_1" }],
489
- },
490
- });
491
-
492
- loadWebMediaMock.mockResolvedValueOnce({
493
- buffer: Buffer.from("hello from local file", "utf8"),
494
- fileName: "test-local.txt",
495
- });
496
-
497
- const feishuDocTool = resolveFeishuDocTool();
498
-
499
- const result = await executeFeishuDocTool(feishuDocTool, {
500
- action: "upload_file",
501
- doc_token: "doc_1",
502
- file_path: "/tmp/allowed/test-local.txt",
503
- filename: "test-local.txt",
504
- });
505
-
506
- expect(result.details.success).toBe(true);
507
- expect(result.details.file_token).toBe("token_1");
508
- expect(result.details.file_name).toBe("test-local.txt");
509
-
510
- // Without workspace-only policy, localRoots stays undefined so loadWebMedia
511
- // applies its default managed-root access behavior.
512
- expectLoadWebMediaCall("test-local.txt", undefined);
513
-
514
- const uploadPayload = requireRecord(
515
- callArg(driveUploadAllMock, 0, 0, "drive upload payload"),
516
- "drive upload payload",
517
- );
518
- const uploadData = requireRecord(uploadPayload.data, "drive upload data");
519
- expect(uploadData.parent_type).toBe("docx_file");
520
- expect(uploadData.parent_node).toBe("doc_1");
521
- expect(uploadData.file_name).toBe("test-local.txt");
522
- });
523
-
524
- it("passes workspace localRoots for upload_file when workspace-only policy is active", async () => {
525
- blockChildrenCreateMock.mockResolvedValueOnce({
526
- code: 0,
527
- data: {
528
- children: [{ block_type: 23, block_id: "file_block_1" }],
529
- },
530
- });
531
-
532
- loadWebMediaMock.mockResolvedValueOnce({
533
- buffer: Buffer.from("hello from local file", "utf8"),
534
- fileName: "test-local.txt",
535
- });
536
-
537
- const feishuDocTool = resolveFeishuDocTool({
538
- workspaceDir: WORKSPACE_ROOT,
539
- fsPolicy: { workspaceOnly: true },
540
- });
541
-
542
- await executeFeishuDocTool(feishuDocTool, {
543
- action: "upload_file",
544
- doc_token: "doc_1",
545
- file_path: "/tmp/klaw-1000/test-local.txt",
546
- filename: "test-local.txt",
547
- });
548
-
549
- expectLoadWebMediaCall("test-local.txt", [WORKSPACE_ROOT]);
550
- });
551
-
552
- it("passes empty localRoots when workspace-only policy is active without workspaceDir", async () => {
553
- blockChildrenCreateMock.mockResolvedValueOnce({
554
- code: 0,
555
- data: {
556
- children: [{ block_type: 23, block_id: "file_block_1" }],
557
- },
558
- });
559
-
560
- loadWebMediaMock.mockResolvedValueOnce({
561
- buffer: Buffer.from("hello from local file", "utf8"),
562
- fileName: "test-local.txt",
563
- });
564
-
565
- const feishuDocTool = resolveFeishuDocTool({
566
- fsPolicy: { workspaceOnly: true },
567
- });
568
-
569
- await executeFeishuDocTool(feishuDocTool, {
570
- action: "upload_file",
571
- doc_token: "doc_1",
572
- file_path: "/tmp/klaw-1000/test-local.txt",
573
- filename: "test-local.txt",
574
- });
575
-
576
- expectLoadWebMediaCall("test-local.txt", []);
577
- });
578
-
579
- it("passes workspace localRoots for upload_image local paths when workspace-only policy is active", async () => {
580
- loadWebMediaMock.mockResolvedValueOnce({
581
- buffer: Buffer.from("hello from local file", "utf8"),
582
- fileName: "test-local.png",
583
- });
584
-
585
- const feishuDocTool = resolveFeishuDocTool({
586
- workspaceDir: WORKSPACE_ROOT,
587
- fsPolicy: { workspaceOnly: true },
588
- });
589
-
590
- await executeFeishuDocTool(feishuDocTool, {
591
- action: "upload_image",
592
- doc_token: "doc_1",
593
- image: "./test-local.png",
594
- filename: "test-local.png",
595
- });
596
-
597
- expectLoadWebMediaCall("test-local.png", [WORKSPACE_ROOT]);
598
- });
599
-
600
- it("passes workspace localRoots for upload_image absolute local paths when workspace-only policy is active", async () => {
601
- const fixtureDir = path.join(process.cwd(), ".tmp-docx-upload-image-absolute");
602
- const absoluteImagePath = path.join(fixtureDir, "absolute-image.png");
603
- mkdirSync(fixtureDir, { recursive: true });
604
- writeFileSync(absoluteImagePath, "not-real-image");
605
-
606
- loadWebMediaMock.mockResolvedValueOnce({
607
- buffer: Buffer.from("hello from local file", "utf8"),
608
- fileName: "absolute-image.png",
609
- });
610
-
611
- const feishuDocTool = resolveFeishuDocTool({
612
- workspaceDir: WORKSPACE_ROOT,
613
- fsPolicy: { workspaceOnly: true },
614
- });
615
-
616
- try {
617
- await executeFeishuDocTool(feishuDocTool, {
618
- action: "upload_image",
619
- doc_token: "doc_1",
620
- image: absoluteImagePath,
621
- filename: "absolute-image.png",
622
- });
623
-
624
- expectLoadWebMediaCall("absolute-image.png", [WORKSPACE_ROOT]);
625
- } finally {
626
- rmSync(fixtureDir, { recursive: true, force: true });
627
- }
628
- });
629
-
630
- it("returns an error when upload_file cannot list placeholder siblings", async () => {
631
- blockChildrenCreateMock.mockResolvedValueOnce({
632
- code: 0,
633
- data: {
634
- children: [{ block_type: 23, block_id: "file_block_1" }],
635
- },
636
- });
637
- blockChildrenGetMock.mockResolvedValueOnce({
638
- code: 999,
639
- msg: "list failed",
640
- data: { items: [] },
641
- });
642
-
643
- loadWebMediaMock.mockResolvedValueOnce({
644
- buffer: Buffer.from("hello from local file", "utf8"),
645
- fileName: "test-local.txt",
646
- });
647
-
648
- const feishuDocTool = resolveFeishuDocTool();
649
-
650
- const result = await executeFeishuDocTool(feishuDocTool, {
651
- action: "upload_file",
652
- doc_token: "doc_1",
653
- file_path: "/tmp/allowed/test-local.txt",
654
- filename: "test-local.txt",
655
- });
656
-
657
- expect(result.details.error).toBe("list failed");
658
- expect(driveUploadAllMock).not.toHaveBeenCalled();
659
- });
660
-
661
- it("rejects traversal paths in upload_file via loadWebMedia sandbox", async () => {
662
- loadWebMediaMock.mockRejectedValueOnce(
663
- new Error("Local media path is not under an allowed directory: /etc/passwd"),
664
- );
665
-
666
- const feishuDocTool = resolveFeishuDocTool();
667
-
668
- const result = await executeFeishuDocTool(feishuDocTool, {
669
- action: "upload_file",
670
- doc_token: "doc_1",
671
- file_path: "/etc/passwd",
672
- });
673
-
674
- expect(result.details.error).toContain("not under an allowed directory");
675
- expect(driveUploadAllMock).not.toHaveBeenCalled();
676
- });
677
-
678
- it("rejects traversal paths in upload_image via loadWebMedia sandbox", async () => {
679
- blockChildrenCreateMock.mockResolvedValueOnce({
680
- code: 0,
681
- data: {
682
- children: [{ block_type: 27, block_id: "img_block_1" }],
683
- },
684
- });
685
-
686
- loadWebMediaMock.mockRejectedValueOnce(
687
- new Error("Local media path is not under an allowed directory: /home/admin/.klaw/klaw.json"),
688
- );
689
-
690
- const feishuDocTool = resolveFeishuDocTool();
691
-
692
- const result = await executeFeishuDocTool(feishuDocTool, {
693
- action: "upload_image",
694
- doc_token: "doc_1",
695
- file_path: "/home/admin/.klaw/klaw.json",
696
- });
697
-
698
- expect(result.details.error).toContain("not under an allowed directory");
699
- expect(driveUploadAllMock).not.toHaveBeenCalled();
700
- });
701
- });