@foldrun/core 18.1.0 → 18.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -93,6 +93,23 @@ export declare function untrustedTextFindings(text: string): {
93
93
  line: number;
94
94
  message: string;
95
95
  }[];
96
+ /**
97
+ * Secrets in files about to LEAVE this machine (a snapshot upload, Part B3,
98
+ * 10 Nov 2026): every file, with nothing the files themselves can turn off —
99
+ * no foldrun-ignore, no vendored-path skip (Codex: a repo comment must not
100
+ * silence a key on its way out). A file that is not text (a NUL in its
101
+ * first 8 KB) cannot be read for secrets and is returned as unscanned, for
102
+ * the caller to say so rather than pass it quietly.
103
+ */
104
+ export declare function uploadSecretFindings(files: ScanFile[]): {
105
+ findings: {
106
+ rule: string;
107
+ file: string;
108
+ line?: number;
109
+ message: string;
110
+ }[];
111
+ unscanned: string[];
112
+ };
96
113
  /** The known field a key was probably meant to be, or null. */
97
114
  export declare function nearestField(key: string, known: readonly string[]): string | null;
98
115
  /** What a run leaves in an agent's folder — the Claude CLI's `.cache/` logs,
package/dist/src/scan.js CHANGED
@@ -598,6 +598,33 @@ export function untrustedTextFindings(text) {
598
598
  scanContent({ path: "untrusted", content: text }, text.split(/\r?\n/), (rule, _file, line, _text, message) => out.push({ rule, line: line ?? 0, message }), true);
599
599
  return out;
600
600
  }
601
+ /**
602
+ * Secrets in files about to LEAVE this machine (a snapshot upload, Part B3,
603
+ * 10 Nov 2026): every file, with nothing the files themselves can turn off —
604
+ * no foldrun-ignore, no vendored-path skip (Codex: a repo comment must not
605
+ * silence a key on its way out). A file that is not text (a NUL in its
606
+ * first 8 KB) cannot be read for secrets and is returned as unscanned, for
607
+ * the caller to say so rather than pass it quietly.
608
+ */
609
+ export function uploadSecretFindings(files) {
610
+ const findings = [];
611
+ const unscanned = [];
612
+ const seen = new Set();
613
+ for (const f of files) {
614
+ if (f.content.slice(0, 8000).includes("\u0000")) {
615
+ unscanned.push(f.path);
616
+ continue;
617
+ }
618
+ scanSecrets(f, f.content.split(/\r?\n/), (rule, file, line, _text, message) => {
619
+ const key = `${rule}\0${file}\0${line ?? ""}`;
620
+ if (seen.has(key))
621
+ return;
622
+ seen.add(key);
623
+ findings.push({ rule, file, ...(line ? { line } : {}), message });
624
+ });
625
+ }
626
+ return { findings, unscanned };
627
+ }
601
628
  /** The text hidden in tag characters: each is U+E0000 + an ASCII code. */
602
629
  function decodeTags(s) {
603
630
  let out = "";
@@ -0,0 +1,37 @@
1
+ export interface SnapshotEntry {
2
+ /** Relative, `/`-separated. */
3
+ path: string;
4
+ /** 0o644 or 0o755. */
5
+ mode: number;
6
+ content: Buffer;
7
+ }
8
+ export interface SnapshotLimits {
9
+ maxFiles: number;
10
+ maxFileBytes: number;
11
+ maxTotalBytes: number;
12
+ maxCompressedBytes: number;
13
+ }
14
+ export declare const SNAPSHOT_LIMITS: SnapshotLimits;
15
+ /** Why an archive was refused, in words a person can act on. */
16
+ export declare class SnapshotRefused extends Error {
17
+ constructor(message: string);
18
+ }
19
+ /** The path rules, for the packer to check before it packs, and the reader after. */
20
+ export declare function snapshotPathProblem(p: string): string | null;
21
+ /** A deterministic gzipped tar of these files (directories are implied). */
22
+ export declare function packSnapshot(entries: SnapshotEntry[], limits?: SnapshotLimits): {
23
+ archive: Buffer;
24
+ sha256: string;
25
+ files: number;
26
+ bytes: number;
27
+ };
28
+ /**
29
+ * Unpack an archive a stranger sent, under every rule above. Throws
30
+ * SnapshotRefused naming the first thing wrong; nothing is written anywhere —
31
+ * the caller gets the entries to store.
32
+ */
33
+ export declare function unpackSnapshot(archive: Buffer, limits?: SnapshotLimits): {
34
+ entries: SnapshotEntry[];
35
+ sha256: string;
36
+ bytes: number;
37
+ };
@@ -0,0 +1,255 @@
1
+ // Snapshot archives (Part B3, 10 Nov 2026): a folder from the user's machine,
2
+ // as one gzipped tar, for an agent on foldrun to work on.
3
+ //
4
+ // One writer and one strict reader, here, so the CLI (which packs) and the
5
+ // platform (which unpacks what a stranger sent) hold the same rules:
6
+ //
7
+ // - only regular files and directories — no links, devices, FIFOs, sparse
8
+ // files, PAX or GNU long-name headers (each a way to make a path mean
9
+ // something other than it says);
10
+ // - every path relative, `/`-separated, no `.`/`..`/empty segment, no
11
+ // backslash, NUL or control character, ≤ 255 bytes and ≤ 32 levels;
12
+ // - no path twice, also when only its case differs, and no file where a
13
+ // directory is (`a` and `a/b`);
14
+ // - limits on file count, one file's size and the whole, enforced while
15
+ // reading — before a byte past them is held;
16
+ // - header checksums verified; nothing after the end-of-archive blocks;
17
+ // - modes are 0644 or 0755 (the owner's exec bit), nothing else kept.
18
+ //
19
+ // The writer is deterministic: entries sorted, mtime 0, uid/gid 0, no names
20
+ // — the same folder is the same bytes, so a snapshot is known by its hash.
21
+ import crypto from "node:crypto";
22
+ import zlib from "node:zlib";
23
+ export const SNAPSHOT_LIMITS = {
24
+ maxFiles: 20_000,
25
+ maxFileBytes: 10 * 1024 * 1024,
26
+ maxTotalBytes: 200 * 1024 * 1024,
27
+ maxCompressedBytes: 50 * 1024 * 1024,
28
+ };
29
+ const MAX_PATH = 255;
30
+ const MAX_DEPTH = 32;
31
+ /** Why an archive was refused, in words a person can act on. */
32
+ export class SnapshotRefused extends Error {
33
+ constructor(message) {
34
+ super(message);
35
+ this.name = "SnapshotRefused";
36
+ }
37
+ }
38
+ /** The path rules, for the packer to check before it packs, and the reader after. */
39
+ export function snapshotPathProblem(p) {
40
+ if (!p)
41
+ return "an empty path";
42
+ if (Buffer.byteLength(p) > MAX_PATH)
43
+ return `a path longer than ${MAX_PATH} bytes`;
44
+ if (p.startsWith("/"))
45
+ return "an absolute path";
46
+ if (/[\u0000-\u001f\u007f\\]/.test(p))
47
+ return "a backslash or control character in a path";
48
+ const parts = p.split("/");
49
+ if (parts.length > MAX_DEPTH)
50
+ return `a path deeper than ${MAX_DEPTH} folders`;
51
+ if (parts.some((s) => s === "" || s === "." || s === ".."))
52
+ return "an empty, `.` or `..` segment";
53
+ return null;
54
+ }
55
+ /**
56
+ * The set of paths in one archive, with every clash rule in one place for the
57
+ * writer and the reader alike (Codex: the writer packed what the reader then
58
+ * refused). Case-insensitive throughout: `A` and `a/b` cannot both exist on
59
+ * a case-insensitive filesystem, so neither may be here.
60
+ */
61
+ class PathSet {
62
+ kinds = new Map();
63
+ parents = new Set();
64
+ add(p, isDir) {
65
+ const key = p.toLowerCase();
66
+ if (this.kinds.has(key))
67
+ throw new SnapshotRefused(`${p}: there twice (paths may not differ only by case)`);
68
+ const segs = key.split("/");
69
+ for (let i = 1; i < segs.length; i++) {
70
+ const parent = segs.slice(0, i).join("/");
71
+ if (this.kinds.get(parent) === "file")
72
+ throw new SnapshotRefused(`${p}: inside ${p.split("/").slice(0, i).join("/")}, which is a file`);
73
+ }
74
+ if (!isDir && this.parents.has(key))
75
+ throw new SnapshotRefused(`${p}: a file where another entry makes it a folder`);
76
+ this.kinds.set(key, isDir ? "dir" : "file");
77
+ for (let i = 1; i < segs.length; i++)
78
+ this.parents.add(segs.slice(0, i).join("/"));
79
+ }
80
+ }
81
+ // ------------------------------------------------------------------ writer
82
+ function octal(n, width) {
83
+ return n.toString(8).padStart(width - 1, "0") + "\0";
84
+ }
85
+ function header(path, size, mode, type) {
86
+ const h = Buffer.alloc(512, 0);
87
+ // ustar: name (100) and prefix (155); split at a "/" when it is long.
88
+ let name = path;
89
+ let prefix = "";
90
+ if (Buffer.byteLength(name) > 100) {
91
+ const cut = path.lastIndexOf("/", path.length - 1);
92
+ let at = -1;
93
+ for (let i = cut; i > 0; i = path.lastIndexOf("/", i - 1)) {
94
+ if (Buffer.byteLength(path.slice(i + 1)) <= 100 && Buffer.byteLength(path.slice(0, i)) <= 155) {
95
+ at = i;
96
+ break;
97
+ }
98
+ }
99
+ if (at < 0)
100
+ throw new SnapshotRefused(`${path}: too long to store`);
101
+ prefix = path.slice(0, at);
102
+ name = path.slice(at + 1);
103
+ }
104
+ h.write(name, 0, 100, "utf8");
105
+ h.write(octal(mode, 8), 100, 8, "ascii");
106
+ h.write(octal(0, 8), 108, 8, "ascii"); // uid
107
+ h.write(octal(0, 8), 116, 8, "ascii"); // gid
108
+ h.write(octal(size, 12), 124, 12, "ascii");
109
+ h.write(octal(0, 12), 136, 12, "ascii"); // mtime
110
+ h.write(" ", 148, 8, "ascii"); // checksum placeholder
111
+ h.write(type, 156, 1, "ascii");
112
+ h.write("ustar\u000000", 257, 8, "ascii");
113
+ h.write(prefix, 345, 155, "utf8");
114
+ let sum = 0;
115
+ for (const b of h)
116
+ sum += b;
117
+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii");
118
+ return h;
119
+ }
120
+ /** A deterministic gzipped tar of these files (directories are implied). */
121
+ export function packSnapshot(entries, limits = SNAPSHOT_LIMITS) {
122
+ if (entries.length > limits.maxFiles)
123
+ throw new SnapshotRefused(`${entries.length} files — the most is ${limits.maxFiles}`);
124
+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
125
+ const parts = [];
126
+ let total = 0;
127
+ const paths = new PathSet();
128
+ for (const e of sorted) {
129
+ const problem = snapshotPathProblem(e.path);
130
+ if (problem)
131
+ throw new SnapshotRefused(`${e.path}: ${problem}`);
132
+ paths.add(e.path, false);
133
+ if (e.content.length > limits.maxFileBytes)
134
+ throw new SnapshotRefused(`${e.path}: ${e.content.length} bytes — the most for one file is ${limits.maxFileBytes}`);
135
+ total += e.content.length;
136
+ if (total > limits.maxTotalBytes)
137
+ throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
138
+ parts.push(header(e.path, e.content.length, e.mode === 0o755 ? 0o755 : 0o644, "0"));
139
+ parts.push(e.content);
140
+ const pad = (512 - (e.content.length % 512)) % 512;
141
+ if (pad)
142
+ parts.push(Buffer.alloc(pad, 0));
143
+ }
144
+ parts.push(Buffer.alloc(1024, 0));
145
+ const archive = zlib.gzipSync(Buffer.concat(parts), { level: 9, mtime: 0 });
146
+ // gzip's header carries an mtime and an OS byte; both fixed, so the bytes are the folder's alone.
147
+ archive.writeUInt32LE(0, 4);
148
+ archive[9] = 255;
149
+ if (archive.length > limits.maxCompressedBytes)
150
+ throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
151
+ return { archive, sha256: crypto.createHash("sha256").update(archive).digest("hex"), files: sorted.length, bytes: total };
152
+ }
153
+ // ------------------------------------------------------------------ reader
154
+ function readString(b, start, len) {
155
+ const s = b.subarray(start, start + len);
156
+ const nul = s.indexOf(0);
157
+ return s.subarray(0, nul < 0 ? len : nul).toString("utf8");
158
+ }
159
+ function readOctal(b, start, len, what) {
160
+ const raw = readString(b, start, len).trim();
161
+ if (raw === "")
162
+ return 0;
163
+ if (!/^[0-7]+$/.test(raw))
164
+ throw new SnapshotRefused(`a header's ${what} is not a number`);
165
+ const n = parseInt(raw, 8);
166
+ if (!Number.isSafeInteger(n))
167
+ throw new SnapshotRefused(`a header's ${what} is out of range`);
168
+ return n;
169
+ }
170
+ /**
171
+ * Unpack an archive a stranger sent, under every rule above. Throws
172
+ * SnapshotRefused naming the first thing wrong; nothing is written anywhere —
173
+ * the caller gets the entries to store.
174
+ */
175
+ export function unpackSnapshot(archive, limits = SNAPSHOT_LIMITS) {
176
+ if (archive.length > limits.maxCompressedBytes)
177
+ throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
178
+ let tar;
179
+ try {
180
+ // The tar is at most the files, their headers and padding: past that, a bomb.
181
+ const ceiling = limits.maxTotalBytes + (limits.maxFiles + 2) * 1024 + 1024;
182
+ tar = zlib.gunzipSync(archive, { maxOutputLength: ceiling });
183
+ }
184
+ catch (err) {
185
+ const code = err.code;
186
+ throw new SnapshotRefused(code === "ERR_BUFFER_TOO_LARGE" || /larger than/i.test(String(err.message)) ? `it unpacks past ${limits.maxTotalBytes} bytes` : "it is not a gzip archive");
187
+ }
188
+ const entries = [];
189
+ const paths = new PathSet();
190
+ // Every entry counts against maxFiles, folders too, before its path is
191
+ // recorded: an archive of folders alone would otherwise pass every limit
192
+ // and fill memory with paths (Codex). Our writer emits no folder entries.
193
+ let count = 0;
194
+ let total = 0;
195
+ let off = 0;
196
+ let ended = false;
197
+ while (off + 512 <= tar.length) {
198
+ const h = tar.subarray(off, off + 512);
199
+ if (h.every((x) => x === 0)) {
200
+ const next = tar.subarray(off + 512, off + 1024);
201
+ if (next.length === 512 && next.every((x) => x === 0)) {
202
+ ended = true;
203
+ off += 1024;
204
+ break;
205
+ }
206
+ throw new SnapshotRefused("a lone empty block before the end");
207
+ }
208
+ let sum = 0;
209
+ for (let i = 0; i < 512; i++)
210
+ sum += i >= 148 && i < 156 ? 32 : h[i];
211
+ if (readOctal(h, 148, 8, "checksum") !== sum)
212
+ throw new SnapshotRefused("a header's checksum is wrong");
213
+ if (readString(h, 257, 6) !== "ustar")
214
+ throw new SnapshotRefused("not a ustar archive");
215
+ const type = String.fromCharCode(h[156]);
216
+ const name = readString(h, 0, 100);
217
+ const prefix = readString(h, 345, 155);
218
+ const p0 = prefix ? `${prefix}/${name}` : name;
219
+ const isDir = type === "5";
220
+ const p = isDir ? p0.replace(/\/+$/, "") : p0;
221
+ if (type !== "0" && type !== "\0" && !isDir) {
222
+ const what = { "1": "a hard link", "2": "a symbolic link", "3": "a character device", "4": "a block device", "6": "a FIFO", x: "an extended (PAX) header", g: "a global PAX header", L: "a GNU long name", K: "a GNU long link", S: "a sparse file" }[type] ?? `an entry of type ${JSON.stringify(type)}`;
223
+ throw new SnapshotRefused(`${p || "(unnamed)"}: ${what} — only plain files and folders`);
224
+ }
225
+ const problem = snapshotPathProblem(p);
226
+ if (problem)
227
+ throw new SnapshotRefused(`${p}: ${problem}`);
228
+ const size = readOctal(h, 124, 12, "size");
229
+ if (isDir && size !== 0)
230
+ throw new SnapshotRefused(`${p}: a folder with a size`);
231
+ if (size > limits.maxFileBytes)
232
+ throw new SnapshotRefused(`${p}: ${size} bytes — the most for one file is ${limits.maxFileBytes}`);
233
+ if (++count > limits.maxFiles)
234
+ throw new SnapshotRefused(`more than ${limits.maxFiles} entries`);
235
+ paths.add(p, isDir);
236
+ off += 512;
237
+ if (!isDir) {
238
+ if (off + size > tar.length)
239
+ throw new SnapshotRefused(`${p}: cut short`);
240
+ total += size;
241
+ if (total > limits.maxTotalBytes)
242
+ throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
243
+ if (entries.length + 1 > limits.maxFiles)
244
+ throw new SnapshotRefused(`more than ${limits.maxFiles} files`);
245
+ const mode = readOctal(h, 100, 8, "mode");
246
+ entries.push({ path: p, mode: mode & 0o100 ? 0o755 : 0o644, content: Buffer.from(tar.subarray(off, off + size)) });
247
+ off += size + ((512 - (size % 512)) % 512);
248
+ }
249
+ }
250
+ if (!ended)
251
+ throw new SnapshotRefused("no end-of-archive marker");
252
+ if (tar.subarray(off).some((x) => x !== 0))
253
+ throw new SnapshotRefused("data after the end of the archive");
254
+ return { entries, sha256: crypto.createHash("sha256").update(archive).digest("hex"), bytes: total };
255
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foldrun/core",
3
- "version": "18.1.0",
3
+ "version": "18.2.0",
4
4
  "description": "Agents are just folders. The format, the runner, the checks.",
5
5
  "license": "FSL-1.1-ALv2",
6
6
  "type": "module",
@@ -33,7 +33,8 @@
33
33
  "./providers",
34
34
  "./subagents",
35
35
  "./tool-names",
36
- "./scan"
36
+ "./scan",
37
+ "./snapshot-archive"
37
38
  ]
38
39
  },
39
40
  "main": "./dist/index.js",
package/src/scan.ts CHANGED
@@ -679,6 +679,33 @@ export function untrustedTextFindings(text: string): { rule: string; line: numbe
679
679
  return out;
680
680
  }
681
681
 
682
+ /**
683
+ * Secrets in files about to LEAVE this machine (a snapshot upload, Part B3,
684
+ * 10 Nov 2026): every file, with nothing the files themselves can turn off —
685
+ * no foldrun-ignore, no vendored-path skip (Codex: a repo comment must not
686
+ * silence a key on its way out). A file that is not text (a NUL in its
687
+ * first 8 KB) cannot be read for secrets and is returned as unscanned, for
688
+ * the caller to say so rather than pass it quietly.
689
+ */
690
+ export function uploadSecretFindings(files: ScanFile[]): { findings: { rule: string; file: string; line?: number; message: string }[]; unscanned: string[] } {
691
+ const findings: { rule: string; file: string; line?: number; message: string }[] = [];
692
+ const unscanned: string[] = [];
693
+ const seen = new Set<string>();
694
+ for (const f of files) {
695
+ if (f.content.slice(0, 8000).includes("\u0000")) {
696
+ unscanned.push(f.path);
697
+ continue;
698
+ }
699
+ scanSecrets(f, f.content.split(/\r?\n/), (rule, file, line, _text, message) => {
700
+ const key = `${rule}\0${file}\0${line ?? ""}`;
701
+ if (seen.has(key)) return;
702
+ seen.add(key);
703
+ findings.push({ rule, file, ...(line ? { line } : {}), message });
704
+ });
705
+ }
706
+ return { findings, unscanned };
707
+ }
708
+
682
709
  /** The text hidden in tag characters: each is U+E0000 + an ASCII code. */
683
710
  function decodeTags(s: string): string {
684
711
  let out = "";
@@ -0,0 +1,249 @@
1
+ // Snapshot archives (Part B3, 10 Nov 2026): a folder from the user's machine,
2
+ // as one gzipped tar, for an agent on foldrun to work on.
3
+ //
4
+ // One writer and one strict reader, here, so the CLI (which packs) and the
5
+ // platform (which unpacks what a stranger sent) hold the same rules:
6
+ //
7
+ // - only regular files and directories — no links, devices, FIFOs, sparse
8
+ // files, PAX or GNU long-name headers (each a way to make a path mean
9
+ // something other than it says);
10
+ // - every path relative, `/`-separated, no `.`/`..`/empty segment, no
11
+ // backslash, NUL or control character, ≤ 255 bytes and ≤ 32 levels;
12
+ // - no path twice, also when only its case differs, and no file where a
13
+ // directory is (`a` and `a/b`);
14
+ // - limits on file count, one file's size and the whole, enforced while
15
+ // reading — before a byte past them is held;
16
+ // - header checksums verified; nothing after the end-of-archive blocks;
17
+ // - modes are 0644 or 0755 (the owner's exec bit), nothing else kept.
18
+ //
19
+ // The writer is deterministic: entries sorted, mtime 0, uid/gid 0, no names
20
+ // — the same folder is the same bytes, so a snapshot is known by its hash.
21
+
22
+ import crypto from "node:crypto";
23
+ import zlib from "node:zlib";
24
+
25
+ export interface SnapshotEntry {
26
+ /** Relative, `/`-separated. */
27
+ path: string;
28
+ /** 0o644 or 0o755. */
29
+ mode: number;
30
+ content: Buffer;
31
+ }
32
+
33
+ export interface SnapshotLimits {
34
+ maxFiles: number;
35
+ maxFileBytes: number;
36
+ maxTotalBytes: number;
37
+ maxCompressedBytes: number;
38
+ }
39
+
40
+ export const SNAPSHOT_LIMITS: SnapshotLimits = {
41
+ maxFiles: 20_000,
42
+ maxFileBytes: 10 * 1024 * 1024,
43
+ maxTotalBytes: 200 * 1024 * 1024,
44
+ maxCompressedBytes: 50 * 1024 * 1024,
45
+ };
46
+
47
+ const MAX_PATH = 255;
48
+ const MAX_DEPTH = 32;
49
+
50
+ /** Why an archive was refused, in words a person can act on. */
51
+ export class SnapshotRefused extends Error {
52
+ constructor(message: string) {
53
+ super(message);
54
+ this.name = "SnapshotRefused";
55
+ }
56
+ }
57
+
58
+ /** The path rules, for the packer to check before it packs, and the reader after. */
59
+ export function snapshotPathProblem(p: string): string | null {
60
+ if (!p) return "an empty path";
61
+ if (Buffer.byteLength(p) > MAX_PATH) return `a path longer than ${MAX_PATH} bytes`;
62
+ if (p.startsWith("/")) return "an absolute path";
63
+ if (/[\u0000-\u001f\u007f\\]/.test(p)) return "a backslash or control character in a path";
64
+ const parts = p.split("/");
65
+ if (parts.length > MAX_DEPTH) return `a path deeper than ${MAX_DEPTH} folders`;
66
+ if (parts.some((s) => s === "" || s === "." || s === "..")) return "an empty, `.` or `..` segment";
67
+ return null;
68
+ }
69
+
70
+ /**
71
+ * The set of paths in one archive, with every clash rule in one place for the
72
+ * writer and the reader alike (Codex: the writer packed what the reader then
73
+ * refused). Case-insensitive throughout: `A` and `a/b` cannot both exist on
74
+ * a case-insensitive filesystem, so neither may be here.
75
+ */
76
+ class PathSet {
77
+ private kinds = new Map<string, "file" | "dir">();
78
+ private parents = new Set<string>();
79
+ add(p: string, isDir: boolean): void {
80
+ const key = p.toLowerCase();
81
+ if (this.kinds.has(key)) throw new SnapshotRefused(`${p}: there twice (paths may not differ only by case)`);
82
+ const segs = key.split("/");
83
+ for (let i = 1; i < segs.length; i++) {
84
+ const parent = segs.slice(0, i).join("/");
85
+ if (this.kinds.get(parent) === "file") throw new SnapshotRefused(`${p}: inside ${p.split("/").slice(0, i).join("/")}, which is a file`);
86
+ }
87
+ if (!isDir && this.parents.has(key)) throw new SnapshotRefused(`${p}: a file where another entry makes it a folder`);
88
+ this.kinds.set(key, isDir ? "dir" : "file");
89
+ for (let i = 1; i < segs.length; i++) this.parents.add(segs.slice(0, i).join("/"));
90
+ }
91
+ }
92
+
93
+ // ------------------------------------------------------------------ writer
94
+
95
+ function octal(n: number, width: number): string {
96
+ return n.toString(8).padStart(width - 1, "0") + "\0";
97
+ }
98
+
99
+ function header(path: string, size: number, mode: number, type: "0" | "5"): Buffer {
100
+ const h = Buffer.alloc(512, 0);
101
+ // ustar: name (100) and prefix (155); split at a "/" when it is long.
102
+ let name = path;
103
+ let prefix = "";
104
+ if (Buffer.byteLength(name) > 100) {
105
+ const cut = path.lastIndexOf("/", path.length - 1);
106
+ let at = -1;
107
+ for (let i = cut; i > 0; i = path.lastIndexOf("/", i - 1)) {
108
+ if (Buffer.byteLength(path.slice(i + 1)) <= 100 && Buffer.byteLength(path.slice(0, i)) <= 155) {
109
+ at = i;
110
+ break;
111
+ }
112
+ }
113
+ if (at < 0) throw new SnapshotRefused(`${path}: too long to store`);
114
+ prefix = path.slice(0, at);
115
+ name = path.slice(at + 1);
116
+ }
117
+ h.write(name, 0, 100, "utf8");
118
+ h.write(octal(mode, 8), 100, 8, "ascii");
119
+ h.write(octal(0, 8), 108, 8, "ascii"); // uid
120
+ h.write(octal(0, 8), 116, 8, "ascii"); // gid
121
+ h.write(octal(size, 12), 124, 12, "ascii");
122
+ h.write(octal(0, 12), 136, 12, "ascii"); // mtime
123
+ h.write(" ", 148, 8, "ascii"); // checksum placeholder
124
+ h.write(type, 156, 1, "ascii");
125
+ h.write("ustar\u000000", 257, 8, "ascii");
126
+ h.write(prefix, 345, 155, "utf8");
127
+ let sum = 0;
128
+ for (const b of h) sum += b;
129
+ h.write(sum.toString(8).padStart(6, "0") + "\0 ", 148, 8, "ascii");
130
+ return h;
131
+ }
132
+
133
+ /** A deterministic gzipped tar of these files (directories are implied). */
134
+ export function packSnapshot(entries: SnapshotEntry[], limits: SnapshotLimits = SNAPSHOT_LIMITS): { archive: Buffer; sha256: string; files: number; bytes: number } {
135
+ if (entries.length > limits.maxFiles) throw new SnapshotRefused(`${entries.length} files — the most is ${limits.maxFiles}`);
136
+ const sorted = [...entries].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
137
+ const parts: Buffer[] = [];
138
+ let total = 0;
139
+ const paths = new PathSet();
140
+ for (const e of sorted) {
141
+ const problem = snapshotPathProblem(e.path);
142
+ if (problem) throw new SnapshotRefused(`${e.path}: ${problem}`);
143
+ paths.add(e.path, false);
144
+ if (e.content.length > limits.maxFileBytes) throw new SnapshotRefused(`${e.path}: ${e.content.length} bytes — the most for one file is ${limits.maxFileBytes}`);
145
+ total += e.content.length;
146
+ if (total > limits.maxTotalBytes) throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
147
+ parts.push(header(e.path, e.content.length, e.mode === 0o755 ? 0o755 : 0o644, "0"));
148
+ parts.push(e.content);
149
+ const pad = (512 - (e.content.length % 512)) % 512;
150
+ if (pad) parts.push(Buffer.alloc(pad, 0));
151
+ }
152
+ parts.push(Buffer.alloc(1024, 0));
153
+ const archive = zlib.gzipSync(Buffer.concat(parts), { level: 9, mtime: 0 } as zlib.ZlibOptions);
154
+ // gzip's header carries an mtime and an OS byte; both fixed, so the bytes are the folder's alone.
155
+ archive.writeUInt32LE(0, 4);
156
+ archive[9] = 255;
157
+ if (archive.length > limits.maxCompressedBytes) throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
158
+ return { archive, sha256: crypto.createHash("sha256").update(archive).digest("hex"), files: sorted.length, bytes: total };
159
+ }
160
+
161
+ // ------------------------------------------------------------------ reader
162
+
163
+ function readString(b: Buffer, start: number, len: number): string {
164
+ const s = b.subarray(start, start + len);
165
+ const nul = s.indexOf(0);
166
+ return s.subarray(0, nul < 0 ? len : nul).toString("utf8");
167
+ }
168
+
169
+ function readOctal(b: Buffer, start: number, len: number, what: string): number {
170
+ const raw = readString(b, start, len).trim();
171
+ if (raw === "") return 0;
172
+ if (!/^[0-7]+$/.test(raw)) throw new SnapshotRefused(`a header's ${what} is not a number`);
173
+ const n = parseInt(raw, 8);
174
+ if (!Number.isSafeInteger(n)) throw new SnapshotRefused(`a header's ${what} is out of range`);
175
+ return n;
176
+ }
177
+
178
+ /**
179
+ * Unpack an archive a stranger sent, under every rule above. Throws
180
+ * SnapshotRefused naming the first thing wrong; nothing is written anywhere —
181
+ * the caller gets the entries to store.
182
+ */
183
+ export function unpackSnapshot(archive: Buffer, limits: SnapshotLimits = SNAPSHOT_LIMITS): { entries: SnapshotEntry[]; sha256: string; bytes: number } {
184
+ if (archive.length > limits.maxCompressedBytes) throw new SnapshotRefused(`${archive.length} bytes compressed — the most is ${limits.maxCompressedBytes}`);
185
+ let tar: Buffer;
186
+ try {
187
+ // The tar is at most the files, their headers and padding: past that, a bomb.
188
+ const ceiling = limits.maxTotalBytes + (limits.maxFiles + 2) * 1024 + 1024;
189
+ tar = zlib.gunzipSync(archive, { maxOutputLength: ceiling });
190
+ } catch (err) {
191
+ const code = (err as { code?: string }).code;
192
+ throw new SnapshotRefused(code === "ERR_BUFFER_TOO_LARGE" || /larger than/i.test(String((err as Error).message)) ? `it unpacks past ${limits.maxTotalBytes} bytes` : "it is not a gzip archive");
193
+ }
194
+ const entries: SnapshotEntry[] = [];
195
+ const paths = new PathSet();
196
+ // Every entry counts against maxFiles, folders too, before its path is
197
+ // recorded: an archive of folders alone would otherwise pass every limit
198
+ // and fill memory with paths (Codex). Our writer emits no folder entries.
199
+ let count = 0;
200
+ let total = 0;
201
+ let off = 0;
202
+ let ended = false;
203
+ while (off + 512 <= tar.length) {
204
+ const h = tar.subarray(off, off + 512);
205
+ if (h.every((x) => x === 0)) {
206
+ const next = tar.subarray(off + 512, off + 1024);
207
+ if (next.length === 512 && next.every((x) => x === 0)) {
208
+ ended = true;
209
+ off += 1024;
210
+ break;
211
+ }
212
+ throw new SnapshotRefused("a lone empty block before the end");
213
+ }
214
+ let sum = 0;
215
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 32 : h[i]!;
216
+ if (readOctal(h, 148, 8, "checksum") !== sum) throw new SnapshotRefused("a header's checksum is wrong");
217
+ if (readString(h, 257, 6) !== "ustar") throw new SnapshotRefused("not a ustar archive");
218
+ const type = String.fromCharCode(h[156]!);
219
+ const name = readString(h, 0, 100);
220
+ const prefix = readString(h, 345, 155);
221
+ const p0 = prefix ? `${prefix}/${name}` : name;
222
+ const isDir = type === "5";
223
+ const p = isDir ? p0.replace(/\/+$/, "") : p0;
224
+ if (type !== "0" && type !== "\0" && !isDir) {
225
+ const what = { "1": "a hard link", "2": "a symbolic link", "3": "a character device", "4": "a block device", "6": "a FIFO", x: "an extended (PAX) header", g: "a global PAX header", L: "a GNU long name", K: "a GNU long link", S: "a sparse file" }[type] ?? `an entry of type ${JSON.stringify(type)}`;
226
+ throw new SnapshotRefused(`${p || "(unnamed)"}: ${what} — only plain files and folders`);
227
+ }
228
+ const problem = snapshotPathProblem(p);
229
+ if (problem) throw new SnapshotRefused(`${p}: ${problem}`);
230
+ const size = readOctal(h, 124, 12, "size");
231
+ if (isDir && size !== 0) throw new SnapshotRefused(`${p}: a folder with a size`);
232
+ if (size > limits.maxFileBytes) throw new SnapshotRefused(`${p}: ${size} bytes — the most for one file is ${limits.maxFileBytes}`);
233
+ if (++count > limits.maxFiles) throw new SnapshotRefused(`more than ${limits.maxFiles} entries`);
234
+ paths.add(p, isDir);
235
+ off += 512;
236
+ if (!isDir) {
237
+ if (off + size > tar.length) throw new SnapshotRefused(`${p}: cut short`);
238
+ total += size;
239
+ if (total > limits.maxTotalBytes) throw new SnapshotRefused(`more than ${limits.maxTotalBytes} bytes in all`);
240
+ if (entries.length + 1 > limits.maxFiles) throw new SnapshotRefused(`more than ${limits.maxFiles} files`);
241
+ const mode = readOctal(h, 100, 8, "mode");
242
+ entries.push({ path: p, mode: mode & 0o100 ? 0o755 : 0o644, content: Buffer.from(tar.subarray(off, off + size)) });
243
+ off += size + ((512 - (size % 512)) % 512);
244
+ }
245
+ }
246
+ if (!ended) throw new SnapshotRefused("no end-of-archive marker");
247
+ if (tar.subarray(off).some((x) => x !== 0)) throw new SnapshotRefused("data after the end of the archive");
248
+ return { entries, sha256: crypto.createHash("sha256").update(archive).digest("hex"), bytes: total };
249
+ }