@exulu/backend 5.11.1 → 5.13.0

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.
@@ -0,0 +1,389 @@
1
+ import { mkdtemp, mkdir, writeFile, readFile, readdir, rm, symlink, lstat, utimes } from "node:fs/promises";
2
+ import { existsSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+
6
+ jest.mock("@SRC/uppy/index.ts", () => ({
7
+ listS3ObjectsByPrefix: jest.fn(),
8
+ getS3ObjectBytes: jest.fn(),
9
+ }));
10
+
11
+ import { listS3ObjectsByPrefix, getS3ObjectBytes } from "@SRC/uppy/index.ts";
12
+ import {
13
+ planProjectSync,
14
+ syncProjectDir,
15
+ projectSyncMarkerPath,
16
+ resolveSandboxProjectId,
17
+ removeTreeSafely,
18
+ } from "./project-sync";
19
+
20
+ const list = listS3ObjectsByPrefix as jest.Mock;
21
+ const bytes = getS3ObjectBytes as jest.Mock;
22
+ const config = { fileUploads: { s3Bucket: "b", s3prefix: "pre" } } as any;
23
+
24
+ describe("planProjectSync", () => {
25
+ it("downloads new and size-changed files, removes files gone remotely, leaves identical ones alone", () => {
26
+ const plan = planProjectSync(
27
+ [
28
+ { name: "same.pdf", size: 10 },
29
+ { name: "changed.pdf", size: 20 },
30
+ { name: "new.pdf", size: 5 },
31
+ ],
32
+ [
33
+ { name: "same.pdf", size: 10 },
34
+ { name: "changed.pdf", size: 19 },
35
+ { name: "gone.pdf", size: 7 },
36
+ ],
37
+ );
38
+ expect(plan.download.sort()).toEqual(["changed.pdf", "new.pdf"]);
39
+ expect(plan.remove).toEqual(["gone.pdf"]);
40
+ });
41
+
42
+ it("is a no-op when both sides match", () => {
43
+ expect(planProjectSync([{ name: "a", size: 1 }], [{ name: "a", size: 1 }])).toEqual({ download: [], remove: [] });
44
+ });
45
+ });
46
+
47
+ describe("syncProjectDir", () => {
48
+ let root: string;
49
+ let sessionDir: string;
50
+
51
+ beforeEach(async () => {
52
+ root = await mkdtemp(join(tmpdir(), "project-sync-"));
53
+ sessionDir = join(root, "sess-1");
54
+ await mkdir(sessionDir, { recursive: true });
55
+ list.mockReset();
56
+ bytes.mockReset();
57
+ });
58
+ afterEach(async () => {
59
+ await rm(root, { recursive: true, force: true });
60
+ });
61
+
62
+ const remoteObj = (name: string, size: number) => ({
63
+ key: `pre/projects/p1/files/${name}`,
64
+ size,
65
+ lastModified: new Date(),
66
+ });
67
+
68
+ it("projectId null removes a project/ dir this sync created earlier", async () => {
69
+ list.mockResolvedValue([remoteObj("a.pdf", 3)]);
70
+ bytes.mockResolvedValue(Buffer.from("abc"));
71
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
72
+ expect(existsSync(join(sessionDir, "project", "a.pdf"))).toBe(true);
73
+
74
+ await syncProjectDir({ sessionDir, projectId: null, config });
75
+ expect(existsSync(join(sessionDir, "project"))).toBe(false);
76
+ expect(existsSync(projectSyncMarkerPath(sessionDir))).toBe(false);
77
+ });
78
+
79
+ it("projectId null leaves a project/ dir alone that never came from a project (session without project)", async () => {
80
+ await mkdir(join(sessionDir, "project"), { recursive: true });
81
+ await writeFile(join(sessionDir, "project", "x.txt"), "agent file");
82
+ await syncProjectDir({ sessionDir, projectId: null, config });
83
+ expect(await readFile(join(sessionDir, "project", "x.txt"), "utf8")).toBe("agent file");
84
+ expect(list).not.toHaveBeenCalled();
85
+ });
86
+
87
+ it("downloads remote files, removes local ones gone remotely, keeps identical ones", async () => {
88
+ const dir = join(sessionDir, "project");
89
+ // An earlier sync of the same project left same.txt (marker + folder).
90
+ list.mockResolvedValue([remoteObj("same.txt", 3)]);
91
+ bytes.mockResolvedValue(Buffer.from("123"));
92
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
93
+ bytes.mockReset();
94
+ await writeFile(join(dir, "gone.txt"), "x");
95
+ await mkdir(join(dir, "agent-subdir"));
96
+ list.mockResolvedValue([remoteObj("same.txt", 3), remoteObj("new.txt", 2)]);
97
+ bytes.mockImplementation(async (key: string) => Buffer.from(key.endsWith("new.txt") ? "hi" : "ZZZ"));
98
+
99
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
100
+
101
+ expect(list).toHaveBeenCalledWith("projects/p1/files/", config);
102
+ expect((await readdir(dir)).sort()).toEqual(["new.txt", "same.txt"]);
103
+ expect(await readFile(join(dir, "same.txt"), "utf8")).toBe("123"); // not re-downloaded
104
+ expect(await readFile(join(dir, "new.txt"), "utf8")).toBe("hi");
105
+ expect(bytes).toHaveBeenCalledTimes(1);
106
+ });
107
+
108
+ it("one failing download does not abort the others", async () => {
109
+ list.mockResolvedValue([remoteObj("bad.txt", 1), remoteObj("good.txt", 2)]);
110
+ bytes.mockImplementation(async (key: string) => {
111
+ if (key.endsWith("bad.txt")) throw new Error("boom");
112
+ return Buffer.from("ok");
113
+ });
114
+ const err = jest.spyOn(console, "error").mockImplementation(() => {});
115
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
116
+ err.mockRestore();
117
+ expect(await readFile(join(sessionDir, "project", "good.txt"), "utf8")).toBe("ok");
118
+ expect(existsSync(join(sessionDir, "project", "bad.txt"))).toBe(false);
119
+ });
120
+
121
+ it("a failing listing keeps the local copy as it is", async () => {
122
+ await mkdir(join(sessionDir, "project"), { recursive: true });
123
+ await writeFile(join(sessionDir, "project", "a.txt"), "a");
124
+ list.mockRejectedValue(new Error("s3 down"));
125
+ const err = jest.spyOn(console, "error").mockImplementation(() => {});
126
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
127
+ err.mockRestore();
128
+ expect(existsSync(join(sessionDir, "project", "a.txt"))).toBe(true);
129
+ });
130
+
131
+ it("switching to another project starts from an empty folder", async () => {
132
+ list.mockResolvedValueOnce([remoteObj("a.txt", 1)]);
133
+ bytes.mockResolvedValue(Buffer.from("A"));
134
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
135
+
136
+ list.mockResolvedValueOnce([{ key: "pre/projects/p2/files/a.txt", size: 1, lastModified: new Date() }]);
137
+ bytes.mockResolvedValue(Buffer.from("B"));
138
+ await syncProjectDir({ sessionDir, projectId: "p2", config });
139
+ // same name and size, but a different project: must not keep p1's bytes
140
+ expect(await readFile(join(sessionDir, "project", "a.txt"), "utf8")).toBe("B");
141
+ });
142
+
143
+ it("ignores remote keys that are not flat file names", async () => {
144
+ list.mockResolvedValue([
145
+ { key: "pre/projects/p1/files/", size: 0, lastModified: new Date() },
146
+ { key: "pre/projects/p1/files/sub/x.txt", size: 1, lastModified: new Date() },
147
+ remoteObj("ok.txt", 1),
148
+ ]);
149
+ bytes.mockResolvedValue(Buffer.from("k"));
150
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
151
+ expect(await readdir(join(sessionDir, "project"))).toEqual(["ok.txt"]);
152
+ });
153
+
154
+ it("a project symlink is replaced by a real directory and its target is left untouched", async () => {
155
+ const victim = join(root, "victim");
156
+ await mkdir(join(victim, "sub"), { recursive: true });
157
+ await writeFile(join(victim, "keep.txt"), "victim");
158
+ await writeFile(join(victim, "sub", "deep.txt"), "deep");
159
+ // a first sync writes the marker, so the next one is the "marker matches" case
160
+ list.mockResolvedValue([remoteObj("a.txt", 1)]);
161
+ bytes.mockResolvedValue(Buffer.from("A"));
162
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
163
+ await rm(join(sessionDir, "project"), { recursive: true, force: true });
164
+ await symlink(victim, join(sessionDir, "project"));
165
+
166
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
167
+
168
+ expect(await readFile(join(victim, "keep.txt"), "utf8")).toBe("victim");
169
+ expect(await readFile(join(victim, "sub", "deep.txt"), "utf8")).toBe("deep");
170
+ expect((await readdir(victim)).sort()).toEqual(["keep.txt", "sub"]);
171
+ const st = await lstat(join(sessionDir, "project"));
172
+ expect(st.isSymbolicLink()).toBe(false);
173
+ expect(st.isDirectory()).toBe(true);
174
+ expect(await readFile(join(sessionDir, "project", "a.txt"), "utf8")).toBe("A");
175
+ });
176
+
177
+ it("a regular file named project is replaced by the directory", async () => {
178
+ await writeFile(join(sessionDir, "project"), "not a dir");
179
+ list.mockResolvedValue([remoteObj("a.txt", 1)]);
180
+ bytes.mockResolvedValue(Buffer.from("A"));
181
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
182
+ expect((await lstat(join(sessionDir, "project"))).isDirectory()).toBe(true);
183
+ expect(await readFile(join(sessionDir, "project", "a.txt"), "utf8")).toBe("A");
184
+ });
185
+
186
+ it("a symlink planted at a download name after the scan is not written through", async () => {
187
+ const victim = join(root, "victim.txt");
188
+ await writeFile(victim, "victim");
189
+ list.mockResolvedValue([remoteObj("a.txt", 1)]);
190
+ // Plant the link while the bytes are being fetched, i.e. after readdir/plan.
191
+ bytes.mockImplementation(async () => {
192
+ await mkdir(join(sessionDir, "project"), { recursive: true });
193
+ await symlink(victim, join(sessionDir, "project", "a.txt"));
194
+ return Buffer.from("A");
195
+ });
196
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
197
+ expect(await readFile(victim, "utf8")).toBe("victim");
198
+ expect((await lstat(join(sessionDir, "project", "a.txt"))).isSymbolicLink()).toBe(false);
199
+ expect(await readFile(join(sessionDir, "project", "a.txt"), "utf8")).toBe("A");
200
+ expect((await readdir(join(sessionDir, "project"))).sort()).toEqual(["a.txt"]);
201
+ });
202
+
203
+ const snapshotTree = async (d: string): Promise<string[]> => {
204
+ const out: string[] = [];
205
+ const walk = async (x: string, rel: string) => {
206
+ for (const e of await readdir(x, { withFileTypes: true })) {
207
+ const r = `${rel}${e.name}`;
208
+ if (e.isDirectory()) { out.push(`${r}/`); await walk(join(x, e.name), `${r}/`); }
209
+ else out.push(`${r}=${await readFile(join(x, e.name), "utf8")}`);
210
+ }
211
+ };
212
+ await walk(d, "");
213
+ return out.sort();
214
+ };
215
+ const makeVictim = async () => {
216
+ const victim = join(root, "victim");
217
+ await mkdir(join(victim, "sub"), { recursive: true });
218
+ await writeFile(join(victim, "keep.txt"), "victim");
219
+ await writeFile(join(victim, "sub", "deep.txt"), "deep");
220
+ await writeFile(join(victim, "gone.txt"), "would be removed by plan");
221
+ return victim;
222
+ };
223
+
224
+ it("a project link swapped in while the sync runs is never followed", async () => {
225
+ const victim = await makeVictim();
226
+ const before = await snapshotTree(victim);
227
+ // first sync: marker matches and a local copy exists, like a real later turn
228
+ list.mockResolvedValue([remoteObj("a.txt", 1)]);
229
+ bytes.mockResolvedValue(Buffer.from("A"));
230
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
231
+ await writeFile(join(sessionDir, "project", "gone.txt"), "x");
232
+
233
+ list.mockResolvedValue([remoteObj("a.txt", 2), remoteObj("b.txt", 1)]);
234
+ bytes.mockImplementation(async (key: string) => {
235
+ // the agent's loop wins the race during the S3 await
236
+ await rm(join(sessionDir, "project"), { recursive: true, force: true });
237
+ await symlink(victim, join(sessionDir, "project"));
238
+ return Buffer.from(key.endsWith("a.txt") ? "AA" : "B");
239
+ });
240
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
241
+
242
+ expect(await snapshotTree(victim)).toEqual(before);
243
+ const st = await lstat(join(sessionDir, "project")).catch(() => null);
244
+ if (st) {
245
+ expect(st.isSymbolicLink()).toBe(false);
246
+ expect(st.isDirectory()).toBe(true);
247
+ expect(await snapshotTree(join(sessionDir, "project"))).toEqual(["a.txt=AA", "b.txt=B"]);
248
+ }
249
+ });
250
+
251
+ it("detach while project/sub is a link to a victim leaves the victim untouched", async () => {
252
+ const victim = await makeVictim();
253
+ const before = await snapshotTree(victim);
254
+ list.mockResolvedValue([remoteObj("a.txt", 1)]);
255
+ bytes.mockResolvedValue(Buffer.from("A"));
256
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
257
+ await symlink(victim, join(sessionDir, "project", "sub"));
258
+
259
+ await syncProjectDir({ sessionDir, projectId: null, config });
260
+ expect(existsSync(join(sessionDir, "project"))).toBe(false);
261
+ expect(await snapshotTree(victim)).toEqual(before);
262
+ });
263
+
264
+ it("unchanged files are reused without a download", async () => {
265
+ list.mockResolvedValue([remoteObj("a.txt", 1), remoteObj("b.txt", 2)]);
266
+ bytes.mockImplementation(async (key: string) => Buffer.from(key.endsWith("a.txt") ? "A" : "BB"));
267
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
268
+ bytes.mockClear();
269
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
270
+ expect(bytes).not.toHaveBeenCalled();
271
+ expect(await snapshotTree(join(sessionDir, "project"))).toEqual(["a.txt=A", "b.txt=BB"]);
272
+ });
273
+
274
+ it("leaves no staging or trash directories behind", async () => {
275
+ list.mockResolvedValue([remoteObj("a.txt", 1)]);
276
+ bytes.mockResolvedValue(Buffer.from("A"));
277
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
278
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
279
+ await syncProjectDir({ sessionDir, projectId: null, config });
280
+ for (const d of [".project-staging", ".project-trash"]) {
281
+ const p = join(root, d);
282
+ if (existsSync(p)) expect(await readdir(p)).toEqual([]);
283
+ }
284
+ });
285
+
286
+ it("removeTreeSafely refuses anything outside the two helper roots", async () => {
287
+ const err = jest.spyOn(console, "error").mockImplementation(() => {});
288
+ await writeFile(join(sessionDir, "keep.txt"), "k");
289
+ for (const p of [
290
+ sessionDir,
291
+ join(sessionDir, "keep.txt"),
292
+ join(root, ".project-trash"),
293
+ join(root, ".project-trash", "..", "sess-1"),
294
+ join(root, ".project-trashX", "a"),
295
+ "/",
296
+ ]) {
297
+ expect(await removeTreeSafely(p, sessionDir)).toBe(false);
298
+ }
299
+ err.mockRestore();
300
+ expect(await readFile(join(sessionDir, "keep.txt"), "utf8")).toBe("k");
301
+ });
302
+
303
+ it("removeTreeSafely deletes a trash dir holding a link without touching the link's target", async () => {
304
+ const victim = await makeVictim();
305
+ const before = await snapshotTree(victim);
306
+ const trash = join(root, ".project-trash", "sess-1-abc");
307
+ await mkdir(join(trash, "nested"), { recursive: true });
308
+ await writeFile(join(trash, "f.txt"), "f");
309
+ await symlink(victim, join(trash, "link"));
310
+ await symlink(victim, join(trash, "nested", "link2"));
311
+ expect(await removeTreeSafely(trash, sessionDir)).toBe(true);
312
+ expect(existsSync(trash)).toBe(false);
313
+ expect(await snapshotTree(victim)).toEqual(before);
314
+ });
315
+
316
+ it("sweeps this session's trash older than a day on the next sync", async () => {
317
+ const old = join(root, ".project-trash", "sess-1-old");
318
+ const fresh = join(root, ".project-trash", "sess-1-fresh");
319
+ const other = join(root, ".project-trash", "sess-2-old");
320
+ for (const d of [old, fresh, other]) await mkdir(d, { recursive: true });
321
+ const twoDaysAgo = new Date(Date.now() - 2 * 86400_000);
322
+ await utimes(old, twoDaysAgo, twoDaysAgo);
323
+ await utimes(other, twoDaysAgo, twoDaysAgo);
324
+ list.mockResolvedValue([]);
325
+ await syncProjectDir({ sessionDir, projectId: "p1", config });
326
+ expect(existsSync(old)).toBe(false);
327
+ expect(existsSync(fresh)).toBe(true);
328
+ expect(existsSync(other)).toBe(true);
329
+ });
330
+
331
+ it("keeps the marker outside the session directory, so the sandbox cannot write it", () => {
332
+ const marker = projectSyncMarkerPath(sessionDir);
333
+ expect(marker.startsWith(sessionDir + "/")).toBe(false);
334
+ expect(marker.startsWith(sessionDir)).toBe(false);
335
+ });
336
+ });
337
+
338
+ describe("resolveSandboxProjectId", () => {
339
+ const project = { id: "p1", created_by: 1, rights_mode: "private" };
340
+ const deps = (over: Partial<Parameters<typeof resolveSandboxProjectId>[1]> = {}) => ({
341
+ getProject: jest.fn(async () => project),
342
+ getRbac: jest.fn(async () => ({ type: "private", users: [], roles: [] })),
343
+ getUser: jest.fn(async (id: number | string) => ({ id: Number(id), role: null })),
344
+ ...over,
345
+ });
346
+
347
+ it("returns null without a project", async () => {
348
+ const d = deps();
349
+ expect(await resolveSandboxProjectId({ projectId: undefined, ownerId: 1 }, d)).toBeNull();
350
+ expect(d.getProject).not.toHaveBeenCalled();
351
+ });
352
+
353
+ it("returns the id when the owner can read the project", async () => {
354
+ expect(await resolveSandboxProjectId({ projectId: "p1", ownerId: 1 }, deps())).toBe("p1");
355
+ });
356
+
357
+ it("returns null when the owner has no read access", async () => {
358
+ expect(await resolveSandboxProjectId({ projectId: "p1", ownerId: 2 }, deps())).toBeNull();
359
+ });
360
+
361
+ it("returns null when the project no longer exists", async () => {
362
+ expect(
363
+ await resolveSandboxProjectId({ projectId: "p1", ownerId: 1 }, deps({ getProject: jest.fn(async () => undefined) })),
364
+ ).toBeNull();
365
+ });
366
+
367
+ it("returns null when the owner cannot be loaded", async () => {
368
+ expect(
369
+ await resolveSandboxProjectId({ projectId: "p1", ownerId: 1 }, deps({ getUser: jest.fn(async () => undefined) })),
370
+ ).toBeNull();
371
+ });
372
+
373
+ it("matches a role grant when the owner's role is a hydrated role object", async () => {
374
+ const d = deps({
375
+ getRbac: jest.fn(async () => ({ type: "roles", users: [], roles: [{ id: "r1", rights: "read" }] })),
376
+ });
377
+ const owner = { id: 2, role: { id: "r1", name: "Team" } };
378
+ expect(await resolveSandboxProjectId({ projectId: "p1", ownerId: 2, owner }, d)).toBe("p1");
379
+ expect(d.getUser).not.toHaveBeenCalled();
380
+ });
381
+
382
+ it("logs and returns null when resolving throws", async () => {
383
+ const err = jest.spyOn(console, "error").mockImplementation(() => {});
384
+ const d = deps({ getRbac: jest.fn(async () => { throw new Error("db"); }) });
385
+ expect(await resolveSandboxProjectId({ projectId: "p1", ownerId: 1 }, d)).toBeNull();
386
+ expect(err).toHaveBeenCalled();
387
+ err.mockRestore();
388
+ });
389
+ });