@kodelyth/msteams 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 (177) hide show
  1. package/klaw.plugin.json +726 -2
  2. package/package.json +16 -4
  3. package/api.ts +0 -3
  4. package/channel-config-api.ts +0 -1
  5. package/channel-plugin-api.ts +0 -2
  6. package/config-api.ts +0 -4
  7. package/contract-api.ts +0 -4
  8. package/index.ts +0 -20
  9. package/runtime-api.ts +0 -66
  10. package/secret-contract-api.ts +0 -5
  11. package/setup-entry.ts +0 -13
  12. package/setup-plugin-api.ts +0 -3
  13. package/src/ai-entity.ts +0 -7
  14. package/src/approval-auth.ts +0 -44
  15. package/src/attachments/bot-framework.test.ts +0 -506
  16. package/src/attachments/bot-framework.ts +0 -348
  17. package/src/attachments/download.ts +0 -328
  18. package/src/attachments/graph.test.ts +0 -441
  19. package/src/attachments/graph.ts +0 -489
  20. package/src/attachments/html.ts +0 -122
  21. package/src/attachments/payload.ts +0 -14
  22. package/src/attachments/remote-media.test.ts +0 -187
  23. package/src/attachments/remote-media.ts +0 -86
  24. package/src/attachments/shared.test.ts +0 -547
  25. package/src/attachments/shared.ts +0 -655
  26. package/src/attachments/types.ts +0 -47
  27. package/src/attachments.graph.test.ts +0 -414
  28. package/src/attachments.helpers.test.ts +0 -245
  29. package/src/attachments.test-helpers.ts +0 -17
  30. package/src/attachments.test.ts +0 -754
  31. package/src/attachments.ts +0 -18
  32. package/src/block-streaming-config.test.ts +0 -61
  33. package/src/channel-api.ts +0 -1
  34. package/src/channel.actions.test.ts +0 -797
  35. package/src/channel.directory.test.ts +0 -176
  36. package/src/channel.message-adapter.test.ts +0 -227
  37. package/src/channel.runtime.ts +0 -56
  38. package/src/channel.setup.ts +0 -77
  39. package/src/channel.test.ts +0 -136
  40. package/src/channel.ts +0 -1176
  41. package/src/config-schema.ts +0 -6
  42. package/src/config-ui-hints.ts +0 -40
  43. package/src/conversation-store-fs.test.ts +0 -81
  44. package/src/conversation-store-fs.ts +0 -149
  45. package/src/conversation-store-helpers.test.ts +0 -202
  46. package/src/conversation-store-helpers.ts +0 -105
  47. package/src/conversation-store-memory.ts +0 -51
  48. package/src/conversation-store.shared.test.ts +0 -260
  49. package/src/conversation-store.ts +0 -71
  50. package/src/directory-live.test.ts +0 -156
  51. package/src/directory-live.ts +0 -111
  52. package/src/doctor.ts +0 -27
  53. package/src/errors.test.ts +0 -154
  54. package/src/errors.ts +0 -270
  55. package/src/feedback-reflection-prompt.ts +0 -117
  56. package/src/feedback-reflection-store.ts +0 -113
  57. package/src/feedback-reflection.test.ts +0 -237
  58. package/src/feedback-reflection.ts +0 -268
  59. package/src/file-consent-helpers.test.ts +0 -328
  60. package/src/file-consent-helpers.ts +0 -115
  61. package/src/file-consent-invoke.ts +0 -150
  62. package/src/file-consent.test.ts +0 -378
  63. package/src/file-consent.ts +0 -223
  64. package/src/graph-chat.ts +0 -36
  65. package/src/graph-group-management.test.ts +0 -332
  66. package/src/graph-group-management.ts +0 -168
  67. package/src/graph-members.test.ts +0 -89
  68. package/src/graph-members.ts +0 -48
  69. package/src/graph-messages.actions.test.ts +0 -253
  70. package/src/graph-messages.read.test.ts +0 -391
  71. package/src/graph-messages.search.test.ts +0 -227
  72. package/src/graph-messages.test-helpers.ts +0 -50
  73. package/src/graph-messages.ts +0 -534
  74. package/src/graph-teams.test.ts +0 -222
  75. package/src/graph-teams.ts +0 -114
  76. package/src/graph-thread.test.ts +0 -252
  77. package/src/graph-thread.ts +0 -146
  78. package/src/graph-upload.test.ts +0 -253
  79. package/src/graph-upload.ts +0 -531
  80. package/src/graph-users.ts +0 -29
  81. package/src/graph.test.ts +0 -540
  82. package/src/graph.ts +0 -308
  83. package/src/inbound.test.ts +0 -221
  84. package/src/inbound.ts +0 -148
  85. package/src/index.ts +0 -4
  86. package/src/media-helpers.test.ts +0 -220
  87. package/src/media-helpers.ts +0 -105
  88. package/src/mentions.test.ts +0 -254
  89. package/src/mentions.ts +0 -114
  90. package/src/messenger.test.ts +0 -961
  91. package/src/messenger.ts +0 -608
  92. package/src/monitor-handler/access.ts +0 -136
  93. package/src/monitor-handler/inbound-media.test.ts +0 -314
  94. package/src/monitor-handler/inbound-media.ts +0 -180
  95. package/src/monitor-handler/message-handler-mock-support.test-support.ts +0 -28
  96. package/src/monitor-handler/message-handler.authz.test.ts +0 -739
  97. package/src/monitor-handler/message-handler.dm-media.test.ts +0 -54
  98. package/src/monitor-handler/message-handler.test-support.ts +0 -99
  99. package/src/monitor-handler/message-handler.thread-parent.test.ts +0 -225
  100. package/src/monitor-handler/message-handler.thread-session.test.ts +0 -132
  101. package/src/monitor-handler/message-handler.ts +0 -1003
  102. package/src/monitor-handler/reaction-handler.test.ts +0 -325
  103. package/src/monitor-handler/reaction-handler.ts +0 -122
  104. package/src/monitor-handler/thread-session.ts +0 -30
  105. package/src/monitor-handler.adaptive-card.test.ts +0 -158
  106. package/src/monitor-handler.feedback-authz.test.ts +0 -357
  107. package/src/monitor-handler.file-consent.test.ts +0 -443
  108. package/src/monitor-handler.sso.test.ts +0 -576
  109. package/src/monitor-handler.test-helpers.ts +0 -181
  110. package/src/monitor-handler.ts +0 -538
  111. package/src/monitor-handler.types.ts +0 -27
  112. package/src/monitor-types.ts +0 -6
  113. package/src/monitor.lifecycle.test.ts +0 -457
  114. package/src/monitor.test.ts +0 -119
  115. package/src/monitor.ts +0 -476
  116. package/src/oauth.flow.ts +0 -77
  117. package/src/oauth.shared.ts +0 -37
  118. package/src/oauth.test.ts +0 -350
  119. package/src/oauth.token.ts +0 -162
  120. package/src/oauth.ts +0 -130
  121. package/src/outbound.test.ts +0 -400
  122. package/src/outbound.ts +0 -198
  123. package/src/pending-uploads-fs.test.ts +0 -261
  124. package/src/pending-uploads-fs.ts +0 -235
  125. package/src/pending-uploads.test.ts +0 -186
  126. package/src/pending-uploads.ts +0 -121
  127. package/src/policy.test.ts +0 -156
  128. package/src/policy.ts +0 -245
  129. package/src/polls-store-memory.ts +0 -32
  130. package/src/polls.test.ts +0 -169
  131. package/src/polls.ts +0 -312
  132. package/src/presentation.ts +0 -93
  133. package/src/probe.test.ts +0 -79
  134. package/src/probe.ts +0 -132
  135. package/src/reply-dispatcher.test.ts +0 -543
  136. package/src/reply-dispatcher.ts +0 -523
  137. package/src/reply-stream-controller.test.ts +0 -424
  138. package/src/reply-stream-controller.ts +0 -334
  139. package/src/resolve-allowlist.test.ts +0 -253
  140. package/src/resolve-allowlist.ts +0 -309
  141. package/src/revoked-context.ts +0 -17
  142. package/src/runtime.ts +0 -12
  143. package/src/sdk-types.ts +0 -59
  144. package/src/sdk.test.ts +0 -727
  145. package/src/sdk.ts +0 -916
  146. package/src/secret-contract.ts +0 -49
  147. package/src/secret-input.ts +0 -7
  148. package/src/send-context.test.ts +0 -93
  149. package/src/send-context.ts +0 -269
  150. package/src/send.test.ts +0 -588
  151. package/src/send.ts +0 -697
  152. package/src/sent-message-cache.test.ts +0 -106
  153. package/src/sent-message-cache.ts +0 -174
  154. package/src/session-route.ts +0 -40
  155. package/src/setup-core.ts +0 -162
  156. package/src/setup-surface.test.ts +0 -175
  157. package/src/setup-surface.ts +0 -319
  158. package/src/sso-token-store.test.ts +0 -74
  159. package/src/sso-token-store.ts +0 -166
  160. package/src/sso.ts +0 -300
  161. package/src/storage.ts +0 -25
  162. package/src/store-fs.ts +0 -42
  163. package/src/streaming-message.test.ts +0 -323
  164. package/src/streaming-message.ts +0 -327
  165. package/src/test-runtime.ts +0 -16
  166. package/src/thread-parent-context.test.ts +0 -224
  167. package/src/thread-parent-context.ts +0 -159
  168. package/src/token-response.ts +0 -11
  169. package/src/token.test.ts +0 -268
  170. package/src/token.ts +0 -194
  171. package/src/user-agent.test.ts +0 -121
  172. package/src/user-agent.ts +0 -53
  173. package/src/webhook-timeouts.ts +0 -27
  174. package/src/welcome-card.test.ts +0 -104
  175. package/src/welcome-card.ts +0 -57
  176. package/test-api.ts +0 -1
  177. package/tsconfig.json +0 -16
@@ -1,261 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
5
- import { prepareFileConsentActivityFs } from "./file-consent-helpers.js";
6
- import {
7
- getPendingUploadFs,
8
- removePendingUploadFs,
9
- setPendingUploadActivityIdFs,
10
- storePendingUploadFs,
11
- } from "./pending-uploads-fs.js";
12
- import { clearPendingUploads } from "./pending-uploads.js";
13
- import { setMSTeamsRuntime } from "./runtime.js";
14
- import { msteamsRuntimeStub } from "./test-runtime.js";
15
-
16
- // Track temp dirs created by each test so afterEach can clean them up.
17
- const createdTempDirs: string[] = [];
18
-
19
- async function makeTempStateDir(): Promise<string> {
20
- const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "klaw-msteams-pending-"));
21
- createdTempDirs.push(dir);
22
- return dir;
23
- }
24
-
25
- function makeEnv(stateDir: string): NodeJS.ProcessEnv {
26
- return { ...process.env, KLAW_STATE_DIR: stateDir };
27
- }
28
-
29
- async function requirePendingUpload(id: string, env: NodeJS.ProcessEnv) {
30
- const upload = await getPendingUploadFs(id, { env });
31
- if (!upload) {
32
- throw new Error(`expected pending upload ${id}`);
33
- }
34
- return upload;
35
- }
36
-
37
- async function cleanupTempDirs(): Promise<void> {
38
- while (createdTempDirs.length > 0) {
39
- const dir = createdTempDirs.pop();
40
- if (!dir) {
41
- continue;
42
- }
43
- try {
44
- await fs.promises.rm(dir, { recursive: true, force: true });
45
- } catch {
46
- // tmp dir may already be gone
47
- }
48
- }
49
- }
50
-
51
- describe("msteams pending uploads (fs-backed)", () => {
52
- beforeEach(() => {
53
- setMSTeamsRuntime(msteamsRuntimeStub);
54
- clearPendingUploads();
55
- });
56
-
57
- afterEach(async () => {
58
- await cleanupTempDirs();
59
- vi.useRealTimers();
60
- });
61
-
62
- it("stores and retrieves a pending upload by id", async () => {
63
- const stateDir = await makeTempStateDir();
64
- const env = makeEnv(stateDir);
65
-
66
- await storePendingUploadFs(
67
- {
68
- id: "upload-1",
69
- buffer: Buffer.from("hello world"),
70
- filename: "greeting.txt",
71
- contentType: "text/plain",
72
- conversationId: "19:conv@thread.v2",
73
- },
74
- { env },
75
- );
76
-
77
- const loaded = await requirePendingUpload("upload-1", env);
78
- expect(loaded.id).toBe("upload-1");
79
- expect(loaded.filename).toBe("greeting.txt");
80
- expect(loaded.contentType).toBe("text/plain");
81
- expect(loaded.conversationId).toBe("19:conv@thread.v2");
82
- expect(loaded.buffer.toString("utf8")).toBe("hello world");
83
- });
84
-
85
- it("returns undefined for missing and undefined ids", async () => {
86
- const stateDir = await makeTempStateDir();
87
- const env = makeEnv(stateDir);
88
-
89
- expect(await getPendingUploadFs(undefined, { env })).toBeUndefined();
90
- expect(await getPendingUploadFs("does-not-exist", { env })).toBeUndefined();
91
- });
92
-
93
- it("persists so another reader finds the entry (simulates cross-process)", async () => {
94
- const stateDir = await makeTempStateDir();
95
- const env = makeEnv(stateDir);
96
-
97
- // First "process": writer
98
- await storePendingUploadFs(
99
- {
100
- id: "upload-x",
101
- buffer: Buffer.from("top secret"),
102
- filename: "secret.bin",
103
- conversationId: "19:conv@thread.v2",
104
- },
105
- { env },
106
- );
107
-
108
- // Confirm the backing file actually exists on disk with expected shape
109
- const storePath = path.join(stateDir, "msteams-pending-uploads.json");
110
- const raw = await fs.promises.readFile(storePath, "utf-8");
111
- const parsed = JSON.parse(raw) as {
112
- version: number;
113
- uploads: Record<string, { bufferBase64: string; filename: string }>;
114
- };
115
- expect(parsed.version).toBe(1);
116
- expect(parsed.uploads["upload-x"]?.filename).toBe("secret.bin");
117
- expect(Buffer.from(parsed.uploads["upload-x"].bufferBase64, "base64").toString("utf8")).toBe(
118
- "top secret",
119
- );
120
-
121
- // Second "process": reader using the same state dir
122
- const reader = await getPendingUploadFs("upload-x", { env });
123
- expect(reader?.buffer.toString("utf8")).toBe("top secret");
124
- expect(reader?.filename).toBe("secret.bin");
125
- });
126
-
127
- it("removes persisted entries", async () => {
128
- const stateDir = await makeTempStateDir();
129
- const env = makeEnv(stateDir);
130
-
131
- await storePendingUploadFs(
132
- {
133
- id: "upload-rm",
134
- buffer: Buffer.from("x"),
135
- filename: "rm.bin",
136
- conversationId: "19:conv@thread.v2",
137
- },
138
- { env },
139
- );
140
- const loaded = await requirePendingUpload("upload-rm", env);
141
- expect(loaded.id).toBe("upload-rm");
142
- expect(loaded.filename).toBe("rm.bin");
143
- expect(loaded.contentType).toBeUndefined();
144
- expect(loaded.conversationId).toBe("19:conv@thread.v2");
145
- expect(loaded.consentCardActivityId).toBeUndefined();
146
- expect(loaded.buffer.toString("utf8")).toBe("x");
147
- expect(Number.isFinite(loaded.createdAt)).toBe(true);
148
-
149
- await removePendingUploadFs("upload-rm", { env });
150
- expect(await getPendingUploadFs("upload-rm", { env })).toBeUndefined();
151
- });
152
-
153
- it("remove is a no-op for unknown ids", async () => {
154
- const stateDir = await makeTempStateDir();
155
- const env = makeEnv(stateDir);
156
-
157
- await expect(removePendingUploadFs("never-existed", { env })).resolves.toBeUndefined();
158
- await expect(removePendingUploadFs(undefined, { env })).resolves.toBeUndefined();
159
- });
160
-
161
- it("expires entries past their ttl on read", async () => {
162
- const stateDir = await makeTempStateDir();
163
- const env = makeEnv(stateDir);
164
- const now = new Date("2026-05-08T00:00:00.000Z");
165
- vi.useFakeTimers({ now });
166
-
167
- await storePendingUploadFs(
168
- {
169
- id: "upload-old",
170
- buffer: Buffer.from("stale"),
171
- filename: "stale.txt",
172
- conversationId: "19:conv@thread.v2",
173
- },
174
- { env, ttlMs: 1 },
175
- );
176
- vi.setSystemTime(now.getTime() + 2);
177
- expect(await getPendingUploadFs("upload-old", { env, ttlMs: 1 })).toBeUndefined();
178
- });
179
-
180
- it("updates consent card activity id on an existing entry", async () => {
181
- const stateDir = await makeTempStateDir();
182
- const env = makeEnv(stateDir);
183
-
184
- await storePendingUploadFs(
185
- {
186
- id: "upload-a",
187
- buffer: Buffer.from("payload"),
188
- filename: "f.txt",
189
- conversationId: "19:conv@thread.v2",
190
- },
191
- { env },
192
- );
193
-
194
- await setPendingUploadActivityIdFs("upload-a", "activity-xyz", { env });
195
- const loaded = await getPendingUploadFs("upload-a", { env });
196
- expect(loaded?.consentCardActivityId).toBe("activity-xyz");
197
- });
198
-
199
- it("ignores malformed or empty store files and returns undefined", async () => {
200
- const stateDir = await makeTempStateDir();
201
- const env = makeEnv(stateDir);
202
- const storePath = path.join(stateDir, "msteams-pending-uploads.json");
203
- await fs.promises.writeFile(storePath, "not valid json", "utf-8");
204
-
205
- // Should not throw and should treat as empty
206
- expect(await getPendingUploadFs("anything", { env })).toBeUndefined();
207
-
208
- await fs.promises.writeFile(storePath, JSON.stringify({ version: 2, uploads: {} }), "utf-8");
209
- expect(await getPendingUploadFs("anything", { env })).toBeUndefined();
210
- });
211
- });
212
-
213
- describe("prepareFileConsentActivityFs end-to-end", () => {
214
- beforeEach(() => {
215
- setMSTeamsRuntime(msteamsRuntimeStub);
216
- clearPendingUploads();
217
- });
218
-
219
- afterEach(async () => {
220
- await cleanupTempDirs();
221
- });
222
-
223
- it("writes the pending upload to the fs store with the same id as the card", async () => {
224
- const stateDir = await makeTempStateDir();
225
- const env = makeEnv(stateDir);
226
- // Redirect state dir via env so the helper's FS writes land under our tmp
227
- const originalEnv = process.env.KLAW_STATE_DIR;
228
- process.env.KLAW_STATE_DIR = stateDir;
229
-
230
- try {
231
- const result = await prepareFileConsentActivityFs({
232
- media: {
233
- buffer: Buffer.from("cli file"),
234
- filename: "cli.bin",
235
- contentType: "application/octet-stream",
236
- },
237
- conversationId: "19:victim@thread.v2",
238
- description: "Sent via CLI",
239
- });
240
-
241
- expect(result.uploadId).toMatch(/[0-9a-f-]/);
242
- const attachments = result.activity.attachments as Array<Record<string, unknown>>;
243
- expect(attachments).toHaveLength(1);
244
- const content = attachments[0]?.content as { acceptContext: { uploadId: string } };
245
- expect(content.acceptContext.uploadId).toBe(result.uploadId);
246
-
247
- // Reader in (simulated) other process finds the entry under the same key
248
- const loaded = await requirePendingUpload(result.uploadId, env);
249
- expect(loaded.filename).toBe("cli.bin");
250
- expect(loaded.contentType).toBe("application/octet-stream");
251
- expect(loaded.conversationId).toBe("19:victim@thread.v2");
252
- expect(loaded.buffer.toString("utf8")).toBe("cli file");
253
- } finally {
254
- if (originalEnv === undefined) {
255
- delete process.env.KLAW_STATE_DIR;
256
- } else {
257
- process.env.KLAW_STATE_DIR = originalEnv;
258
- }
259
- }
260
- });
261
- });
@@ -1,235 +0,0 @@
1
- /**
2
- * Filesystem-backed pending upload store for the FileConsentCard flow.
3
- *
4
- * The CLI `message send --media` path runs in a different process from the
5
- * gateway's bot monitor that receives the `fileConsent/invoke` callback.
6
- * An in-memory `pending-uploads.ts` store cannot bridge those processes, so
7
- * when the user clicks "Allow" the monitor handler's lookup misses and the
8
- * user sees "card action not supported".
9
- *
10
- * This FS store persists pending uploads to a JSON file (with the file buffer
11
- * base64-encoded) so any process that shares the Klaw state dir can read
12
- * them back. The in-memory store in `pending-uploads.ts` is still the fast
13
- * path for same-process flows (for example the messenger reply path); this FS
14
- * store is a cross-process fallback.
15
- */
16
-
17
- import { resolveMSTeamsStorePath } from "./storage.js";
18
- import { readJsonFile, withFileLock, writeJsonFile } from "./store-fs.js";
19
-
20
- /** TTL for persisted pending uploads (matches in-memory store). */
21
- const PENDING_UPLOAD_TTL_MS = 5 * 60 * 1000;
22
-
23
- /** Cap to avoid unbounded growth if a process crashes mid-flow. */
24
- const MAX_PENDING_UPLOADS = 100;
25
-
26
- const STORE_FILENAME = "msteams-pending-uploads.json";
27
-
28
- type PendingUploadFsRecord = {
29
- id: string;
30
- bufferBase64: string;
31
- filename: string;
32
- contentType?: string;
33
- conversationId: string;
34
- /** Activity ID of the original FileConsentCard, used to replace it after upload */
35
- consentCardActivityId?: string;
36
- createdAt: number;
37
- };
38
-
39
- type PendingUploadFs = {
40
- id: string;
41
- buffer: Buffer;
42
- filename: string;
43
- contentType?: string;
44
- conversationId: string;
45
- consentCardActivityId?: string;
46
- createdAt: number;
47
- };
48
-
49
- type PendingUploadStoreData = {
50
- version: 1;
51
- uploads: Record<string, PendingUploadFsRecord>;
52
- };
53
-
54
- const empty: PendingUploadStoreData = { version: 1, uploads: {} };
55
-
56
- type PendingUploadsFsOptions = {
57
- env?: NodeJS.ProcessEnv;
58
- homedir?: () => string;
59
- stateDir?: string;
60
- storePath?: string;
61
- ttlMs?: number;
62
- };
63
-
64
- function resolveFilePath(options: PendingUploadsFsOptions | undefined): string {
65
- return resolveMSTeamsStorePath({
66
- filename: STORE_FILENAME,
67
- env: options?.env,
68
- homedir: options?.homedir,
69
- stateDir: options?.stateDir,
70
- storePath: options?.storePath,
71
- });
72
- }
73
-
74
- function pruneExpired(
75
- uploads: Record<string, PendingUploadFsRecord>,
76
- nowMs: number,
77
- ttlMs: number,
78
- ): Record<string, PendingUploadFsRecord> {
79
- const kept: Record<string, PendingUploadFsRecord> = {};
80
- for (const [id, record] of Object.entries(uploads)) {
81
- if (nowMs - record.createdAt <= ttlMs) {
82
- kept[id] = record;
83
- }
84
- }
85
- return kept;
86
- }
87
-
88
- function pruneToLimit(
89
- uploads: Record<string, PendingUploadFsRecord>,
90
- ): Record<string, PendingUploadFsRecord> {
91
- const entries = Object.entries(uploads);
92
- if (entries.length <= MAX_PENDING_UPLOADS) {
93
- return uploads;
94
- }
95
- // Oldest createdAt first; drop the oldest until we fit.
96
- entries.sort((a, b) => a[1].createdAt - b[1].createdAt);
97
- const keep = entries.slice(entries.length - MAX_PENDING_UPLOADS);
98
- return Object.fromEntries(keep);
99
- }
100
-
101
- function recordToUpload(record: PendingUploadFsRecord): PendingUploadFs {
102
- return {
103
- id: record.id,
104
- buffer: Buffer.from(record.bufferBase64, "base64"),
105
- filename: record.filename,
106
- contentType: record.contentType,
107
- conversationId: record.conversationId,
108
- consentCardActivityId: record.consentCardActivityId,
109
- createdAt: record.createdAt,
110
- };
111
- }
112
-
113
- function isValidStore(value: unknown): value is PendingUploadStoreData {
114
- if (!value || typeof value !== "object") {
115
- return false;
116
- }
117
- const candidate = value as Partial<PendingUploadStoreData>;
118
- return (
119
- candidate.version === 1 &&
120
- typeof candidate.uploads === "object" &&
121
- candidate.uploads !== null &&
122
- !Array.isArray(candidate.uploads)
123
- );
124
- }
125
-
126
- async function readStore(filePath: string, ttlMs: number): Promise<PendingUploadStoreData> {
127
- const { value } = await readJsonFile<unknown>(filePath, empty);
128
- if (!isValidStore(value)) {
129
- return { version: 1, uploads: {} };
130
- }
131
- const uploads = pruneToLimit(pruneExpired(value.uploads, Date.now(), ttlMs));
132
- return { version: 1, uploads };
133
- }
134
-
135
- /**
136
- * Persist a pending upload record so another process can read it back.
137
- * Pass in the pre-generated id (same as the one placed in the consent card
138
- * context) so the in-memory and FS stores share the same key.
139
- */
140
- export async function storePendingUploadFs(
141
- upload: {
142
- id: string;
143
- buffer: Buffer;
144
- filename: string;
145
- contentType?: string;
146
- conversationId: string;
147
- consentCardActivityId?: string;
148
- },
149
- options?: PendingUploadsFsOptions,
150
- ): Promise<void> {
151
- const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS;
152
- const filePath = resolveFilePath(options);
153
- await withFileLock(filePath, empty, async () => {
154
- const store = await readStore(filePath, ttlMs);
155
- store.uploads[upload.id] = {
156
- id: upload.id,
157
- bufferBase64: upload.buffer.toString("base64"),
158
- filename: upload.filename,
159
- contentType: upload.contentType,
160
- conversationId: upload.conversationId,
161
- consentCardActivityId: upload.consentCardActivityId,
162
- createdAt: Date.now(),
163
- };
164
- store.uploads = pruneToLimit(pruneExpired(store.uploads, Date.now(), ttlMs));
165
- await writeJsonFile(filePath, store);
166
- });
167
- }
168
-
169
- /**
170
- * Retrieve a persisted pending upload. Expired entries are treated as absent.
171
- */
172
- export async function getPendingUploadFs(
173
- id: string | undefined,
174
- options?: PendingUploadsFsOptions,
175
- ): Promise<PendingUploadFs | undefined> {
176
- if (!id) {
177
- return undefined;
178
- }
179
- const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS;
180
- const filePath = resolveFilePath(options);
181
- const store = await readStore(filePath, ttlMs);
182
- const record = store.uploads[id];
183
- if (!record) {
184
- return undefined;
185
- }
186
- if (Date.now() - record.createdAt > ttlMs) {
187
- return undefined;
188
- }
189
- return recordToUpload(record);
190
- }
191
-
192
- /**
193
- * Remove a persisted pending upload (after successful upload or decline).
194
- * No-op if the entry is already gone.
195
- */
196
- export async function removePendingUploadFs(
197
- id: string | undefined,
198
- options?: PendingUploadsFsOptions,
199
- ): Promise<void> {
200
- if (!id) {
201
- return;
202
- }
203
- const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS;
204
- const filePath = resolveFilePath(options);
205
- await withFileLock(filePath, empty, async () => {
206
- const store = await readStore(filePath, ttlMs);
207
- if (!(id in store.uploads)) {
208
- return;
209
- }
210
- delete store.uploads[id];
211
- await writeJsonFile(filePath, store);
212
- });
213
- }
214
-
215
- /**
216
- * Set the consent card activity ID on a persisted entry. Called after the
217
- * FileConsentCard activity is sent and we know its message id.
218
- */
219
- export async function setPendingUploadActivityIdFs(
220
- id: string,
221
- activityId: string,
222
- options?: PendingUploadsFsOptions,
223
- ): Promise<void> {
224
- const ttlMs = options?.ttlMs ?? PENDING_UPLOAD_TTL_MS;
225
- const filePath = resolveFilePath(options);
226
- await withFileLock(filePath, empty, async () => {
227
- const store = await readStore(filePath, ttlMs);
228
- const record = store.uploads[id];
229
- if (!record) {
230
- return;
231
- }
232
- record.consentCardActivityId = activityId;
233
- await writeJsonFile(filePath, store);
234
- });
235
- }
@@ -1,186 +0,0 @@
1
- import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
2
- import {
3
- clearPendingUploads,
4
- getPendingUpload,
5
- getPendingUploadCount,
6
- removePendingUpload,
7
- setPendingUploadActivityId,
8
- storePendingUpload,
9
- } from "./pending-uploads.js";
10
-
11
- function requirePendingUpload(id: string) {
12
- const upload = getPendingUpload(id);
13
- if (!upload) {
14
- throw new Error(`expected pending upload ${id}`);
15
- }
16
- return upload;
17
- }
18
-
19
- describe("pending-uploads", () => {
20
- beforeEach(() => {
21
- vi.useFakeTimers();
22
- clearPendingUploads();
23
- });
24
-
25
- afterEach(() => {
26
- clearPendingUploads();
27
- vi.useRealTimers();
28
- });
29
-
30
- describe("storePendingUpload", () => {
31
- it("stores and retrieves a pending upload", () => {
32
- const id = storePendingUpload({
33
- buffer: Buffer.from("data"),
34
- filename: "file.txt",
35
- contentType: "text/plain",
36
- conversationId: "conv-1",
37
- });
38
-
39
- const upload = requirePendingUpload(id);
40
- expect(upload.id).toBe(id);
41
- expect(upload.buffer.toString()).toBe("data");
42
- expect(upload.filename).toBe("file.txt");
43
- expect(upload.contentType).toBe("text/plain");
44
- expect(upload.conversationId).toBe("conv-1");
45
- expect(upload.createdAt).toBe(Date.now());
46
- });
47
-
48
- it("stores consentCardActivityId when provided", () => {
49
- const id = storePendingUpload({
50
- buffer: Buffer.from("data"),
51
- filename: "file.txt",
52
- conversationId: "conv-1",
53
- consentCardActivityId: "activity-abc",
54
- });
55
-
56
- const upload = getPendingUpload(id);
57
- expect(upload?.consentCardActivityId).toBe("activity-abc");
58
- });
59
-
60
- it("stores without consentCardActivityId when not provided", () => {
61
- const id = storePendingUpload({
62
- buffer: Buffer.from("data"),
63
- filename: "file.txt",
64
- conversationId: "conv-1",
65
- });
66
-
67
- const upload = getPendingUpload(id);
68
- expect(upload?.consentCardActivityId).toBeUndefined();
69
- });
70
-
71
- it("auto-removes entry after TTL expires", () => {
72
- const id = storePendingUpload({
73
- buffer: Buffer.from("data"),
74
- filename: "file.txt",
75
- conversationId: "conv-1",
76
- });
77
-
78
- expect(requirePendingUpload(id).filename).toBe("file.txt");
79
- vi.advanceTimersByTime(5 * 60 * 1000 + 1);
80
- // After TTL the in-memory check also gates access
81
- expect(getPendingUpload(id)).toBeUndefined();
82
- });
83
- });
84
-
85
- describe("removePendingUpload", () => {
86
- it("removes the entry immediately", () => {
87
- const id = storePendingUpload({
88
- buffer: Buffer.from("data"),
89
- filename: "file.txt",
90
- conversationId: "conv-1",
91
- });
92
-
93
- removePendingUpload(id);
94
- expect(getPendingUpload(id)).toBeUndefined();
95
- });
96
-
97
- it("clears the TTL timer so it does not fire after explicit removal", () => {
98
- const id = storePendingUpload({
99
- buffer: Buffer.from("data"),
100
- filename: "file.txt",
101
- conversationId: "conv-1",
102
- });
103
-
104
- expect(getPendingUploadCount()).toBe(1);
105
- removePendingUpload(id);
106
- expect(getPendingUploadCount()).toBe(0);
107
-
108
- // Advance past TTL — timer should have been cleared and count stays 0
109
- vi.advanceTimersByTime(5 * 60 * 1000 + 1);
110
- expect(getPendingUploadCount()).toBe(0);
111
- });
112
-
113
- it("leaves existing uploads untouched for undefined id", () => {
114
- storePendingUpload({
115
- buffer: Buffer.from("data"),
116
- filename: "file.txt",
117
- conversationId: "conv-1",
118
- });
119
-
120
- removePendingUpload(undefined);
121
- expect(getPendingUploadCount()).toBe(1);
122
- });
123
-
124
- it("leaves the store empty for unknown ids", () => {
125
- removePendingUpload("non-existent-id");
126
- expect(getPendingUploadCount()).toBe(0);
127
- });
128
- });
129
-
130
- describe("clearPendingUploads", () => {
131
- it("removes all entries and cancels timers", () => {
132
- storePendingUpload({ buffer: Buffer.from("a"), filename: "a.txt", conversationId: "c1" });
133
- storePendingUpload({ buffer: Buffer.from("b"), filename: "b.txt", conversationId: "c2" });
134
- expect(getPendingUploadCount()).toBe(2);
135
-
136
- clearPendingUploads();
137
- expect(getPendingUploadCount()).toBe(0);
138
-
139
- // TTL timers should have been cleared — no side-effects after advance
140
- vi.advanceTimersByTime(5 * 60 * 1000 + 1);
141
- expect(getPendingUploadCount()).toBe(0);
142
- });
143
- });
144
-
145
- describe("setPendingUploadActivityId", () => {
146
- it("sets the consentCardActivityId on an existing upload", () => {
147
- const id = storePendingUpload({
148
- buffer: Buffer.from("data"),
149
- filename: "file.txt",
150
- conversationId: "conv-1",
151
- });
152
-
153
- expect(getPendingUpload(id)?.consentCardActivityId).toBeUndefined();
154
-
155
- setPendingUploadActivityId(id, "activity-xyz");
156
- expect(getPendingUpload(id)?.consentCardActivityId).toBe("activity-xyz");
157
- });
158
-
159
- it("leaves the store empty for unknown upload ids", () => {
160
- setPendingUploadActivityId("non-existent", "activity-xyz");
161
- expect(getPendingUploadCount()).toBe(0);
162
- });
163
- });
164
-
165
- describe("getPendingUpload", () => {
166
- it("returns undefined for undefined id", () => {
167
- expect(getPendingUpload(undefined)).toBeUndefined();
168
- });
169
-
170
- it("returns undefined for unknown id", () => {
171
- expect(getPendingUpload("no-such-id")).toBeUndefined();
172
- });
173
-
174
- it("returns undefined when entry is past TTL but timer has not yet fired", () => {
175
- const id = storePendingUpload({
176
- buffer: Buffer.from("data"),
177
- filename: "file.txt",
178
- conversationId: "conv-1",
179
- });
180
-
181
- // Manually advance time without firing timers to simulate stale entry
182
- vi.setSystemTime(Date.now() + 5 * 60 * 1000 + 1);
183
- expect(getPendingUpload(id)).toBeUndefined();
184
- });
185
- });
186
- });