The best way to control Claude Code, Codex and more from any computer or phone

main
ts 585 lines 23.1 KB
Raw
1 import { gunzipSync } from "node:zlib";
2 import { createComputeArchive, normalizeEntrypoint } from "@alchemy.run/prisma/ComputeArchive";
3 import { describe, expect, it } from "@alchemy.run/test";
4 import { PlatformServices } from "alchemy/Util/PlatformServices";
5 import * as Effect from "effect/Effect";
6 import * as FileSystem from "effect/FileSystem";
7 import * as Path from "effect/Path";
8 import * as ChildProcess from "effect/process/ChildProcess";
9 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
10 import { closeDirectoryHandle } from "../../../prisma/src/internal/ArchivePlatform.ts";
11
12 interface TarEntry {
13 name: string;
14 body: string;
15 mode: number;
16 type: string;
17 linkname: string;
18 }
19
20 const readString = (buffer: Uint8Array, start: number, length: number) => {
21 const bytes = buffer.slice(start, start + length);
22 const end = bytes.indexOf(0);
23 return new TextDecoder().decode(end >= 0 ? bytes.slice(0, end) : bytes);
24 };
25
26 const parseTar = (buffer: Uint8Array) => {
27 const entries: TarEntry[] = [];
28 let offset = 0;
29 while (offset + 512 <= buffer.length) {
30 const header = buffer.slice(offset, offset + 512);
31 if (header.every((byte) => byte === 0)) break;
32 const name = readString(header, 0, 100);
33 const prefix = readString(header, 345, 155);
34 const sizeText = readString(header, 124, 12).trim();
35 const size = Number.parseInt(sizeText || "0", 8);
36 const bodyStart = offset + 512;
37 const body = buffer.slice(bodyStart, bodyStart + size);
38 entries.push({
39 name: prefix ? `${prefix}/${name}` : name,
40 body: new TextDecoder().decode(body),
41 mode: Number.parseInt(readString(header, 100, 8).trim() || "0", 8),
42 type: readString(header, 156, 1) || "0",
43 linkname: readString(header, 157, 100),
44 });
45 offset = bodyStart + size + ((512 - (size % 512)) % 512);
46 }
47 return entries;
48 };
49
50 describe(
51 "createComputeArchive",
52 { tags: ["provider:prisma", "provider:prisma:compute", "local"] },
53 () => {
54 it(
55 "closes Node and Bun directory handles without masking traversal",
56 async () => {
57 await expect(closeDirectoryHandle({ close: () => undefined })).resolves.toBeUndefined();
58 await expect(
59 closeDirectoryHandle({ close: () => Promise.resolve() }),
60 ).resolves.toBeUndefined();
61 await expect(
62 closeDirectoryHandle({ close: () => Promise.reject(new Error("closed")) }),
63 ).resolves.toBeUndefined();
64 await expect(
65 closeDirectoryHandle({
66 close: () => {
67 throw new Error("closed");
68 },
69 }),
70 ).resolves.toBeUndefined();
71 },
72 { tags: ["unit"] },
73 );
74
75 it.effect(
76 "rejects exclusions that remove a required static index",
77 () =>
78 Effect.gen(function* () {
79 const fs = yield* FileSystem.FileSystem;
80 const path = yield* Path.Path;
81 const root = yield* fs.makeTempDirectoryScoped({
82 prefix: "alchemy-prisma-required-index-",
83 });
84 yield* fs.makeDirectory(path.join(root, "public"));
85 yield* fs.writeFileString(path.join(root, "server.mjs"), "export {};");
86 yield* fs.writeFileString(path.join(root, "public", "index.html"), "site");
87
88 const error = yield* createComputeArchive({
89 directory: root,
90 entrypoint: "server.mjs",
91 ignorePrefix: "public",
92 ignore: ["*.html"],
93 requiredFiles: ["public/index.html"],
94 }).pipe(Effect.flip);
95
96 expect(error.message).toContain(
97 "Required file not found in compute artifact: public/index.html",
98 );
99 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
100 { tags: ["unit"] },
101 );
102
103 it.effect(
104 "creates the tar.gz format expected by Prisma Compute",
105 () =>
106 Effect.gen(function* () {
107 const fs = yield* FileSystem.FileSystem;
108 const path = yield* Path.Path;
109 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
110 yield* fs.makeDirectory(path.join(root, "src"));
111 yield* fs.writeFileString(path.join(root, "src", "main.ts"), "console.log('hello');");
112 yield* fs.writeFileString(path.join(root, "package.json"), "{}");
113
114 const archive = yield* createComputeArchive({
115 directory: root,
116 entrypoint: "src/main.ts",
117 });
118 const entries = parseTar(yield* Effect.sync(() => gunzipSync(archive)));
119 const byName = new Map(entries.map((entry) => [entry.name, entry.body]));
120
121 expect(byName.get("bundle/src/main.ts")).toBe("console.log('hello');");
122 expect(byName.get("bundle/package.json")).toBe("{}");
123 expect(JSON.parse(byName.get("compute.manifest.json")!)).toEqual({
124 manifestVersion: "1",
125 entrypoint: "bundle/src/main.ts",
126 });
127 }).pipe(Effect.provide(PlatformServices)),
128 { tags: ["unit"] },
129 );
130
131 it.effect("round-trips long framework chunk names and symlink targets through tar", () =>
132 Effect.gen(function* () {
133 const fs = yield* FileSystem.FileSystem;
134 const path = yield* Path.Path;
135 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
136 const root = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-prisma-long-path-" });
137 const output = yield* fs.makeTempDirectoryScoped({ prefix: "alchemy-prisma-extract-" });
138 const name = `${"framework-".repeat(12)}é.js`;
139 yield* fs.writeFileString(path.join(root, name), "export const greeting = 'vinext';");
140 yield* fs.symlink(name, path.join(root, "server.js"));
141 const archive = yield* createComputeArchive({ directory: root, entrypoint: "server.js" });
142 const again = yield* createComputeArchive({ directory: root, entrypoint: "server.js" });
143 expect(again).toEqual(archive);
144 const archivePath = path.join(output, "site.tar.gz");
145 yield* fs.writeFile(archivePath, archive);
146 const extracted = yield* spawner.exitCode(
147 ChildProcess.make("tar", ["-xzf", archivePath, "-C", output]),
148 );
149 expect(Number(extracted)).toBe(0);
150 expect(yield* fs.readFileString(path.join(output, "bundle", name))).toBe(
151 "export const greeting = 'vinext';",
152 );
153 expect(
154 (yield* fs.readLink(path.join(output, "bundle", "server.js"))).normalize("NFC"),
155 ).toBe(name);
156 }).pipe(Effect.scoped, Effect.provide(PlatformServices)),
157 );
158
159 it.effect(
160 "produces deterministic bytes for unchanged input",
161 () =>
162 Effect.gen(function* () {
163 const fs = yield* FileSystem.FileSystem;
164 const path = yield* Path.Path;
165 const root = yield* fs.makeTempDirectory({
166 prefix: "alchemy-prisma-compute-deterministic-",
167 });
168 yield* fs.writeFileString(path.join(root, "z.ts"), "z");
169 yield* fs.writeFileString(path.join(root, "server.ts"), "server");
170 yield* fs.writeFileString(path.join(root, "a.ts"), "a");
171
172 const first = yield* createComputeArchive({ directory: root, entrypoint: "server.ts" });
173 const second = yield* createComputeArchive({ directory: root, entrypoint: "server.ts" });
174
175 expect(second).toEqual(first);
176 }).pipe(Effect.provide(PlatformServices)),
177 { tags: ["unit"] },
178 );
179
180 it.effect(
181 "rejects unsafe entrypoints",
182 () =>
183 Effect.gen(function* () {
184 const parent = yield* Effect.exit(normalizeEntrypoint("../server.ts"));
185 const absolute = yield* Effect.exit(normalizeEntrypoint("/server.ts"));
186
187 expect(parent._tag).toBe("Failure");
188 expect(absolute._tag).toBe("Failure");
189 }),
190 { tags: ["unit"] },
191 );
192
193 it.effect(
194 "preserves executable file modes",
195 () =>
196 Effect.gen(function* () {
197 const fs = yield* FileSystem.FileSystem;
198 const path = yield* Path.Path;
199 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
200 const server = path.join(root, "server.sh");
201 yield* fs.writeFileString(server, "#!/bin/sh\n");
202 yield* fs.chmod(server, 0o755);
203
204 const archive = yield* createComputeArchive({ directory: root, entrypoint: "server.sh" });
205 const entries = parseTar(yield* Effect.sync(() => gunzipSync(archive)));
206 const byName = new Map(entries.map((entry) => [entry.name, entry]));
207
208 expect(byName.get("bundle/server.sh")?.mode).toBe(0o755);
209 }).pipe(Effect.provide(PlatformServices)),
210 { tags: ["unit"] },
211 );
212
213 it.effect(
214 "rejects missing entrypoints before uploading",
215 () =>
216 Effect.gen(function* () {
217 const fs = yield* FileSystem.FileSystem;
218 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
219 const result = yield* Effect.exit(
220 createComputeArchive({ directory: root, entrypoint: "server.ts" }),
221 );
222
223 expect(result._tag).toBe("Failure");
224 }).pipe(Effect.provide(PlatformServices)),
225 { tags: ["unit"] },
226 );
227
228 it.effect(
229 "preserves symlinks that stay inside the artifact root",
230 () =>
231 Effect.gen(function* () {
232 const fs = yield* FileSystem.FileSystem;
233 const path = yield* Path.Path;
234 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
235 yield* fs.writeFileString(path.join(root, "server.ts"), "export {};");
236 yield* fs.writeFileString(path.join(root, "real.ts"), "real file");
237 yield* fs.symlink(path.join(root, "real.ts"), path.join(root, "link.ts"));
238
239 const archive = yield* createComputeArchive({ directory: root, entrypoint: "server.ts" });
240 const entries = parseTar(yield* Effect.sync(() => gunzipSync(archive)));
241 const byName = new Map(entries.map((entry) => [entry.name, entry]));
242
243 expect(byName.get("bundle/link.ts")).toMatchObject({ type: "2", linkname: "real.ts" });
244 expect(byName.get("bundle/real.ts")?.body).toBe("real file");
245 }).pipe(Effect.provide(PlatformServices)),
246 { tags: ["unit"] },
247 );
248
249 it.effect(
250 "preserves symlinked directories that stay inside the artifact root",
251 () =>
252 Effect.gen(function* () {
253 const fs = yield* FileSystem.FileSystem;
254 const path = yield* Path.Path;
255 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
256 const realDir = path.join(root, "real");
257 yield* fs.makeDirectory(realDir);
258 yield* fs.writeFileString(path.join(root, "server.ts"), "export {};");
259 yield* fs.writeFileString(path.join(realDir, "nested.ts"), "nested");
260 yield* fs.symlink(realDir, path.join(root, "linked"));
261
262 const archive = yield* createComputeArchive({ directory: root, entrypoint: "server.ts" });
263 const entries = parseTar(yield* Effect.sync(() => gunzipSync(archive)));
264 const byName = new Map(entries.map((entry) => [entry.name, entry]));
265
266 expect(byName.get("bundle/linked")).toMatchObject({ type: "2", linkname: "real" });
267 expect(byName.get("bundle/real/nested.ts")?.body).toBe("nested");
268 expect(byName.has("bundle/linked/nested.ts")).toBe(false);
269 }).pipe(Effect.provide(PlatformServices)),
270 { tags: ["unit"] },
271 );
272
273 it.effect(
274 "rejects symlinks that escape the artifact root",
275 () =>
276 Effect.gen(function* () {
277 const fs = yield* FileSystem.FileSystem;
278 const path = yield* Path.Path;
279 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
280 const outside = yield* fs.makeTempDirectory({
281 prefix: "alchemy-prisma-compute-outside-",
282 });
283 yield* fs.writeFileString(path.join(root, "server.ts"), "export {};");
284 yield* fs.writeFileString(path.join(outside, "secret.ts"), "secret");
285 yield* fs.symlink(path.join(outside, "secret.ts"), path.join(root, "secret.ts"));
286
287 const result = yield* Effect.exit(
288 createComputeArchive({ directory: root, entrypoint: "server.ts" }),
289 );
290
291 expect(result._tag).toBe("Failure");
292 }).pipe(Effect.provide(PlatformServices)),
293 { tags: ["unit"] },
294 );
295
296 it.effect(
297 "rejects symlinked directories that escape the artifact root",
298 () =>
299 Effect.gen(function* () {
300 const fs = yield* FileSystem.FileSystem;
301 const path = yield* Path.Path;
302 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-" });
303 const outside = yield* fs.makeTempDirectory({
304 prefix: "alchemy-prisma-compute-outside-",
305 });
306 yield* fs.writeFileString(path.join(root, "server.ts"), "export {};");
307 yield* fs.writeFileString(path.join(outside, "secret.ts"), "secret");
308 yield* fs.symlink(outside, path.join(root, "outside"));
309
310 const result = yield* Effect.exit(
311 createComputeArchive({ directory: root, entrypoint: "server.ts" }),
312 );
313
314 expect(result._tag).toBe("Failure");
315 }).pipe(Effect.provide(PlatformServices)),
316 { tags: ["unit"] },
317 );
318
319 it.effect(
320 "excludes sensitive files at every workspace depth",
321 () =>
322 Effect.gen(function* () {
323 const fs = yield* FileSystem.FileSystem;
324 const path = yield* Path.Path;
325 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-sensitive-" });
326 yield* fs.makeDirectory(path.join(root, "apps", "api", ".git"), { recursive: true });
327 yield* fs.makeDirectory(path.join(root, "apps", "api", ".alchemy"), { recursive: true });
328 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
329 yield* fs.writeFileString(path.join(root, ".env"), "ROOT_SECRET=x");
330 yield* fs.writeFileString(
331 path.join(root, "apps", "api", ".env.production"),
332 "NESTED_SECRET=x",
333 );
334 yield* fs.writeFileString(
335 path.join(root, "apps", "api", ".git", "config"),
336 "credential=x",
337 );
338 yield* fs.writeFileString(
339 path.join(root, "apps", "api", ".alchemy", "state"),
340 "secret=x",
341 );
342 yield* fs.writeFileString(path.join(root, "debug.log"), "ignored");
343
344 const archive = yield* createComputeArchive({
345 directory: root,
346 entrypoint: "server.ts",
347 ignore: ["*.log"],
348 });
349 const names = parseTar(yield* Effect.sync(() => gunzipSync(archive))).map(
350 (entry) => entry.name,
351 );
352
353 expect(names).toContain("bundle/server.ts");
354 expect(names.some((name) => name.includes(".env"))).toBe(false);
355 expect(names.some((name) => name.includes(".git"))).toBe(false);
356 expect(names.some((name) => name.includes(".alchemy"))).toBe(false);
357 expect(names).not.toContain("bundle/debug.log");
358 }).pipe(Effect.provide(PlatformServices)),
359 { tags: ["unit"] },
360 );
361
362 it.effect(
363 "rejects an entrypoint excluded by the safety policy",
364 () =>
365 Effect.gen(function* () {
366 const fs = yield* FileSystem.FileSystem;
367 const path = yield* Path.Path;
368 const root = yield* fs.makeTempDirectory({
369 prefix: "alchemy-prisma-compute-ignored-entry-",
370 });
371 yield* fs.writeFileString(path.join(root, ".env"), "secret");
372
373 const result = yield* Effect.exit(
374 createComputeArchive({ directory: root, entrypoint: ".env" }),
375 );
376
377 expect(result._tag).toBe("Failure");
378 }).pipe(Effect.provide(PlatformServices)),
379 { tags: ["unit"] },
380 );
381
382 it.effect(
383 "allows dots in ignore names but rejects parent-segment patterns",
384 () =>
385 Effect.gen(function* () {
386 const fs = yield* FileSystem.FileSystem;
387 const path = yield* Path.Path;
388 const root = yield* fs.makeTempDirectory({
389 prefix: "alchemy-prisma-compute-ignore-validation-",
390 });
391 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
392 yield* fs.writeFileString(path.join(root, "foo..bar"), "ignored");
393
394 const archive = yield* createComputeArchive({
395 directory: root,
396 entrypoint: "server.ts",
397 ignore: ["foo..bar"],
398 });
399 const names = parseTar(yield* Effect.sync(() => gunzipSync(archive))).map(
400 (entry) => entry.name,
401 );
402 const unsafe = yield* Effect.exit(
403 createComputeArchive({
404 directory: root,
405 entrypoint: "server.ts",
406 ignore: ["../outside"],
407 }),
408 );
409
410 expect(names).not.toContain("bundle/foo..bar");
411 expect(unsafe._tag).toBe("Failure");
412 }).pipe(Effect.provide(PlatformServices)),
413 { tags: ["unit"] },
414 );
415
416 it.effect(
417 "validates custom ignore patterns before applying a prefix",
418 () =>
419 Effect.gen(function* () {
420 const fs = yield* FileSystem.FileSystem;
421 const path = yield* Path.Path;
422 const root = yield* fs.makeTempDirectory({
423 prefix: "alchemy-prisma-compute-prefixed-ignore-validation-",
424 });
425 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
426
427 const unsafe = yield* Effect.exit(
428 createComputeArchive({
429 directory: root,
430 entrypoint: "server.ts",
431 ignore: ["../outside"],
432 ignorePrefix: "public",
433 }),
434 );
435
436 expect(unsafe._tag).toBe("Failure");
437 }).pipe(Effect.provide(PlatformServices)),
438 { tags: ["unit"] },
439 );
440
441 it.effect(
442 "reports invalid archive limits as typed errors",
443 () =>
444 Effect.gen(function* () {
445 const fs = yield* FileSystem.FileSystem;
446 const path = yield* Path.Path;
447 const root = yield* fs.makeTempDirectory({
448 prefix: "alchemy-prisma-compute-invalid-limit-",
449 });
450 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
451
452 const error = yield* createComputeArchive({
453 directory: root,
454 entrypoint: "server.ts",
455 maxEntries: 0,
456 }).pipe(Effect.flip);
457
458 expect(error).toBeInstanceOf(Error);
459 expect(error.message).toContain("maxEntries");
460 }).pipe(Effect.provide(PlatformServices)),
461 { tags: ["unit"] },
462 );
463
464 it.effect(
465 "does not allow callers to raise production safety ceilings",
466 () =>
467 Effect.gen(function* () {
468 const fs = yield* FileSystem.FileSystem;
469 const path = yield* Path.Path;
470 const root = yield* fs.makeTempDirectory({
471 prefix: "alchemy-prisma-compute-hard-limit-",
472 });
473 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
474
475 const entriesError = yield* createComputeArchive({
476 directory: root,
477 entrypoint: "server.ts",
478 maxEntries: 50_001,
479 }).pipe(Effect.flip);
480 const fileError = yield* createComputeArchive({
481 directory: root,
482 entrypoint: "server.ts",
483 maxFileBytes: 128 * 1024 * 1024 + 1,
484 }).pipe(Effect.flip);
485 const totalError = yield* createComputeArchive({
486 directory: root,
487 entrypoint: "server.ts",
488 maxUncompressedBytes: 768 * 1024 * 1024 + 1,
489 }).pipe(Effect.flip);
490
491 expect(entriesError.message).toContain("hard limit");
492 expect(fileError.message).toContain("hard limit");
493 expect(totalError.message).toContain("hard limit");
494 }).pipe(Effect.provide(PlatformServices)),
495 { tags: ["unit"] },
496 );
497
498 it.effect(
499 "creates a verified file-backed archive with explicit cleanup",
500 () =>
501 Effect.gen(function* () {
502 const fs = yield* FileSystem.FileSystem;
503 const path = yield* Path.Path;
504 const root = yield* fs.makeTempDirectory({
505 prefix: "alchemy-prisma-compute-file-archive-",
506 });
507 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
508
509 const archive = yield* createComputeArchive({
510 directory: root,
511 entrypoint: "server.ts",
512 output: "file",
513 });
514 const bytes = yield* fs.readFile(archive.path);
515 const names = parseTar(yield* Effect.sync(() => gunzipSync(bytes))).map(
516 (entry) => entry.name,
517 );
518
519 expect(archive.size).toBe(bytes.byteLength);
520 expect(archive.sha256).toMatch(/^[a-f0-9]{64}$/);
521 expect(names).toContain("bundle/server.ts");
522 expect(yield* fs.exists(archive.path)).toBe(true);
523 yield* archive.cleanup;
524 expect(yield* fs.exists(archive.path)).toBe(false);
525 }).pipe(Effect.provide(PlatformServices)),
526 { tags: ["unit"] },
527 );
528
529 it.effect(
530 "fails explicitly for oversized files and archives",
531 () =>
532 Effect.gen(function* () {
533 const fs = yield* FileSystem.FileSystem;
534 const path = yield* Path.Path;
535 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-limit-" });
536 yield* fs.writeFileString(path.join(root, "server.ts"), "12345");
537 yield* fs.writeFileString(path.join(root, "other.ts"), "67890");
538
539 const fileResult = yield* Effect.exit(
540 createComputeArchive({ directory: root, entrypoint: "server.ts", maxFileBytes: 4 }),
541 );
542 const totalResult = yield* Effect.exit(
543 createComputeArchive({
544 directory: root,
545 entrypoint: "server.ts",
546 maxFileBytes: 10,
547 maxUncompressedBytes: 9,
548 }),
549 );
550
551 expect(fileResult._tag).toBe("Failure");
552 expect(totalResult._tag).toBe("Failure");
553 }).pipe(Effect.provide(PlatformServices)),
554 { tags: ["unit"] },
555 );
556
557 it.effect(
558 "encodes long nested symlink targets with PAX records",
559 () =>
560 Effect.gen(function* () {
561 const fs = yield* FileSystem.FileSystem;
562 const path = yield* Path.Path;
563 const root = yield* fs.makeTempDirectory({ prefix: "alchemy-prisma-compute-long-link-" });
564 const segments = Array.from(
565 { length: 12 },
566 (_, index) => `segment-${index.toString().padStart(2, "0")}`,
567 );
568 const target = path.join(...segments, "target.ts");
569 yield* fs.makeDirectory(path.join(root, ...segments), { recursive: true });
570 yield* fs.writeFileString(path.join(root, "server.ts"), "safe");
571 yield* fs.writeFileString(path.join(root, target), "target");
572 yield* fs.symlink(target, path.join(root, "long-link.ts"));
573
574 const archive = yield* createComputeArchive({ directory: root, entrypoint: "server.ts" });
575 const entries = parseTar(yield* Effect.sync(() => gunzipSync(archive)));
576 expect(
577 entries.some(
578 (entry) => entry.type === "x" && entry.body.includes(`linkpath=${target}\n`),
579 ),
580 ).toBe(true);
581 }).pipe(Effect.provide(PlatformServices)),
582 { tags: ["unit"] },
583 );
584 },
585 );