@computesdk/cli 2.6.13 → 2.6.14

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.
package/checkpoint.cjs ADDED
@@ -0,0 +1,1949 @@
1
+ /**
2
+ * checkpoint-oci-module — the in-sandbox capture/restore engine for daemond,
3
+ * OCI artifact edition.
4
+ *
5
+ * Runs as a detached module job (`module.exec`) inside the sandbox: pure Node
6
+ * stdlib (fs/crypto/zlib/http/https), so it executes on any provider image
7
+ * that has a node runtime — including the daemond-bootstrapped static node.
8
+ * The platform installs it via `module.install` with the source passed
9
+ * explicitly (`checkpointInstallInput(source)`); this file is that source.
10
+ *
11
+ * Usage: `node checkpoint-oci-module.cjs <op> <payload>`
12
+ * payload: `b64:<base64-json>` or raw JSON on argv[3].
13
+ * stdout: JSON lines — `{type:"progress",...}`* then `{type:"result",...}`
14
+ * or `{type:"error",message}` with a non-zero exit code.
15
+ *
16
+ * Ops:
17
+ * scan walk + sha256 + build the file index (no upload)
18
+ * capture walk → deterministic tar+gzip layers → CAS blobs → OCI manifest
19
+ * restore fetch manifest → config (file index) → only the layers that
20
+ * cover selected files → verify sha256 → extract
21
+ * diff compare two checkpoints' file indexes → added/changed/deleted
22
+ *
23
+ * Artifact layout (OCI image-layout-inspired, `{prefix}` = "{orgId}/"):
24
+ * blobs/{sha256-hex} content-addressed objects: one per layer
25
+ * (tar+gzip) plus the image-config JSON blob
26
+ * manifests/{id}.json OCI image manifest — the checkpoint's commit
27
+ * point; small, fetchable without pulling layers
28
+ *
29
+ * Because a layer is a tar+gzip blob addressed by digest and the manifest is
30
+ * an OCI manifest, a checkpoint is pullable by ordinary OCI tooling and can
31
+ * lazy-pull: read the manifest (KB), then fetch only the layers needed.
32
+ */
33
+ "use strict";
34
+
35
+ const fs = require("node:fs");
36
+ const path = require("node:path");
37
+ const os = require("node:os");
38
+ const crypto = require("node:crypto");
39
+ const zlib = require("node:zlib");
40
+ const http = require("node:http");
41
+ const https = require("node:https");
42
+
43
+ // ---------------------------------------------------------------------------
44
+ // Wire output
45
+ // ---------------------------------------------------------------------------
46
+
47
+ function emitProgress(op, phase, done, total, bytes) {
48
+ const event = { type: "progress", op, phase, done, total };
49
+ if (bytes !== undefined) event.bytes = bytes;
50
+ process.stdout.write(`${JSON.stringify(event)}\n`);
51
+ }
52
+
53
+ function emitResult(value) {
54
+ process.stdout.write(`${JSON.stringify({ type: "result", ...value })}\n`);
55
+ }
56
+
57
+ /**
58
+ * Emit an op result. When args.resultPath is set the full result is written
59
+ * to that file and stdout gets a slim pointer instead — detached job output
60
+ * is tail-bounded (4MiB), and a big manifest/result line would be clipped
61
+ * mid-JSON before callers could parse it.
62
+ */
63
+ function emitOpResult(args, result) {
64
+ const resultPath =
65
+ typeof args.resultPath === "string" && args.resultPath.length > 0
66
+ ? args.resultPath
67
+ : undefined;
68
+ if (!resultPath) {
69
+ emitResult(result);
70
+ return;
71
+ }
72
+ fs.writeFileSync(resultPath, JSON.stringify(result));
73
+ emitResult({ op: result.op, resultPath });
74
+ }
75
+
76
+ function emitError(err) {
77
+ const message = err instanceof Error ? err.stack ?? err.message : String(err);
78
+ process.stdout.write(`${JSON.stringify({ type: "error", message })}\n`);
79
+ process.exit(1);
80
+ }
81
+
82
+ class ProgressReporter {
83
+ constructor(op, phase, total, intervalMs = 250) {
84
+ this.op = op;
85
+ this.phase = phase;
86
+ this.total = total;
87
+ this.intervalMs = intervalMs;
88
+ this.last = 0;
89
+ }
90
+ tick(done, bytes) {
91
+ const now = Date.now();
92
+ if (done >= this.total || now - this.last >= this.intervalMs) {
93
+ this.last = now;
94
+ emitProgress(this.op, this.phase, done, this.total, bytes);
95
+ }
96
+ }
97
+ }
98
+
99
+ // ---------------------------------------------------------------------------
100
+ // Small utilities
101
+ // ---------------------------------------------------------------------------
102
+
103
+ async function mapLimit(items, limit, fn) {
104
+ const results = new Array(items.length);
105
+ let cursor = 0;
106
+ const workers = new Array(Math.min(limit, items.length))
107
+ .fill(0)
108
+ .map(async () => {
109
+ while (cursor < items.length) {
110
+ const index = cursor++;
111
+ results[index] = await fn(items[index], index);
112
+ }
113
+ });
114
+ await Promise.all(workers);
115
+ return results;
116
+ }
117
+
118
+ function sha256File(filePath) {
119
+ return new Promise((resolve, reject) => {
120
+ const hash = crypto.createHash("sha256");
121
+ const stream = fs.createReadStream(filePath);
122
+ stream.on("error", reject);
123
+ stream.on("data", (chunk) => hash.update(chunk));
124
+ stream.on("end", () => resolve(hash.digest("hex")));
125
+ });
126
+ }
127
+
128
+ function sha256Buffer(data) {
129
+ return crypto.createHash("sha256").update(data).digest("hex");
130
+ }
131
+
132
+ /** True when `resolved` equals `root` or sits under it (`root` itself may be "/"). */
133
+ function isUnderRoot(root, resolved) {
134
+ if (resolved === root) return true;
135
+ const prefix = root.endsWith(path.sep) ? root : root + path.sep;
136
+ return resolved.startsWith(prefix);
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Glob matcher (gitignore-lite: **, *, ?, basename matching for bare names)
141
+ // ---------------------------------------------------------------------------
142
+
143
+ function escapeRegExp(value) {
144
+ return value.replace(/[.+^${}()|[\]\\]/g, "\\$&");
145
+ }
146
+
147
+ function compileGlob(raw) {
148
+ let glob = raw.trim();
149
+ let dirOnly = false;
150
+ if (glob.endsWith("/")) {
151
+ dirOnly = true;
152
+ glob = glob.slice(0, -1);
153
+ }
154
+ let re = "";
155
+ let i = 0;
156
+ while (i < glob.length) {
157
+ const ch = glob[i];
158
+ if (ch === "*") {
159
+ if (glob[i + 1] === "*") {
160
+ const after = glob[i + 2];
161
+ if (after === "/") {
162
+ re += "(?:.*/)?";
163
+ i += 3;
164
+ } else {
165
+ re += ".*";
166
+ i += 2;
167
+ }
168
+ } else {
169
+ re += "[^/]*";
170
+ i += 1;
171
+ }
172
+ } else if (ch === "?") {
173
+ re += "[^/]";
174
+ i += 1;
175
+ } else {
176
+ re += escapeRegExp(ch);
177
+ i += 1;
178
+ }
179
+ }
180
+ return { regex: new RegExp(`(?:^|/)${re}$`), dirOnly };
181
+ }
182
+
183
+ function compileGlobs(globs) {
184
+ return (globs ?? []).map(compileGlob);
185
+ }
186
+
187
+ function isExcluded(absPath, isDir, globs) {
188
+ for (const glob of globs) {
189
+ if (glob.dirOnly && !isDir) continue;
190
+ if (glob.regex.test(absPath)) return true;
191
+ }
192
+ return false;
193
+ }
194
+
195
+ // ---------------------------------------------------------------------------
196
+ // File index (the checkpoint's config payload)
197
+ // ---------------------------------------------------------------------------
198
+
199
+ /**
200
+ * The file index travels inside the OCI image-config blob — it is what makes
201
+ * lazy pull meaningful (which layers cover which paths), powers `diff`, and
202
+ * gives restore per-file sha256 verification without opening a layer.
203
+ * Index entries are the old manifest's vocabulary plus `layer` — the index
204
+ * of the manifest's `layers[]` the entry was packed into.
205
+ */
206
+
207
+ function walkTree(paths, globs) {
208
+ const tree = { files: [], dirs: [], symlinks: [], missing: [] };
209
+ const visit = (abs) => {
210
+ let stat;
211
+ try {
212
+ stat = fs.lstatSync(abs);
213
+ } catch {
214
+ tree.missing.push(abs);
215
+ return;
216
+ }
217
+ if (stat.isSymbolicLink()) {
218
+ if (isExcluded(abs, false, globs)) return;
219
+ let link = "";
220
+ try {
221
+ link = fs.readlinkSync(abs);
222
+ } catch {
223
+ tree.missing.push(abs);
224
+ return;
225
+ }
226
+ tree.symlinks.push({ abs, link, mode: stat.mode, mtime: stat.mtimeMs });
227
+ return;
228
+ }
229
+ if (stat.isDirectory()) {
230
+ if (isExcluded(abs, true, globs)) return;
231
+ tree.dirs.push({ abs, mode: stat.mode, mtime: stat.mtimeMs });
232
+ let names;
233
+ try {
234
+ names = fs.readdirSync(abs).sort();
235
+ } catch {
236
+ tree.missing.push(abs);
237
+ return;
238
+ }
239
+ for (const name of names) visit(path.join(abs, name));
240
+ return;
241
+ }
242
+ if (stat.isFile()) {
243
+ if (isExcluded(abs, false, globs)) return;
244
+ tree.files.push({ abs, size: stat.size, mode: stat.mode, mtime: stat.mtimeMs });
245
+ return;
246
+ }
247
+ // sockets/fifos/devices: host-bound, never captured.
248
+ };
249
+ for (const root of paths) visit(path.resolve(root));
250
+ return tree;
251
+ }
252
+
253
+ async function hashFiles(files, concurrency, reporter) {
254
+ const hashes = new Map();
255
+ let done = 0;
256
+ let bytes = 0;
257
+ await mapLimit(files, concurrency, async (file) => {
258
+ const sha = await sha256File(file.abs);
259
+ hashes.set(file.abs, sha);
260
+ done += 1;
261
+ bytes += file.size;
262
+ reporter.tick(done, bytes);
263
+ });
264
+ return hashes;
265
+ }
266
+
267
+ /**
268
+ * Layer assignment: every capture root owns one layer; each tree entry is
269
+ * packed into the layer of the *deepest* root that contains it, so a
270
+ * checkpoint of unchanged subtrees reproduces identical layer blobs and
271
+ * dedups whole-layer against the store.
272
+ */
273
+ function layerFor(abs, roots) {
274
+ let best = -1;
275
+ for (let i = 0; i < roots.length; i += 1) {
276
+ const root = roots[i];
277
+ if (abs === root || abs.startsWith(root === "/" ? "/" : `${root}/`)) {
278
+ if (best === -1 || roots[best].length < root.length) best = i;
279
+ }
280
+ }
281
+ return best;
282
+ }
283
+
284
+ async function buildIndex(args) {
285
+ const globs = compileGlobs(args.exclude);
286
+ const paths = (args.paths ?? []).map((p) => path.resolve(p));
287
+ // Capture-root belt: the platform validates `paths` lexically, but a
288
+ // root with a symlinked intermediate component (e.g. /root/link/sub
289
+ // where link -> /etc) resolves out of scope — realpath catches what a
290
+ // string check cannot. Roots that don't resolve land in `missing`.
291
+ const allowedRoots = (args.allowedRoots ?? [])
292
+ .map((r) => {
293
+ try {
294
+ return fs.realpathSync(path.resolve(r));
295
+ } catch {
296
+ return null;
297
+ }
298
+ })
299
+ .filter((r) => r !== null);
300
+ if (allowedRoots.length > 0) {
301
+ for (const p of paths) {
302
+ let real;
303
+ try {
304
+ real = fs.realpathSync(p);
305
+ } catch {
306
+ continue;
307
+ }
308
+ if (!allowedRoots.some((r) => real === r || real.startsWith(`${r}/`))) {
309
+ throw new Error(
310
+ `capture path escapes allowed roots: ${p} -> ${real}`,
311
+ );
312
+ }
313
+ }
314
+ }
315
+ const tree = walkTree(paths, globs);
316
+ const totalBytes = tree.files.reduce((sum, f) => sum + f.size, 0);
317
+ const reporter = new ProgressReporter("scan", "hash", tree.files.length);
318
+ const hashes = await hashFiles(tree.files, args.hashConcurrency ?? 8, reporter);
319
+
320
+ const files = {};
321
+ for (const dir of tree.dirs) {
322
+ files[dir.abs] = {
323
+ type: "dir",
324
+ mode: dir.mode,
325
+ mtime: Math.round(dir.mtime),
326
+ layer: layerFor(dir.abs, paths),
327
+ };
328
+ }
329
+ for (const link of tree.symlinks) {
330
+ files[link.abs] = {
331
+ type: "symlink",
332
+ mode: link.mode,
333
+ mtime: Math.round(link.mtime),
334
+ link: link.link,
335
+ layer: layerFor(link.abs, paths),
336
+ };
337
+ }
338
+ for (const file of tree.files) {
339
+ files[file.abs] = {
340
+ type: "file",
341
+ sha: hashes.get(file.abs),
342
+ size: file.size,
343
+ mode: file.mode,
344
+ mtime: Math.round(file.mtime),
345
+ layer: layerFor(file.abs, paths),
346
+ };
347
+ }
348
+
349
+ const config = {
350
+ kind: "sandbox-checkpoint",
351
+ version: 1,
352
+ checkpointId:
353
+ args.checkpointId ?? `ckpt-${crypto.randomBytes(8).toString("hex")}`,
354
+ createdAt: new Date().toISOString(),
355
+ arch: args.meta?.arch ?? process.arch,
356
+ platform: args.meta?.platform ?? process.platform,
357
+ capture: { paths, exclude: args.exclude ?? [], missing: tree.missing },
358
+ stats: {
359
+ files: tree.files.length,
360
+ dirs: tree.dirs.length,
361
+ symlinks: tree.symlinks.length,
362
+ bytes: totalBytes,
363
+ },
364
+ files,
365
+ };
366
+ if (args.meta?.cwd !== undefined) config.cwd = args.meta.cwd;
367
+ if (args.meta?.env !== undefined) config.env = args.meta.env;
368
+ if (args.meta?.organizationId !== undefined) {
369
+ config.organizationId = args.meta.organizationId;
370
+ }
371
+ if (args.meta?.sourceSandboxId !== undefined) {
372
+ config.sourceSandboxId = args.meta.sourceSandboxId;
373
+ }
374
+ if (args.meta?.sourceProvider !== undefined) {
375
+ config.sourceProvider = args.meta.sourceProvider;
376
+ }
377
+
378
+ return { config, missing: tree.missing, fileBytes: hashes };
379
+ }
380
+
381
+ function diffIndexes(a, b) {
382
+ const added = [];
383
+ const deleted = [];
384
+ const changed = [];
385
+ let unchanged = 0;
386
+ const aFiles = a.files ?? {};
387
+ const bFiles = b.files ?? {};
388
+ for (const [p, entry] of Object.entries(bFiles)) {
389
+ const prev = aFiles[p];
390
+ if (!prev) {
391
+ added.push(p);
392
+ } else if (
393
+ prev.type !== entry.type ||
394
+ prev.sha !== entry.sha ||
395
+ prev.mode !== entry.mode ||
396
+ prev.link !== entry.link
397
+ ) {
398
+ changed.push({ path: p, aSha: prev.sha, bSha: entry.sha });
399
+ } else {
400
+ unchanged += 1;
401
+ }
402
+ }
403
+ for (const p of Object.keys(aFiles)) {
404
+ if (!(p in bFiles)) deleted.push(p);
405
+ }
406
+ added.sort();
407
+ deleted.sort();
408
+ changed.sort((x, y) => x.path.localeCompare(y.path));
409
+ return { added, deleted, changed, unchanged };
410
+ }
411
+
412
+ // ---------------------------------------------------------------------------
413
+ // Tar writer — ustar + pax, streaming, deterministic.
414
+ //
415
+ // Entries are emitted sorted by tar path; header fields carry the file's real
416
+ // mode/uid/gid/mtime. gzip (zlib) writes a fixed mtime=0 header, so an
417
+ // unchanged subtree reproduces an identical layer blob — that identity is
418
+ // what content-addressed dedup across checkpoints rests on.
419
+ // ---------------------------------------------------------------------------
420
+
421
+ const TAR_BLOCK = 512;
422
+
423
+ function octal(value, length) {
424
+ // POSIX octal field: zero-padded digits, null-terminated.
425
+ const s = Math.floor(value).toString(8).padStart(length - 1, "0");
426
+ if (s.length > length - 1) throw new Error(`tar: field overflow ${value}`);
427
+ return `${s}\0`;
428
+ }
429
+
430
+ /**
431
+ * Split a long name across ustar prefix+name when a "/" boundary allows it
432
+ * (name ≤100, prefix ≤155); null when even that cannot hold it — the caller
433
+ * emits a pax `path` record instead.
434
+ */
435
+ function ustarNameSplit(name) {
436
+ if (name.length <= 100) return { name, prefix: "" };
437
+ const slash = name.lastIndexOf("/", Math.min(name.length, 100));
438
+ if (slash < 0) return null;
439
+ const prefix = name.slice(0, slash);
440
+ const tail = name.slice(slash + 1);
441
+ if (tail.length > 100 || prefix.length > 155 || tail.length === 0) return null;
442
+ return { name: tail, prefix };
443
+ }
444
+
445
+ function tarChecksum(header) {
446
+ let sum = 0;
447
+ for (let i = 0; i < TAR_BLOCK; i += 1) {
448
+ // chksum field (offset 148, len 8) counts as spaces while summing.
449
+ sum += i >= 148 && i < 156 ? 0x20 : header[i];
450
+ }
451
+ return sum;
452
+ }
453
+
454
+ function tarHeader(fields) {
455
+ const header = Buffer.alloc(TAR_BLOCK);
456
+ header.write(fields.name.slice(0, 100), 0, "utf8");
457
+ header.write(octal(fields.mode & 0o7777, 8), 100, "utf8");
458
+ header.write(octal(fields.uid ?? 0, 8), 108, "utf8");
459
+ header.write(octal(fields.gid ?? 0, 8), 116, "utf8");
460
+ header.write(octal(fields.size ?? 0, 12), 124, "utf8");
461
+ header.write(octal(fields.mtime ?? 0, 12), 136, "utf8");
462
+ // chksum filled after summing.
463
+ header.write(fields.typeflag, 156, "utf8");
464
+ if (fields.linkname) header.write(fields.linkname.slice(0, 100), 157, "utf8");
465
+ header.write("ustar\0", 257, "utf8");
466
+ header.write("00", 263, "utf8");
467
+ if (fields.uname) header.write(fields.uname.slice(0, 32), 265, "utf8");
468
+ if (fields.gname) header.write(fields.gname.slice(0, 32), 297, "utf8");
469
+ if (fields.prefix) header.write(fields.prefix.slice(0, 155), 345, "utf8");
470
+ const sum = tarChecksum(header);
471
+ header.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, "utf8");
472
+ return header;
473
+ }
474
+
475
+ /** A pax extended-header entry carrying the given records (path, linkpath). */
476
+ function paxEntry(records) {
477
+ let body = "";
478
+ for (const [key, value] of Object.entries(records)) {
479
+ // record = "<len> <key>=<value>\n" where len covers the whole record.
480
+ let len = key.length + String(value).length + 3; // space, '=', '\n'
481
+ len += String(len).length;
482
+ // The length digits can grow the record when len crosses a power of ten.
483
+ while (`${len} ${key}=${value}\n`.length !== len) len += 1;
484
+ body += `${len} ${key}=${value}\n`;
485
+ }
486
+ const data = Buffer.from(body, "utf8");
487
+ return {
488
+ header: tarHeader({
489
+ name: "pax_global_header",
490
+ mode: 0o644,
491
+ size: data.length,
492
+ typeflag: "x",
493
+ }),
494
+ data,
495
+ };
496
+ }
497
+
498
+ /**
499
+ * Writes one layer's tar stream: entries already grouped/sorted by the
500
+ * caller. Each entry = {name, type, mode, mtime, size, link, filePath}.
501
+ * Returns {sha256, bytes} of the produced tar — the layer's diff_id —
502
+ * through the `onChunk` taps the caller pipes through gzip.
503
+ */
504
+ async function writeTar(out, entries, reporter) {
505
+ let done = 0;
506
+ const emit = (buf) => out.write(buf);
507
+ for (const entry of entries) {
508
+ const pax = {};
509
+ const split = ustarNameSplit(entry.name);
510
+ if (split === null) pax.path = entry.name;
511
+ if (entry.link && entry.link.length > 100) pax.linkpath = entry.link;
512
+ let header;
513
+ if (Object.keys(pax).length > 0) {
514
+ const p = paxEntry(pax);
515
+ emit(p.header);
516
+ emit(p.data);
517
+ emit(Buffer.alloc((TAR_BLOCK - (p.data.length % TAR_BLOCK)) % TAR_BLOCK));
518
+ header = tarHeader({
519
+ ...entry,
520
+ // Fallback name: basename truncated to fit — the pax `path` record
521
+ // is authoritative for readers.
522
+ name: entry.name.split("/").pop().slice(0, 100) || "entry",
523
+ prefix: "",
524
+ });
525
+ } else {
526
+ header = tarHeader({ ...entry, name: split.name, prefix: split.prefix });
527
+ }
528
+ emit(header);
529
+ if (entry.typeflag === "0" && entry.size > 0) {
530
+ // Stream the file body — never buffered whole.
531
+ await new Promise((resolve, reject) => {
532
+ const stream = fs.createReadStream(entry.filePath);
533
+ stream.on("error", reject);
534
+ stream.on("data", (chunk) => emit(chunk));
535
+ stream.on("end", resolve);
536
+ });
537
+ emit(Buffer.alloc((TAR_BLOCK - (entry.size % TAR_BLOCK)) % TAR_BLOCK));
538
+ }
539
+ done += 1;
540
+ reporter?.tick(done);
541
+ }
542
+ emit(Buffer.alloc(TAR_BLOCK * 2)); // end-of-archive marker
543
+ }
544
+
545
+ /**
546
+ * Reads a tar stream from a file path and hands each entry to `onEntry`.
547
+ * Entry = {name, typeflag, mode, uid, gid, size, mtime, linkname, pax}.
548
+ * `onEntry` receives a `data()` reader: call it to consume the entry body
549
+ * (must be called, or skipped via `skip()`, before the next entry parses —
550
+ * the body is read lazily to keep memory O(1)).
551
+ * Supports ustar, pax `x` records, and GNU `L`/`K` long-name records.
552
+ */
553
+ async function readTar(filePath, onEntry) {
554
+ const fd = fs.openSync(filePath, "r");
555
+ try {
556
+ let offset = 0;
557
+ const buf = Buffer.alloc(TAR_BLOCK);
558
+ const readBlock = async (at) => {
559
+ const bytesRead = fs.readSync(fd, buf, 0, TAR_BLOCK, at);
560
+ if (bytesRead < TAR_BLOCK) return null;
561
+ return Buffer.from(buf);
562
+ };
563
+ const readBytes = async (at, length) => {
564
+ const data = Buffer.alloc(length);
565
+ let got = 0;
566
+ while (got < length) {
567
+ const bytesRead = fs.readSync(fd, data, got, length - got, at + got);
568
+ if (bytesRead <= 0) break;
569
+ got += bytesRead;
570
+ }
571
+ return data.subarray(0, got);
572
+ };
573
+ const skipTo = (at) => {
574
+ offset = at;
575
+ };
576
+ let pendingName;
577
+ let pendingLink;
578
+ let pendingMtime;
579
+ while (true) {
580
+ const header = await readBlock(offset);
581
+ if (header === null || header.every((b) => b === 0)) break;
582
+ const oct = (start, len) => {
583
+ const raw = header
584
+ .subarray(start, start + len)
585
+ .toString("utf8")
586
+ .replace(/\0.*$/s, "")
587
+ .trim();
588
+ const value = parseInt(raw, 8);
589
+ return Number.isFinite(value) ? value : 0;
590
+ };
591
+ const name = header.subarray(0, 100).toString("utf8").replace(/\0.*$/s, "");
592
+ const size = oct(124, 12);
593
+ const typeflag = header.subarray(156, 157).toString("utf8") || "0";
594
+ const linkname = header.subarray(157, 257).toString("utf8").replace(/\0.*$/s, "");
595
+ const prefix = header.subarray(345, 500).toString("utf8").replace(/\0.*$/s, "");
596
+ offset += TAR_BLOCK;
597
+ const bodyAt = offset;
598
+ offset += Math.ceil(size / TAR_BLOCK) * TAR_BLOCK;
599
+
600
+ if (typeflag === "x" || typeflag === "g") {
601
+ const data = await readBytes(bodyAt, size);
602
+ for (const rec of parsePaxRecords(data)) {
603
+ if (rec.key === "path") pendingName = rec.value;
604
+ else if (rec.key === "linkpath") pendingLink = rec.value;
605
+ else if (rec.key === "mtime") pendingMtime = Math.floor(Number(rec.value));
606
+ }
607
+ continue;
608
+ }
609
+ if (typeflag === "L" || typeflag === "K") {
610
+ const data = await readBytes(bodyAt, size);
611
+ const text = data.toString("utf8").replace(/\0+$/, "");
612
+ if (typeflag === "L") pendingName = text;
613
+ else pendingLink = text;
614
+ continue;
615
+ }
616
+
617
+ const fullName = pendingName ?? (prefix ? `${prefix}/${name}` : name);
618
+ const entry = {
619
+ name: fullName,
620
+ typeflag,
621
+ mode: oct(100, 8),
622
+ uid: oct(108, 8),
623
+ gid: oct(116, 8),
624
+ size,
625
+ mtime: pendingMtime ?? oct(136, 12),
626
+ linkname: pendingLink ?? linkname,
627
+ };
628
+ pendingName = undefined;
629
+ pendingLink = undefined;
630
+ pendingMtime = undefined;
631
+ await onEntry(entry, {
632
+ /** Copy the entry body to `dest`; returns its sha256. */
633
+ extract: async (dest) => {
634
+ const hash = crypto.createHash("sha256");
635
+ const outFd = fs.openSync(dest, "w");
636
+ try {
637
+ let left = size;
638
+ let at = bodyAt;
639
+ while (left > 0) {
640
+ const chunk = Buffer.alloc(Math.min(left, 1 << 20));
641
+ const bytesRead = fs.readSync(
642
+ fd,
643
+ chunk,
644
+ 0,
645
+ chunk.length,
646
+ at,
647
+ );
648
+ if (bytesRead <= 0) break;
649
+ const slice = chunk.subarray(0, bytesRead);
650
+ hash.update(slice);
651
+ fs.writeSync(outFd, slice);
652
+ at += bytesRead;
653
+ left -= bytesRead;
654
+ }
655
+ } finally {
656
+ fs.closeSync(outFd);
657
+ }
658
+ return hash.digest("hex");
659
+ },
660
+ skip: async () => skipTo(offset),
661
+ });
662
+ }
663
+ } finally {
664
+ fs.closeSync(fd);
665
+ }
666
+ }
667
+
668
+ /** Pax record stream: "<len> <key>=<value>\n" repeated. */
669
+ function parsePaxRecords(data) {
670
+ const records = [];
671
+ let at = 0;
672
+ while (at < data.length) {
673
+ const space = data.indexOf(0x20, at);
674
+ if (space < 0) break;
675
+ const len = Number(data.subarray(at, space).toString("utf8"));
676
+ if (!Number.isFinite(len) || len <= 0) break;
677
+ const rec = data.subarray(space + 1, at + len - 1).toString("utf8");
678
+ const eq = rec.indexOf("=");
679
+ if (eq > 0) records.push({ key: rec.slice(0, eq), value: rec.slice(eq + 1) });
680
+ at += len;
681
+ }
682
+ return records;
683
+ }
684
+
685
+ // ---------------------------------------------------------------------------
686
+ // HTTP helpers (no fetch — node:http/https, works on every node since v0.x)
687
+ // ---------------------------------------------------------------------------
688
+
689
+ function httpRequest(opts) {
690
+ return new Promise((resolve, reject) => {
691
+ const url = new URL(opts.url);
692
+ const lib = url.protocol === "http:" ? http : https;
693
+ const req = lib.request(
694
+ url,
695
+ {
696
+ method: opts.method,
697
+ headers: opts.headers,
698
+ timeout: opts.timeoutMs ?? 60000,
699
+ },
700
+ (res) => {
701
+ const chunks = [];
702
+ res.on("data", (chunk) => chunks.push(chunk));
703
+ res.on("end", () => {
704
+ const status = res.statusCode ?? 0;
705
+ const body = Buffer.concat(chunks);
706
+ const redirects = opts.redirects ?? 3;
707
+ if (
708
+ status >= 300 &&
709
+ status < 400 &&
710
+ typeof res.headers.location === "string" &&
711
+ redirects > 0
712
+ ) {
713
+ httpRequest({
714
+ ...opts,
715
+ url: new URL(res.headers.location, url).toString(),
716
+ redirects: redirects - 1,
717
+ }).then(resolve, reject);
718
+ return;
719
+ }
720
+ resolve({ status, headers: res.headers, body });
721
+ });
722
+ },
723
+ );
724
+ req.on("timeout", () => req.destroy(new Error("http request timeout")));
725
+ req.on("error", reject);
726
+ if (opts.body) req.write(opts.body);
727
+ req.end();
728
+ });
729
+ }
730
+
731
+ /** Like httpRequest but streams the request body from a file. */
732
+ function httpPutFile(opts) {
733
+ return new Promise((resolve, reject) => {
734
+ const url = new URL(opts.url);
735
+ const lib = url.protocol === "http:" ? http : https;
736
+ const size = fs.statSync(opts.filePath).size;
737
+ const req = lib.request(
738
+ url,
739
+ {
740
+ method: "PUT",
741
+ headers: { "content-length": String(size), ...(opts.headers ?? {}) },
742
+ timeout: opts.timeoutMs ?? 120000,
743
+ },
744
+ (res) => {
745
+ const chunks = [];
746
+ res.on("data", (chunk) => chunks.push(chunk));
747
+ res.on("end", () => {
748
+ const status = res.statusCode ?? 0;
749
+ const redirects = opts.redirects ?? 3;
750
+ if (
751
+ status >= 300 &&
752
+ status < 400 &&
753
+ typeof res.headers.location === "string" &&
754
+ redirects > 0
755
+ ) {
756
+ httpPutFile({
757
+ ...opts,
758
+ url: new URL(res.headers.location, url).toString(),
759
+ redirects: redirects - 1,
760
+ }).then(resolve, reject);
761
+ return;
762
+ }
763
+ resolve({ status, headers: res.headers, body: Buffer.concat(chunks) });
764
+ });
765
+ },
766
+ );
767
+ req.on("timeout", () => req.destroy(new Error("http put timeout")));
768
+ req.on("error", reject);
769
+ fs.createReadStream(opts.filePath).on("error", reject).pipe(req);
770
+ });
771
+ }
772
+
773
+ /** Streams a response body to `filePath`; returns the final HttpResponse. */
774
+ function httpGetFile(opts) {
775
+ return new Promise((resolve, reject) => {
776
+ const url = new URL(opts.url);
777
+ const lib = url.protocol === "http:" ? http : https;
778
+ const req = lib.request(
779
+ url,
780
+ { method: "GET", headers: opts.headers, timeout: opts.timeoutMs ?? 120000 },
781
+ (res) => {
782
+ const status = res.statusCode ?? 0;
783
+ const redirects = opts.redirects ?? 3;
784
+ if (
785
+ status >= 300 &&
786
+ status < 400 &&
787
+ typeof res.headers.location === "string" &&
788
+ redirects > 0
789
+ ) {
790
+ res.resume();
791
+ httpGetFile({
792
+ ...opts,
793
+ url: new URL(res.headers.location, url).toString(),
794
+ redirects: redirects - 1,
795
+ }).then(resolve, reject);
796
+ return;
797
+ }
798
+ if (status < 200 || status >= 300) {
799
+ const chunks = [];
800
+ res.on("data", (chunk) => chunks.push(chunk));
801
+ res.on("end", () =>
802
+ resolve({ status, headers: res.headers, body: Buffer.concat(chunks) }),
803
+ );
804
+ return;
805
+ }
806
+ const fd = fs.openSync(opts.filePath, "w");
807
+ res.on("data", (chunk) => fs.writeSync(fd, chunk));
808
+ res.on("end", () => {
809
+ fs.closeSync(fd);
810
+ resolve({ status, headers: res.headers, body: Buffer.alloc(0) });
811
+ });
812
+ res.on("error", (err) => {
813
+ fs.closeSync(fd);
814
+ reject(err);
815
+ });
816
+ },
817
+ );
818
+ req.on("timeout", () => req.destroy(new Error("http get timeout")));
819
+ req.on("error", reject);
820
+ req.end();
821
+ });
822
+ }
823
+
824
+ // ---------------------------------------------------------------------------
825
+ // Object stores
826
+ //
827
+ // A directory contract, not an S3 contract: the platform hands the whole
828
+ // `store` object in the op argv and the module dispatches on `store.kind`.
829
+ // There is deliberately no SigV4/raw-credential driver here — the creds
830
+ // contract is that the box never holds an object-store secret.
831
+ // ---------------------------------------------------------------------------
832
+
833
+ function joinKey(prefix, key) {
834
+ return `${prefix ?? ""}${key}`;
835
+ }
836
+
837
+ /** Plain unauthenticated HTTP object store — local stubs, public buckets. */
838
+ function httpStore(cfg) {
839
+ const base = cfg.baseUrl.replace(/\/+$/, "");
840
+ const url = (key) => `${base}/${joinKey(cfg.prefix, key)}`;
841
+ return {
842
+ async get(key, range) {
843
+ const headers = { ...(cfg.headers ?? {}) };
844
+ if (range) headers.Range = `bytes=${range.start}-${range.end}`;
845
+ const res = await httpRequest({ method: "GET", url: url(key), headers });
846
+ if (res.status === 404) throw new Error(`store: object not found: ${key}`);
847
+ if (res.status < 200 || res.status >= 300) {
848
+ throw new Error(
849
+ `store: GET ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
850
+ );
851
+ }
852
+ return res.body;
853
+ },
854
+ async getFile(key, filePath) {
855
+ const res = await httpGetFile({ url: url(key), filePath, headers: cfg.headers });
856
+ if (res.status === 404) throw new Error(`store: object not found: ${key}`);
857
+ if (res.status < 200 || res.status >= 300) {
858
+ throw new Error(
859
+ `store: GET ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
860
+ );
861
+ }
862
+ },
863
+ async head(key) {
864
+ const res = await httpRequest({ method: "HEAD", url: url(key), headers: cfg.headers });
865
+ if (res.status === 404) return false;
866
+ if (res.status < 200 || res.status >= 300) {
867
+ throw new Error(`store: HEAD ${key} failed: ${res.status}`);
868
+ }
869
+ return true;
870
+ },
871
+ async stat(key) {
872
+ const res = await httpRequest({ method: "HEAD", url: url(key), headers: cfg.headers });
873
+ if (res.status < 200 || res.status >= 300) {
874
+ throw new Error(`store: HEAD ${key} failed: ${res.status}`);
875
+ }
876
+ const size = Number(res.headers["content-length"]);
877
+ if (!Number.isFinite(size)) {
878
+ throw new Error(`store: HEAD ${key} returned no content-length`);
879
+ }
880
+ return size;
881
+ },
882
+ async put(key, data) {
883
+ const res = await httpRequest({
884
+ method: "PUT",
885
+ url: url(key),
886
+ headers: { "content-length": String(data.length), ...(cfg.headers ?? {}) },
887
+ body: data,
888
+ });
889
+ if (res.status < 200 || res.status >= 300) {
890
+ throw new Error(`store: PUT ${key} failed: ${res.status}`);
891
+ }
892
+ },
893
+ async putFile(key, filePath) {
894
+ const res = await httpPutFile({ url: url(key), headers: cfg.headers, filePath });
895
+ if (res.status < 200 || res.status >= 300) {
896
+ throw new Error(`store: PUT ${key} failed: ${res.status}`);
897
+ }
898
+ },
899
+ urlFor: url,
900
+ };
901
+ }
902
+
903
+ /**
904
+ * Platform-minted credentials without secrets on the box:
905
+ * - `post`: an S3 POST policy (url + form fields) — uploads land via
906
+ * multipart POST with `key` = minted prefix + object name.
907
+ * - `getBaseUrl`: a read base (public bucket URL or CDN) for GET/HEAD.
908
+ * - `putUrls`: per-object presigned PUTs (the OCI manifest — its key is
909
+ * known ahead of capture, so the platform can presign it exactly).
910
+ * - `getUrls`: per-object presigned GETs — the read counterpart to
911
+ * `putUrls`, for buckets without a public read base. SigV4 presigns are
912
+ * method-bound, so `head`/`stat` probe a `bytes=0-0` GET instead of HEAD.
913
+ */
914
+ function presignedStore(cfg) {
915
+ const readBase = cfg.getBaseUrl
916
+ ? httpStore({ baseUrl: cfg.getBaseUrl, prefix: cfg.prefix })
917
+ : null;
918
+ const post = cfg.post;
919
+ // `getUrlsUrl` carries the full URL set when it outgrew the op's argv:
920
+ // one presigned GET on a platform-written doc `{getUrls: {key: url}}`.
921
+ // Fetched lazily once, so capture-only ops never touch it.
922
+ let docUrls;
923
+ const loadGetUrls = async () => {
924
+ if (docUrls === undefined) {
925
+ docUrls = {};
926
+ if (cfg.getUrlsUrl) {
927
+ const res = await httpRequest({ method: "GET", url: cfg.getUrlsUrl });
928
+ if (res.status !== 200) {
929
+ throw new Error(
930
+ `grant doc fetch failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
931
+ );
932
+ }
933
+ const doc = JSON.parse(res.body.toString("utf8"));
934
+ docUrls = doc.getUrls ?? {};
935
+ }
936
+ }
937
+ };
938
+ const getUrl = (key) =>
939
+ cfg.getUrls?.[joinKey(cfg.prefix, key)] ??
940
+ cfg.getUrls?.[key] ??
941
+ docUrls?.[joinKey(cfg.prefix, key)] ??
942
+ docUrls?.[key];
943
+ /** `bytes=0-0` probe: exists + total size, without needing a signed HEAD. */
944
+ const probe = async (key) => {
945
+ const res = await httpRequest({
946
+ method: "GET",
947
+ url: getUrl(key),
948
+ headers: { Range: "bytes=0-0" },
949
+ });
950
+ if (res.status === 404) return { exists: false, size: 0 };
951
+ if (res.status !== 200 && res.status !== 206) {
952
+ throw new Error(
953
+ `presigned GET ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
954
+ );
955
+ }
956
+ const range = res.headers["content-range"];
957
+ const total =
958
+ (typeof range === "string" && range.match(/\/(\d+)\s*$/)?.[1]) ??
959
+ res.headers["content-length"];
960
+ const size = Number(total);
961
+ if (!Number.isFinite(size)) {
962
+ throw new Error(`presigned GET ${key} returned no object size`);
963
+ }
964
+ return { exists: true, size };
965
+ };
966
+ return {
967
+ async get(key, range) {
968
+ await loadGetUrls();
969
+ const url = getUrl(key);
970
+ if (url) {
971
+ const headers = {};
972
+ if (range) headers.Range = `bytes=${range.start}-${range.end}`;
973
+ const res = await httpRequest({ method: "GET", url, headers });
974
+ if (res.status === 404) throw new Error(`store: object not found: ${key}`);
975
+ if (res.status !== 200 && res.status !== 206) {
976
+ throw new Error(
977
+ `presigned GET ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
978
+ );
979
+ }
980
+ return res.body;
981
+ }
982
+ if (!readBase) {
983
+ throw new Error("presigned store: no getBaseUrl or getUrls for reads");
984
+ }
985
+ return readBase.get(key, range);
986
+ },
987
+ async getFile(key, filePath) {
988
+ await loadGetUrls();
989
+ const url = getUrl(key);
990
+ if (url) {
991
+ const res = await httpGetFile({ url, filePath });
992
+ if (res.status === 404) throw new Error(`store: object not found: ${key}`);
993
+ if (res.status < 200 || res.status >= 300) {
994
+ throw new Error(
995
+ `presigned GET ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
996
+ );
997
+ }
998
+ return;
999
+ }
1000
+ if (!readBase) {
1001
+ throw new Error("presigned store: no getBaseUrl or getUrls for reads");
1002
+ }
1003
+ return readBase.getFile(key, filePath);
1004
+ },
1005
+ async head(key) {
1006
+ await loadGetUrls();
1007
+ if (getUrl(key)) return (await probe(key)).exists;
1008
+ if (!readBase) return false;
1009
+ return readBase.head(key);
1010
+ },
1011
+ async stat(key) {
1012
+ await loadGetUrls();
1013
+ if (getUrl(key)) return (await probe(key)).size;
1014
+ if (!readBase) {
1015
+ throw new Error("presigned store: no getBaseUrl or getUrls for reads");
1016
+ }
1017
+ return readBase.stat(key);
1018
+ },
1019
+ async put(key, data) {
1020
+ const presigned =
1021
+ cfg.putUrls?.[joinKey(cfg.prefix, key)] ?? cfg.putUrls?.[key];
1022
+ if (presigned) {
1023
+ const res = await httpRequest({
1024
+ method: "PUT",
1025
+ url: presigned,
1026
+ headers: { "content-length": String(data.length) },
1027
+ body: data,
1028
+ });
1029
+ if (res.status < 200 || res.status >= 300) {
1030
+ throw new Error(
1031
+ `presigned PUT ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
1032
+ );
1033
+ }
1034
+ return;
1035
+ }
1036
+ if (!post) throw new Error(`presigned store: no upload path for ${key}`);
1037
+ const objectKey = joinKey(cfg.prefix, key);
1038
+ const formFields = { ...post.fields };
1039
+ formFields.key = formFields.key?.includes("${filename}")
1040
+ ? formFields.key.replaceAll("${filename}", objectKey)
1041
+ : objectKey;
1042
+ const boundary = `----daemond${crypto.randomBytes(12).toString("hex")}`;
1043
+ const parts = [];
1044
+ for (const [k, v] of Object.entries(formFields)) {
1045
+ parts.push(
1046
+ Buffer.from(
1047
+ `--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`,
1048
+ "utf8",
1049
+ ),
1050
+ );
1051
+ }
1052
+ parts.push(
1053
+ Buffer.from(
1054
+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${objectKey}"\r\nContent-Type: application/octet-stream\r\n\r\n`,
1055
+ "utf8",
1056
+ ),
1057
+ );
1058
+ parts.push(data);
1059
+ parts.push(Buffer.from(`\r\n--${boundary}--\r\n`, "utf8"));
1060
+ const body = Buffer.concat(parts);
1061
+ const res = await httpRequest({
1062
+ method: "POST",
1063
+ url: post.url,
1064
+ headers: {
1065
+ "content-type": `multipart/form-data; boundary=${boundary}`,
1066
+ "content-length": String(body.length),
1067
+ },
1068
+ body,
1069
+ });
1070
+ if (res.status < 200 || res.status >= 400) {
1071
+ throw new Error(
1072
+ `presigned POST ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
1073
+ );
1074
+ }
1075
+ },
1076
+ async putFile(key, filePath) {
1077
+ // Stream when the platform minted an exact PUT URL for this key.
1078
+ const presigned =
1079
+ cfg.putUrls?.[joinKey(cfg.prefix, key)] ?? cfg.putUrls?.[key];
1080
+ if (presigned) {
1081
+ const res = await httpPutFile({ url: presigned, filePath });
1082
+ if (res.status < 200 || res.status >= 300) {
1083
+ throw new Error(
1084
+ `presigned PUT ${key} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
1085
+ );
1086
+ }
1087
+ return;
1088
+ }
1089
+ // Layers go through the blob POST policy — the multipart body streams
1090
+ // (fields, then the file, then the closing boundary) so a multi-GB
1091
+ // layer never buffers whole.
1092
+ if (!post) throw new Error(`presigned store: no upload path for ${key}`);
1093
+ await postMultipartFile(post, joinKey(cfg.prefix, key), filePath);
1094
+ },
1095
+ urlFor: readBase?.urlFor,
1096
+ };
1097
+ }
1098
+
1099
+ /**
1100
+ * One S3 POST-policy upload of a file: multipart body streamed to the
1101
+ * request (form fields, file body, closing boundary), so blob uploads stay
1102
+ * O(1) memory. `objectKey` is the full prefixed key the policy's
1103
+ * starts-with condition covers.
1104
+ */
1105
+ function postMultipartFile(post, objectKey, filePath) {
1106
+ const formFields = { ...post.fields };
1107
+ formFields.key = formFields.key?.includes("${filename}")
1108
+ ? formFields.key.replaceAll("${filename}", objectKey)
1109
+ : objectKey;
1110
+ const boundary = `----daemond${crypto.randomBytes(12).toString("hex")}`;
1111
+ const headParts = [];
1112
+ for (const [k, v] of Object.entries(formFields)) {
1113
+ headParts.push(
1114
+ Buffer.from(
1115
+ `--${boundary}\r\nContent-Disposition: form-data; name="${k}"\r\n\r\n${v}\r\n`,
1116
+ "utf8",
1117
+ ),
1118
+ );
1119
+ }
1120
+ headParts.push(
1121
+ Buffer.from(
1122
+ `--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${objectKey}"\r\nContent-Type: application/octet-stream\r\n\r\n`,
1123
+ "utf8",
1124
+ ),
1125
+ );
1126
+ const head = Buffer.concat(headParts);
1127
+ const tail = Buffer.from(`\r\n--${boundary}--\r\n`, "utf8");
1128
+ const size = fs.statSync(filePath).size;
1129
+ return new Promise((resolve, reject) => {
1130
+ const url = new URL(post.url);
1131
+ const lib = url.protocol === "http:" ? http : https;
1132
+ const req = lib.request(
1133
+ url,
1134
+ {
1135
+ method: "POST",
1136
+ headers: {
1137
+ "content-type": `multipart/form-data; boundary=${boundary}`,
1138
+ "content-length": String(head.length + size + tail.length),
1139
+ },
1140
+ timeout: 300000,
1141
+ },
1142
+ (res) => {
1143
+ const chunks = [];
1144
+ res.on("data", (chunk) => chunks.push(chunk));
1145
+ res.on("end", () => {
1146
+ const status = res.statusCode ?? 0;
1147
+ const body = Buffer.concat(chunks);
1148
+ if (status < 200 || status >= 400) {
1149
+ reject(
1150
+ new Error(
1151
+ `presigned POST ${objectKey} failed: ${status} ${body.toString("utf8").slice(0, 200)}`,
1152
+ ),
1153
+ );
1154
+ return;
1155
+ }
1156
+ resolve({ status, headers: res.headers, body });
1157
+ });
1158
+ },
1159
+ );
1160
+ req.on("timeout", () => req.destroy(new Error("http post timeout")));
1161
+ req.on("error", reject);
1162
+ req.write(head);
1163
+ const fileStream = fs.createReadStream(filePath);
1164
+ fileStream.on("error", reject);
1165
+ fileStream.on("end", () => {
1166
+ req.write(tail);
1167
+ req.end();
1168
+ });
1169
+ fileStream.pipe(req, { end: false });
1170
+ });
1171
+ }
1172
+
1173
+ /**
1174
+ * A real directory as the object store: `{root}` is a mounted path (an
1175
+ * attached volume, a shared filesystem, or local dev scratch) and keys are
1176
+ * plain files under it. Range GETs read only the requested span.
1177
+ */
1178
+ function fsStore(cfg) {
1179
+ const keyPath = (key) => path.join(cfg.root, joinKey(cfg.prefix, key));
1180
+ return {
1181
+ async get(key, range) {
1182
+ const filePath = keyPath(key);
1183
+ if (!range) {
1184
+ try {
1185
+ return fs.readFileSync(filePath);
1186
+ } catch {
1187
+ throw new Error(`store: object not found: ${key}`);
1188
+ }
1189
+ }
1190
+ let fd;
1191
+ try {
1192
+ fd = fs.openSync(filePath, "r");
1193
+ } catch {
1194
+ throw new Error(`store: object not found: ${key}`);
1195
+ }
1196
+ try {
1197
+ const buf = Buffer.alloc(range.end - range.start + 1);
1198
+ const read = fs.readSync(fd, buf, 0, buf.length, range.start);
1199
+ return buf.subarray(0, read);
1200
+ } finally {
1201
+ fs.closeSync(fd);
1202
+ }
1203
+ },
1204
+ async getFile(key, filePath) {
1205
+ try {
1206
+ fs.copyFileSync(keyPath(key), filePath);
1207
+ } catch {
1208
+ throw new Error(`store: object not found: ${key}`);
1209
+ }
1210
+ },
1211
+ async head(key) {
1212
+ return fs.existsSync(keyPath(key));
1213
+ },
1214
+ async stat(key) {
1215
+ return fs.statSync(keyPath(key)).size;
1216
+ },
1217
+ async put(key, data) {
1218
+ const filePath = keyPath(key);
1219
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
1220
+ fs.writeFileSync(filePath, data);
1221
+ },
1222
+ async putFile(key, filePath) {
1223
+ const target = keyPath(key);
1224
+ fs.mkdirSync(path.dirname(target), { recursive: true });
1225
+ fs.copyFileSync(filePath, target);
1226
+ },
1227
+ urlFor: (key) => `file://${keyPath(key)}`,
1228
+ };
1229
+ }
1230
+
1231
+ function makeStore(cfg) {
1232
+ const store = cfg ?? {};
1233
+ if (store.kind === "fs" || typeof store.root === "string") {
1234
+ return fsStore(store);
1235
+ }
1236
+ if (store.kind === "http" || typeof store.baseUrl === "string") {
1237
+ return httpStore(store);
1238
+ }
1239
+ if (
1240
+ store.kind === "presigned" ||
1241
+ store.post ||
1242
+ store.putUrls ||
1243
+ store.getUrls ||
1244
+ store.getBaseUrl
1245
+ ) {
1246
+ return presignedStore(store);
1247
+ }
1248
+ throw new Error(
1249
+ "checkpoint: store config required (fs root | http baseUrl | presigned post/getBaseUrl/getUrls)",
1250
+ );
1251
+ }
1252
+
1253
+ // ---------------------------------------------------------------------------
1254
+ // OCI assembly
1255
+ // ---------------------------------------------------------------------------
1256
+
1257
+ const BLOBS_PREFIX = "blobs/";
1258
+ const MANIFESTS_PREFIX = "manifests/";
1259
+ const MANIFEST_MEDIA_TYPE = "application/vnd.oci.image.manifest.v1+json";
1260
+ const LAYER_MEDIA_TYPE = "application/vnd.oci.image.layer.v1.tar+gzip";
1261
+ const CONFIG_MEDIA_TYPE = "application/vnd.computesdk.checkpoint.config.v1+json";
1262
+
1263
+ /**
1264
+ * Writes one capture root's subtree as a deterministic tar.gz layer.
1265
+ * Streams through tmp files only — the plain-tar stream and the gzipped
1266
+ * blob are both hashed inline, so one pass yields the blob descriptor and
1267
+ * the uncompressed `diff_id` the OCI config carries.
1268
+ */
1269
+ async function writeLayer(input) {
1270
+ const tarPath = path.join(
1271
+ os.tmpdir(),
1272
+ `checkpoint-layer-${input.index}-${process.pid}.tar`,
1273
+ );
1274
+ const gzPath = `${tarPath}.gz`;
1275
+ const tarHash = crypto.createHash("sha256");
1276
+ const tarFd = fs.openSync(tarPath, "w");
1277
+ try {
1278
+ const sink = {
1279
+ write(buf) {
1280
+ tarHash.update(buf);
1281
+ fs.writeSync(tarFd, buf);
1282
+ },
1283
+ };
1284
+ const reporter = new ProgressReporter("capture", `tar:${input.root}`, input.entries.length);
1285
+ await writeTar(sink, input.entries, reporter);
1286
+ } finally {
1287
+ fs.closeSync(tarFd);
1288
+ }
1289
+ const gzHash = crypto.createHash("sha256");
1290
+ let gzBytes = 0;
1291
+ const gzFd = fs.openSync(gzPath, "w");
1292
+ try {
1293
+ const gunzip = zlib.createGzip({ level: 6 });
1294
+ gunzip.on("data", (chunk) => {
1295
+ gzHash.update(chunk);
1296
+ gzBytes += chunk.length;
1297
+ fs.writeSync(gzFd, chunk);
1298
+ });
1299
+ const done = new Promise((resolve, reject) => {
1300
+ gunzip.on("end", resolve);
1301
+ gunzip.on("error", reject);
1302
+ fs.createReadStream(tarPath).on("error", reject).pipe(gunzip);
1303
+ });
1304
+ await done;
1305
+ } finally {
1306
+ fs.closeSync(gzFd);
1307
+ }
1308
+ fs.rmSync(tarPath, { force: true });
1309
+ return {
1310
+ filePath: gzPath,
1311
+ sha256: gzHash.digest("hex"),
1312
+ size: gzBytes,
1313
+ diffId: `sha256:${tarHash.digest("hex")}`,
1314
+ };
1315
+ }
1316
+
1317
+ /** Tar path for an absolute fs path: root-relative, no leading slash. */
1318
+ function tarName(abs) {
1319
+ return abs.replace(/^\/+/, "");
1320
+ }
1321
+
1322
+ /** Index entry → tar entry. `filePath` set only for regular files. */
1323
+ function tarEntryFor(abs, entry) {
1324
+ const base = {
1325
+ name: tarName(abs),
1326
+ mode: entry.mode ?? 0o644,
1327
+ mtime: Math.floor((entry.mtime ?? 0) / 1000),
1328
+ };
1329
+ if (entry.type === "dir") {
1330
+ return { ...base, typeflag: "5", size: 0 };
1331
+ }
1332
+ if (entry.type === "symlink") {
1333
+ return { ...base, typeflag: "2", size: 0, link: entry.link ?? "", linkname: entry.link ?? "" };
1334
+ }
1335
+ return {
1336
+ ...base,
1337
+ typeflag: "0",
1338
+ size: entry.size ?? 0,
1339
+ filePath: abs,
1340
+ };
1341
+ }
1342
+
1343
+ /**
1344
+ * Builds the OCI image-config JSON — standard fields (architecture, os,
1345
+ * rootfs.diff_ids) plus a `computesdk` extension carrying the file index,
1346
+ * capture scope, and stats. The index is what lets restore select layers
1347
+ * and verify files without reading them.
1348
+ */
1349
+ function buildConfigBlob(config, diffIds) {
1350
+ const body = {
1351
+ architecture: config.arch,
1352
+ os: config.platform,
1353
+ created: config.createdAt,
1354
+ rootfs: { type: "layers", diff_ids: diffIds },
1355
+ computesdk: config,
1356
+ };
1357
+ return Buffer.from(JSON.stringify(body, null, 2), "utf8");
1358
+ }
1359
+
1360
+ function buildManifestBlob(input) {
1361
+ const body = {
1362
+ schemaVersion: 2,
1363
+ mediaType: MANIFEST_MEDIA_TYPE,
1364
+ config: {
1365
+ mediaType: CONFIG_MEDIA_TYPE,
1366
+ digest: `sha256:${input.config.sha256}`,
1367
+ size: input.config.size,
1368
+ },
1369
+ layers: input.layers.map((layer) => ({
1370
+ mediaType: LAYER_MEDIA_TYPE,
1371
+ digest: `sha256:${layer.sha256}`,
1372
+ size: layer.size,
1373
+ annotations: {
1374
+ "org.opencontainers.image.title": layer.root,
1375
+ "com.computesdk.checkpoint.root": layer.root,
1376
+ },
1377
+ })),
1378
+ annotations: {
1379
+ "org.opencontainers.image.title": `computesdk checkpoint ${input.checkpointId}`,
1380
+ "org.opencontainers.image.created": input.config.createdAt,
1381
+ "com.computesdk.checkpoint.id": input.checkpointId,
1382
+ ...(input.config.sourceSandboxId
1383
+ ? { "com.computesdk.checkpoint.sourceSandboxId": input.config.sourceSandboxId }
1384
+ : {}),
1385
+ ...(input.config.sourceProvider
1386
+ ? { "com.computesdk.checkpoint.sourceProvider": input.config.sourceProvider }
1387
+ : {}),
1388
+ },
1389
+ };
1390
+ return Buffer.from(JSON.stringify(body, null, 2), "utf8");
1391
+ }
1392
+
1393
+ /** Any digest format ("sha256:hex" or bare "hex") → the blob key tail. */
1394
+ function digestHex(digest) {
1395
+ return String(digest).startsWith("sha256:") ? String(digest).slice(7) : String(digest);
1396
+ }
1397
+
1398
+ /** Manifest from an inline object, a URL, or a local file path. */
1399
+ async function loadManifestRef(ref) {
1400
+ if (ref?.manifest) return ref.manifest;
1401
+ if (ref?.manifestUrl) {
1402
+ const res = await httpRequest({ method: "GET", url: ref.manifestUrl });
1403
+ if (res.status >= 200 && res.status < 300) {
1404
+ return JSON.parse(res.body.toString("utf8"));
1405
+ }
1406
+ return null;
1407
+ }
1408
+ if (ref?.manifestPath) {
1409
+ return JSON.parse(fs.readFileSync(ref.manifestPath, "utf8"));
1410
+ }
1411
+ return null;
1412
+ }
1413
+
1414
+ /** Config (file index) from inline, a blob via the store, a URL, or a file. */
1415
+ async function loadConfigRef(ref, store) {
1416
+ if (ref?.config) return ref.config;
1417
+ if (ref?.configPath) {
1418
+ return JSON.parse(fs.readFileSync(ref.configPath, "utf8"));
1419
+ }
1420
+ if (ref?.configUrl) {
1421
+ const res = await httpRequest({ method: "GET", url: ref.configUrl });
1422
+ if (res.status >= 200 && res.status < 300) {
1423
+ return JSON.parse(res.body.toString("utf8"));
1424
+ }
1425
+ return null;
1426
+ }
1427
+ if (ref?.configDigest && store) {
1428
+ const hex = digestHex(ref.configDigest);
1429
+ return JSON.parse((await store.get(`${BLOBS_PREFIX}${hex}`)).toString("utf8"));
1430
+ }
1431
+ return null;
1432
+ }
1433
+
1434
+ /**
1435
+ * The checkpoint's config for a manifest: fetch the manifest's config
1436
+ * descriptor's blob through the store. Returns {manifest, config}.
1437
+ */
1438
+ async function resolveConfig(store, manifest) {
1439
+ const digest = manifest?.config?.digest;
1440
+ if (!digest) throw new Error("checkpoint: manifest has no config descriptor");
1441
+ const config = JSON.parse(
1442
+ (await store.get(`${BLOBS_PREFIX}${digestHex(digest)}`)).toString("utf8"),
1443
+ );
1444
+ // Older callers may find the index nested under `computesdk`; flat accepts.
1445
+ return config.computesdk?.kind === "sandbox-checkpoint" ? config.computesdk : config;
1446
+ }
1447
+
1448
+ function parsePayload(argv) {
1449
+ const op = argv[2];
1450
+ if (!op) throw new Error("checkpoint: op required (scan|capture|restore|diff)");
1451
+ let raw = argv[3] ?? "{}";
1452
+ if (raw.startsWith("b64:")) {
1453
+ raw = Buffer.from(raw.slice(4), "base64").toString("utf8");
1454
+ }
1455
+ const args = JSON.parse(raw);
1456
+ return { op, args };
1457
+ }
1458
+
1459
+ // ---------------------------------------------------------------------------
1460
+ // Ops
1461
+ // ---------------------------------------------------------------------------
1462
+
1463
+ async function opScan(args) {
1464
+ const { config, missing } = await buildIndex({
1465
+ checkpointId: args.checkpointId,
1466
+ paths: args.paths ?? [],
1467
+ exclude: args.exclude,
1468
+ meta: args.meta,
1469
+ allowedRoots: args.allowedRoots,
1470
+ hashConcurrency: args.concurrency,
1471
+ });
1472
+ emitOpResult(args, { op: "scan", config, missing });
1473
+ }
1474
+
1475
+ async function opCapture(args) {
1476
+ const started = Date.now();
1477
+ const store = makeStore(args.store);
1478
+ const checkpointId = args.checkpointId;
1479
+ const { config, missing } = await buildIndex({
1480
+ checkpointId,
1481
+ paths: args.paths ?? [],
1482
+ exclude: args.exclude,
1483
+ meta: args.meta,
1484
+ allowedRoots: args.allowedRoots,
1485
+ hashConcurrency: args.concurrency,
1486
+ });
1487
+
1488
+ // One layer per capture root: group the index entries by their assigned
1489
+ // root and tar them in deterministic path order.
1490
+ const roots = config.capture.paths;
1491
+ const layerEntries = roots.map(() => []);
1492
+ for (const [abs, entry] of Object.entries(config.files)) {
1493
+ if (entry.layer >= 0) layerEntries[entry.layer].push(tarEntryFor(abs, entry));
1494
+ }
1495
+ for (const entries of layerEntries) {
1496
+ entries.sort((a, b) => a.name.localeCompare(b.name));
1497
+ }
1498
+
1499
+ // Dedup set: blobs the caller already knows (a parent checkpoint's
1500
+ // manifest, inline or via URL) plus optional store-side HEAD probes.
1501
+ const dedup = args.dedup ?? {};
1502
+ const known = new Set(dedup.knownBlobs ?? []);
1503
+ const parentManifest = await loadManifestRef(dedup.parentManifest);
1504
+ if (parentManifest) {
1505
+ for (const layer of parentManifest.layers ?? []) {
1506
+ if (layer.digest) known.add(digestHex(layer.digest));
1507
+ }
1508
+ if (parentManifest.config?.digest) {
1509
+ known.add(digestHex(parentManifest.config.digest));
1510
+ }
1511
+ }
1512
+
1513
+ // Write every non-empty layer, then upload only the blobs dedup missed.
1514
+ // Content identity is what dedup keys on: an unchanged subtree tars
1515
+ // byte-identically, so its sha256 reuses the parent's blob.
1516
+ const layers = [];
1517
+ const layerFiles = [];
1518
+ let candidates = [];
1519
+ let uploadedLayerBytes = 0;
1520
+ try {
1521
+ for (let i = 0; i < roots.length; i += 1) {
1522
+ const entries = layerEntries[i];
1523
+ if (entries.length === 0) continue;
1524
+ const layer = await writeLayer({ index: i, root: roots[i], entries });
1525
+ layers.push({ root: roots[i], ...layer, index: i });
1526
+ layerFiles.push(layer.filePath);
1527
+ if (!known.has(layer.sha256)) candidates.push(layer);
1528
+ }
1529
+
1530
+ if (dedup.checkHead !== false && candidates.length > 0) {
1531
+ const headReporter = new ProgressReporter("capture", "dedup-head", candidates.length);
1532
+ let headDone = 0;
1533
+ const stillNeeded = await mapLimit(candidates, 16, async (layer) => {
1534
+ const exists = await store.head(`${BLOBS_PREFIX}${layer.sha256}`);
1535
+ headDone += 1;
1536
+ headReporter.tick(headDone);
1537
+ return exists ? null : layer;
1538
+ });
1539
+ candidates = stillNeeded.filter((l) => l !== null);
1540
+ }
1541
+
1542
+ const uploadReporter = new ProgressReporter("capture", "upload-layers", candidates.length);
1543
+ let uploaded = 0;
1544
+ let uploadedBytes = 0;
1545
+ await mapLimit(candidates, args.uploadConcurrency ?? 4, async (layer) => {
1546
+ await store.putFile(`${BLOBS_PREFIX}${layer.sha256}`, layer.filePath);
1547
+ uploaded += 1;
1548
+ uploadedBytes += layer.size;
1549
+ uploadReporter.tick(uploaded, uploadedBytes);
1550
+ });
1551
+ uploadedLayerBytes = uploadedBytes;
1552
+ } finally {
1553
+ for (const filePath of layerFiles) fs.rmSync(filePath, { force: true });
1554
+ }
1555
+
1556
+ // The config blob (file index + capture metadata) is itself a CAS object,
1557
+ // uploaded under the same POST policy before the manifest commits.
1558
+ const diffIds = layers.map((layer) => layer.diffId);
1559
+ const configBlob = buildConfigBlob(config, diffIds);
1560
+ const configSha = sha256Buffer(configBlob);
1561
+ const configNeeded =
1562
+ !known.has(configSha) &&
1563
+ (dedup.checkHead === false ||
1564
+ !(await store.head(`${BLOBS_PREFIX}${configSha}`)));
1565
+ if (configNeeded) {
1566
+ await store.put(`${BLOBS_PREFIX}${configSha}`, configBlob);
1567
+ }
1568
+
1569
+ const manifestBlob = buildManifestBlob({
1570
+ checkpointId: config.checkpointId,
1571
+ config: { sha256: configSha, size: configBlob.length },
1572
+ layers,
1573
+ });
1574
+ const manifestKey = `${MANIFESTS_PREFIX}${config.checkpointId}.json`;
1575
+ // The manifest PUT is the commit point: blobs landed already, so a reader
1576
+ // that finds the manifest can resolve everything it names.
1577
+ const manifestPutUrl = args.manifestPutUrl;
1578
+ if (manifestPutUrl) {
1579
+ const res = await httpRequest({
1580
+ method: "PUT",
1581
+ url: manifestPutUrl,
1582
+ headers: {
1583
+ "content-length": String(manifestBlob.length),
1584
+ "content-type": MANIFEST_MEDIA_TYPE,
1585
+ },
1586
+ body: manifestBlob,
1587
+ });
1588
+ if (res.status < 200 || res.status >= 300) {
1589
+ throw new Error(
1590
+ `presigned PUT ${manifestKey} failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
1591
+ );
1592
+ }
1593
+ } else {
1594
+ await store.put(manifestKey, manifestBlob);
1595
+ }
1596
+
1597
+ emitOpResult(args, {
1598
+ op: "capture",
1599
+ checkpointId: config.checkpointId,
1600
+ manifestKey,
1601
+ manifestDigest: `sha256:${sha256Buffer(manifestBlob)}`,
1602
+ configDigest: `sha256:${configSha}`,
1603
+ layers: layers.map((layer) => ({
1604
+ root: layer.root,
1605
+ digest: `sha256:${layer.sha256}`,
1606
+ diffId: layer.diffId,
1607
+ size: layer.size,
1608
+ })),
1609
+ stats: config.stats,
1610
+ arch: config.arch,
1611
+ platform: config.platform,
1612
+ blobsTotal: layers.length + 1,
1613
+ blobsNew: candidates.length + (configNeeded ? 1 : 0),
1614
+ blobsDeduped: layers.length + 1 - candidates.length - (configNeeded ? 1 : 0),
1615
+ bytesNew: uploadedLayerBytes + (configNeeded ? configBlob.length : 0),
1616
+ missing,
1617
+ ms: Date.now() - started,
1618
+ });
1619
+ }
1620
+
1621
+ async function opRestore(args) {
1622
+ const started = Date.now();
1623
+ const store = args.store ? makeStore(args.store) : null;
1624
+ const checkpointId = String(args.checkpointId ?? "");
1625
+
1626
+ // The manifest object is small — a whole GET, presigned or through the
1627
+ // store. Layers follow by descriptor digest.
1628
+ const manifestUrl = args.manifestUrl ?? args.checkpointUrl;
1629
+ let manifest;
1630
+ if (manifestUrl) {
1631
+ const res = await httpRequest({ method: "GET", url: manifestUrl });
1632
+ if (res.status < 200 || res.status >= 300) {
1633
+ throw new Error(
1634
+ `restore: GET manifest failed: ${res.status} ${res.body.toString("utf8").slice(0, 200)}`,
1635
+ );
1636
+ }
1637
+ manifest = JSON.parse(res.body.toString("utf8"));
1638
+ } else if (store) {
1639
+ manifest = JSON.parse(
1640
+ (await store.get(`${MANIFESTS_PREFIX}${checkpointId}.json`)).toString("utf8"),
1641
+ );
1642
+ } else {
1643
+ throw new Error("restore: manifestUrl or store required");
1644
+ }
1645
+ if (!store) throw new Error("restore: store required for layer blobs");
1646
+
1647
+ const config = await resolveConfig(store, manifest);
1648
+
1649
+ const strictArch = args.strictArch === true;
1650
+ const archMismatch =
1651
+ config.arch !== process.arch || config.platform !== process.platform;
1652
+ if (archMismatch && strictArch) {
1653
+ throw new Error(
1654
+ `restore: arch mismatch — checkpoint is ${config.platform}/${config.arch}, box is ${process.platform}/${process.arch}`,
1655
+ );
1656
+ }
1657
+
1658
+ const includeGlobs = compileGlobs(args.include);
1659
+ const excludeGlobs = compileGlobs(args.exclude);
1660
+ const destDir = args.destDir;
1661
+ // Writing manifest paths verbatim is an explicit opt-in: a crafted index
1662
+ // carries attacker-chosen absolute paths, so identity restore must be
1663
+ // asked for — otherwise every write is confined under destDir.
1664
+ if (!destDir && args.writeAbsolute !== true) {
1665
+ throw new Error(
1666
+ "restore: destDir is required, or pass writeAbsolute: true to write manifest paths verbatim",
1667
+ );
1668
+ }
1669
+ // destDir replaces the capture root: with one capture path it is stripped
1670
+ // outright; with several, their common directory prefix is stripped so the
1671
+ // roots' distinguishing tails survive under destDir. Absolute paths still
1672
+ // identify files in the index — destDir only changes where they land.
1673
+ const capturePaths = (config.capture?.paths ?? []).filter(
1674
+ (p) => typeof p === "string",
1675
+ );
1676
+ const rootPrefix =
1677
+ capturePaths.length === 0
1678
+ ? "/"
1679
+ : capturePaths.length === 1
1680
+ ? capturePaths[0]
1681
+ : (() => {
1682
+ let prefix = capturePaths[0];
1683
+ for (const p of capturePaths.slice(1)) {
1684
+ while (!p.startsWith(prefix + "/") && prefix !== "/") {
1685
+ prefix = path.dirname(prefix);
1686
+ }
1687
+ if (!p.startsWith(prefix)) prefix = "/";
1688
+ }
1689
+ return prefix;
1690
+ })();
1691
+ const mapPath = (abs) => {
1692
+ if (!destDir) {
1693
+ const norm = path.normalize(abs);
1694
+ if (!path.isAbsolute(norm)) {
1695
+ throw new Error(`restore: non-absolute manifest path ${abs}`);
1696
+ }
1697
+ return norm;
1698
+ }
1699
+ const rel =
1700
+ abs === rootPrefix
1701
+ ? ""
1702
+ : abs.startsWith(rootPrefix + "/")
1703
+ ? abs.slice(rootPrefix.length + 1)
1704
+ : abs.replace(/^\/+/, "");
1705
+ if (rel === "") return destDir;
1706
+ const norm = path.normalize(rel);
1707
+ if (norm === ".." || norm.startsWith(`..${path.sep}`) || path.isAbsolute(norm)) {
1708
+ throw new Error(`restore: manifest path escapes destDir: ${abs}`);
1709
+ }
1710
+ return path.join(destDir, norm);
1711
+ };
1712
+
1713
+ // Symlink confinement: resolve destDir once, then before every write verify
1714
+ // the real path still lands under it — covers pre-existing symlinks in the
1715
+ // tree and links a crafted index had us create earlier in this restore.
1716
+ let resolvedRoot = null;
1717
+ if (destDir) {
1718
+ fs.mkdirSync(destDir, { recursive: true });
1719
+ resolvedRoot = fs.realpathSync(destDir);
1720
+ }
1721
+ const assertInsideRoot = (resolved, what) => {
1722
+ if (resolvedRoot && !isUnderRoot(resolvedRoot, resolved)) {
1723
+ throw new Error(`restore: ${what} escapes destDir via symlink (${resolved})`);
1724
+ }
1725
+ };
1726
+ const prepareParent = (dest) => {
1727
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
1728
+ if (resolvedRoot) assertInsideRoot(fs.realpathSync(path.dirname(dest)), dest);
1729
+ };
1730
+
1731
+ const allEntries = Object.entries(config.files ?? {});
1732
+ const selected = new Map();
1733
+ const dirModes = [];
1734
+ const wantedLayers = new Set();
1735
+ for (const [abs, entry] of allEntries) {
1736
+ const isDir = entry.type === "dir";
1737
+ if (includeGlobs.length > 0 && !includeGlobs.some((g) => g.regex.test(abs))) {
1738
+ continue;
1739
+ }
1740
+ if (excludeGlobs.length > 0 && excludeGlobs.some((g) => g.regex.test(abs))) {
1741
+ continue;
1742
+ }
1743
+ // Directories always extract when any of their subtree is selected —
1744
+ // they carry no blob cost, only perms.
1745
+ if (!isDir && entry.layer >= 0) wantedLayers.add(entry.layer);
1746
+ if (isDir) {
1747
+ dirModes.push([abs, entry]);
1748
+ continue;
1749
+ }
1750
+ selected.set(abs, entry);
1751
+ }
1752
+ // A dir whose subtree was excluded entirely still lands — dirs are cheap
1753
+ // and removing them selectively is a later refinement. Track wanted
1754
+ // layers for files/symlinks only.
1755
+
1756
+ const layerDescriptors = manifest.layers ?? [];
1757
+ const layerByIndex = new Map();
1758
+ // Layer indices in the index are positions in capture.paths order; the
1759
+ // manifest's layers[] skips empty roots, so rebuild the assignment by
1760
+ // matching the annotation's root back to its capture path.
1761
+ const rootToLayer = new Map();
1762
+ layerDescriptors.forEach((desc, i) => {
1763
+ const root = desc.annotations?.["com.computesdk.checkpoint.root"];
1764
+ if (root !== undefined) rootToLayer.set(root, i);
1765
+ });
1766
+ for (const pathIdx of wantedLayers) {
1767
+ const root = capturePaths[pathIdx];
1768
+ const descIdx = rootToLayer.get(root);
1769
+ if (descIdx !== undefined) layerByIndex.set(descIdx, layerDescriptors[descIdx]);
1770
+ }
1771
+
1772
+ const failures = [];
1773
+ const reporter = new ProgressReporter("restore", "layers", layerByIndex.size);
1774
+ let layersPulled = 0;
1775
+ let layersSkipped = layerDescriptors.length - layerByIndex.size;
1776
+ let filesWritten = 0;
1777
+ let fetchedBytes = 0;
1778
+ const deferredDirs = [];
1779
+
1780
+ for (const [descIdx, desc] of [...layerByIndex.entries()].sort((a, b) => a[0] - b[0])) {
1781
+ const hex = digestHex(desc.digest);
1782
+ const tmp = path.join(
1783
+ os.tmpdir(),
1784
+ `checkpoint-layer-${process.pid}-${descIdx}.tar.gz`,
1785
+ );
1786
+ try {
1787
+ if (store.getFile) {
1788
+ await store.getFile(`${BLOBS_PREFIX}${hex}`, tmp);
1789
+ } else {
1790
+ fs.writeFileSync(tmp, await store.get(`${BLOBS_PREFIX}${hex}`));
1791
+ }
1792
+ const actual = await sha256File(tmp);
1793
+ if (actual !== hex) {
1794
+ throw new Error(`sha256 mismatch on layer ${hex}: got ${actual}`);
1795
+ }
1796
+ const tarTmp = `${tmp}.tar`;
1797
+ await new Promise((resolve, reject) => {
1798
+ const out = fs.createWriteStream(tarTmp);
1799
+ fs.createReadStream(tmp)
1800
+ .on("error", reject)
1801
+ .pipe(zlib.createGunzip())
1802
+ .on("error", reject)
1803
+ .pipe(out)
1804
+ .on("error", reject)
1805
+ .on("finish", resolve);
1806
+ });
1807
+ const captureRoot = desc.annotations?.["com.computesdk.checkpoint.root"];
1808
+ const rootIdx = capturePaths.indexOf(captureRoot);
1809
+ await readTar(tarTmp, async (entry, body) => {
1810
+ const abs = `/${entry.name}`;
1811
+ const indexEntry = config.files?.[abs];
1812
+ const wanted =
1813
+ indexEntry && indexEntry.layer === rootIdx && selected.has(abs);
1814
+ const dirWanted =
1815
+ entry.typeflag === "5" && indexEntry && indexEntry.layer === rootIdx;
1816
+ if (!wanted && !dirWanted) {
1817
+ await body.skip();
1818
+ return;
1819
+ }
1820
+ try {
1821
+ const dest = mapPath(abs);
1822
+ if (entry.typeflag === "5") {
1823
+ fs.mkdirSync(dest, { recursive: true });
1824
+ if (resolvedRoot) assertInsideRoot(fs.realpathSync(dest), dest);
1825
+ deferredDirs.push([dest, indexEntry]);
1826
+ await body.skip();
1827
+ return;
1828
+ }
1829
+ if (entry.typeflag === "2") {
1830
+ prepareParent(dest);
1831
+ try {
1832
+ if (fs.lstatSync(dest).isSymbolicLink()) fs.rmSync(dest, { force: true });
1833
+ } catch {}
1834
+ fs.symlinkSync(entry.linkname ?? indexEntry.link ?? "", dest);
1835
+ await body.skip();
1836
+ filesWritten += 1;
1837
+ return;
1838
+ }
1839
+ // Regular file: stream to dest while hashing — verification is
1840
+ // against the index sha, not the layer digest (already checked).
1841
+ prepareParent(dest);
1842
+ try {
1843
+ if (fs.lstatSync(dest).isSymbolicLink()) fs.rmSync(dest, { force: true });
1844
+ } catch {}
1845
+ const sha = await body.extract(dest);
1846
+ if (indexEntry.sha && sha !== indexEntry.sha) {
1847
+ fs.rmSync(dest, { force: true });
1848
+ throw new Error(`sha256 mismatch: ${abs}`);
1849
+ }
1850
+ try {
1851
+ fs.chmodSync(dest, (indexEntry.mode ?? entry.mode) & 0o7777);
1852
+ } catch {}
1853
+ try {
1854
+ const mtime = new Date(indexEntry.mtime ?? entry.mtime * 1000);
1855
+ fs.utimesSync(dest, new Date(), mtime);
1856
+ } catch {}
1857
+ fetchedBytes += entry.size;
1858
+ filesWritten += 1;
1859
+ } catch (err) {
1860
+ failures.push({
1861
+ path: abs,
1862
+ error: err instanceof Error ? err.message : String(err),
1863
+ });
1864
+ await body.skip().catch(() => {});
1865
+ }
1866
+ });
1867
+ fs.rmSync(tarTmp, { force: true });
1868
+ layersPulled += 1;
1869
+ reporter.tick(layersPulled);
1870
+ } catch (err) {
1871
+ failures.push({
1872
+ key: `${BLOBS_PREFIX}${hex}`,
1873
+ error: err instanceof Error ? err.message : String(err),
1874
+ });
1875
+ } finally {
1876
+ fs.rmSync(tmp, { force: true });
1877
+ }
1878
+ }
1879
+
1880
+ // chmod dirs deepest-first: a read-only parent mode would otherwise block
1881
+ // its own empty children from being created.
1882
+ for (const [dest, entry] of deferredDirs.sort((a, b) => b[0].length - a[0].length)) {
1883
+ try {
1884
+ fs.chmodSync(dest, (entry.mode ?? 0o755) & 0o7777);
1885
+ } catch {}
1886
+ }
1887
+
1888
+ emitOpResult(args, {
1889
+ op: "restore",
1890
+ checkpointId: config.checkpointId,
1891
+ files: filesWritten,
1892
+ bytes: fetchedBytes,
1893
+ layersPulled,
1894
+ layersSkipped,
1895
+ failures,
1896
+ archMismatch,
1897
+ cwd: config.cwd,
1898
+ env: config.env,
1899
+ ms: Date.now() - started,
1900
+ });
1901
+ // A partial restore is a failed restore — exit non-zero so job control and
1902
+ // callers gating on exit status see it (failures[] carries the detail).
1903
+ if (failures.length > 0) process.exitCode = 1;
1904
+ }
1905
+
1906
+ async function opDiff(args) {
1907
+ const store = args.store ? makeStore(args.store) : null;
1908
+ const load = async (ref) => {
1909
+ const config = await loadConfigRef(ref, store);
1910
+ if (config) return config;
1911
+ const manifest = await loadManifestRef(ref);
1912
+ if (manifest) return resolveConfig(store, manifest);
1913
+ return null;
1914
+ };
1915
+ const a = await load(args.a);
1916
+ const b = await load(args.b);
1917
+ if (!a || !b) {
1918
+ throw new Error(
1919
+ "diff: each side needs config/configUrl/configPath or manifest/manifestUrl/manifestPath",
1920
+ );
1921
+ }
1922
+ emitOpResult(args, { op: "diff", diff: diffIndexes(a, b) });
1923
+ }
1924
+
1925
+ async function main() {
1926
+ const { op, args } = parsePayload(process.argv);
1927
+ switch (op) {
1928
+ case "scan":
1929
+ return opScan(args);
1930
+ case "capture":
1931
+ return opCapture(args);
1932
+ case "restore":
1933
+ return opRestore(args);
1934
+ case "diff":
1935
+ return opDiff(args);
1936
+ default:
1937
+ throw new Error(`checkpoint: unknown op ${op}`);
1938
+ }
1939
+ }
1940
+
1941
+ // The daemon installs this file under an arbitrary name (e.g. checkpoint.cjs),
1942
+ // so match by require.main identity, not by filename.
1943
+ const invokedDirectly =
1944
+ typeof require === "function" &&
1945
+ typeof module === "object" &&
1946
+ require.main === module;
1947
+ if (invokedDirectly) {
1948
+ main().catch(emitError);
1949
+ }