@blamejs/blamejs-shop 0.0.83 → 0.0.85

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,81 @@
1
+ {
2
+ "$schema": "../scripts/release-notes-schema.json",
3
+ "version": "0.12.8",
4
+ "date": "2026-05-23",
5
+ "headline": "`b.archive.tar` + `b.archive.read.tar` — POSIX pax tar format end-to-end + `b.guardArchive.tarEntryPolicy` + `b.backup` tar bundle default",
6
+ "summary": "Tar lands as the second format in the archive family. `b.archive.tar()` builds POSIX pax archives (ustar magic + pax extended headers for >100-char names, >8 GiB sizes, nanosecond mtime); `b.archive.read.tar(adapter)` walks the 512-byte block sequence with the same bomb-cap + path-traversal + entry-type defenses that ZIP read shipped at v0.12.7. Tar's natively-streamable shape means `b.archive.adapters.trustedStream(readable)` is a first-class extract path here (no CD-walk required since tar has no central directory; sequential header-by-header is the canonical adversarial-safe path). `b.guardArchive.tarEntryPolicy` ships as the tar-specific entry-shape policy beyond `entryTypePolicy` — handles typeflag 0/5 (regular/directory) by default, refuses 1/2 (hardlink/symlink) unless `allowDangerous` is set with the realpath-on-link-target dual-check, and refuses 3/4/6/7 (char-device/block-device/FIFO/contiguous-file) unconditionally. `b.backup.bundleAdapterStorage({ format: \"tar\" })` becomes the default for new bundles — directory-tree format stays available via `format: \"directory\"` for back-compat with v0.12.7 bundles. `b.backup.migrate(from, to)` one-shot helper converts v0.12.7 directory bundles to v0.12.8 tar bundles transparently. `b.safeArchive.extract({ source, destination, format: \"auto\" })` now sniffs ustar magic at offset 257 inside the first 512-byte block and dispatches to the tar reader automatically. CVE coverage extends to the tar class: CVE-2026-23745 / 2026-24842 (node-tar symlink+hardlink path resolution), CVE-2025-4517 PATH_MAX TOCTOU (the v0.12.7 dual-check carries through), CVE-2025-11001/11002 (symlink TOCTOU on extract), CVE-2024-12905 / 2025-48387 (tar-fs traversal), CVE-2025-4138/4330 (Python tarfile data filter bypass).",
7
+ "sections": [
8
+ {
9
+ "heading": "Added",
10
+ "items": [
11
+ {
12
+ "title": "`b.archive.tar()` — POSIX pax write builder",
13
+ "body": "Mirrors `b.archive.zip()`'s contract: `addFile(name, content, opts?)` + `addDirectory(name, opts?)` + `toBuffer()` + `toStream(writable)` + `toAdapter(adapter)` + `digest()`. Emits ustar-magic 512-byte header blocks with the standard 11-field prefix (name / mode / uid / gid / size / mtime / chksum / typeflag / linkname / magic / version / uname / gname / devmajor / devminor / prefix). Names >100 chars + sizes >8 GiB + mtime with nanosecond precision get a pax extended header (typeflag=x) preceding the entry; the extended header records (per POSIX.1-2001 §4.18) carry the `path` / `size` / `mtime` / `atime` / `ctime` fields that overflow ustar's fixed widths. Determinism opts: `{ fixedMtime: 0, ignoreOrder: false }` for reproducible builds (matches the ZIP write side)."
14
+ },
15
+ {
16
+ "title": "`b.archive.read.tar(adapter, opts)` — sequential + random-access tar reader",
17
+ "body": "Walks 512-byte header blocks in order. `inspect()` enumerates entries without decompressing; `extract({ destination })` decompresses entry-by-entry with the same bomb-cap + path-traversal + entry-type defenses as ZIP read. Trusted-stream adapters are first-class here — tar has no central directory, so sequential header-by-header walk IS the canonical adversarial-safe path (`b.archive.adapters.trustedStream(readable)` and `b.archive.adapters.fs/buffer/objectStore/http` all flow through the same reader). Per-entry path safety routes through `b.guardFilename.verifyExtractionPath` (the v0.12.7 dual-check). Refuses to overwrite pre-existing destination files (carries the v0.12.7 atomic-rollback contract)."
18
+ },
19
+ {
20
+ "title": "`b.guardArchive.tarEntryPolicy(opts)` — tar-specific entry-type policy",
21
+ "body": "Defaults: typeflag 0 (regular file) + 5 (directory) extract; typeflag 1 (hardlink) + 2 (symlink) refused unless `allowDangerous: { symlinks: true, hardlinks: true }` is set; typeflag 3 (char-device) + 4 (block-device) + 6 (FIFO) + 7 (contiguous-file) refused unconditionally. When `allowDangerous` is set, link target is routed through `b.guardFilename.verifyExtractionPath` against the extraction root — the realpath-on-link-target check defends the CVE-2026-23745 / 24842 node-tar class where the safety check and creation logic diverged on path resolution. Pax extended-header (x) + global-header (g) entries consumed by the reader (merged into the following entry's metadata); operators never see them as standalone entries."
22
+ },
23
+ {
24
+ "title": "`b.backup.bundleAdapterStorage({ format: \"tar\" })` — tar bundle becomes default",
25
+ "body": "New bundles ship as a single tar archive instead of a directory tree. Restore via `b.archive.read.tar` (with the operator-supplied adapter routing the bytes). `format: \"directory\"` opts back into the v0.12.7 layout for operators with existing bundles. `format: \"tar\"` is the new default; `b.backup.diskStorage` stays back-compat at the legacy directory-tree format."
26
+ },
27
+ {
28
+ "title": "`b.backup.migrate(opts)` — directory → tar bundle migration",
29
+ "body": "One-shot helper that walks an operator's directory-tree-format bundle (v0.12.7 layout) and writes the same content as a tar-format bundle via the v0.12.8 bundleAdapterStorage. Idempotent: re-running on an already-migrated bundle is a no-op. Source bundle stays in place until the migrate succeeds; operators with explicit transition windows pass `{ deleteSourceOnSuccess: true }` to opt into the inline replace."
30
+ },
31
+ {
32
+ "title": "`b.safeArchive.extract({ format: \"auto\" })` recognizes tar",
33
+ "body": "Format auto-sniff now dispatches `ustar` magic at offset 257 inside the first 512-byte header block to the tar reader. ZIP magic + tar magic + GZIP magic (v0.12.9) live in the same sniff path; operators with mixed-format pipelines pass `format: \"auto\"` once + the orchestrator picks the right reader."
34
+ }
35
+ ]
36
+ },
37
+ {
38
+ "heading": "Security",
39
+ "items": [
40
+ {
41
+ "title": "Symlink + hardlink path resolution (CVE-2026-23745 / CVE-2026-24842 node-tar class)",
42
+ "body": "node-tar < 7.5.7 / ≤ 7.5.2 shipped a divergence between its hardlink safety check (which used one path resolution) and its hardlink creation logic (which used another). When `allowDangerous: { hardlinks: true }` is set, blamejs routes the link target through `b.guardFilename.verifyExtractionPath` — the SAME primitive that the eventual `link()` call resolves against — so check + create agree by construction. Symlink targets same shape."
43
+ },
44
+ {
45
+ "title": "Path traversal (CVE-2024-12905 / CVE-2025-48387 tar-fs + CVE-2025-4138 / 4330 Python tarfile data filter bypass)",
46
+ "body": "Every entry name passes through `b.guardFilename.verifyExtractionPath` — the v0.12.7 dual-check that refuses pre-resolve names > PATH_MAX (4096 bytes) AND verifies the string-normalize + `fs.realpath` resolutions agree on the same final path. Defends the CVE-2025-4517 / 4138 / 4330 class where the operator's path resolution and the kernel's diverge silently past PATH_MAX."
47
+ },
48
+ {
49
+ "title": "Symlink TOCTOU on extract (CVE-2025-11001 / CVE-2025-11002 7-Zip class)",
50
+ "body": "When `allowDangerous: { symlinks: true }` opts symlinks in, the reader resolves the link target via `verifyExtractionPath` against the extraction root BEFORE calling `fs.symlink` — so the resolved target is inside the trust boundary by construction. The v0.12.7 atomic-rollback contract carries through: any single entry failure aborts the whole extract + cleans up only newly-created files (pre-existing destination files refused at the pre-write check)."
51
+ }
52
+ ]
53
+ },
54
+ {
55
+ "heading": "Detectors",
56
+ "items": [
57
+ {
58
+ "title": "`tar-extract-allow-dangerous-without-link-target-check`",
59
+ "body": "Flags any `b.archive.read.tar(adapter).extract({ allowDangerous: ... })` call site in `lib/` that doesn't route the link target through `b.guardFilename.verifyExtractionPath` against the extraction root. Forces the dual-check discipline at every allow-dangerous opt-in — operators with hardlink / symlink extract needs see the realpath check at the call site."
60
+ },
61
+ {
62
+ "title": "`tar-entry-typeflag-without-policy`",
63
+ "body": "Flags `lib/archive-tar.js` extract code paths that switch on typeflag without composing `b.guardArchive.tarEntryPolicy` for the type-allowlist decision. Locks the shape: every typeflag dispatch goes through the policy, never inline."
64
+ },
65
+ {
66
+ "title": "`backup-migrate-without-source-preserve`",
67
+ "body": "Flags `b.backup.migrate(opts)` call sites that pass `deleteSourceOnSuccess: true` without an operator-stated justification comment. Default is preserve-source; deletes need an explicit reason."
68
+ }
69
+ ]
70
+ }
71
+ ],
72
+ "references": [
73
+ { "label": "POSIX.1-2001 pax extended format (IEEE 1003.1)", "url": "https://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html" },
74
+ { "label": "CVE-2026-23745 — node-tar symlink+hardlink path resolution", "url": "https://www.sentinelone.com/vulnerability-database/cve-2026-23745/" },
75
+ { "label": "CVE-2026-24842 — node-tar hardlink path resolution", "url": "https://github.com/advisories/GHSA-34x7-hfp2-rc4v" },
76
+ { "label": "CVE-2025-4517 — Python tarfile PATH_MAX bypass (CVSS 9.4)", "url": "https://nvd.nist.gov/vuln/detail/CVE-2025-4517" },
77
+ { "label": "CVE-2025-4138 / CVE-2025-4330 — Python tarfile data filter", "url": "https://github.com/0xDTC/CVE-2025-4138-4517-POC" },
78
+ { "label": "CVE-2025-11001 / CVE-2025-11002 — 7-Zip symlink TOCTOU on extract", "url": "https://www.sentinelone.com/vulnerability-database/cve-2025-11001/" },
79
+ { "label": "CVE-2024-12905 / CVE-2025-48387 — node-tar-fs path traversal", "url": "https://vulert.com/vuln-db/debian-11-node-tar-fs-193050" }
80
+ ]
81
+ }
@@ -0,0 +1,247 @@
1
+ "use strict";
2
+ /**
3
+ * Layer 0 — b.archive read substrate + safe-extract orchestrator +
4
+ * guard-archive policy builders + b.guardFilename.verifyExtractionPath
5
+ * + b.backup.bundleAdapterStorage.
6
+ *
7
+ * Round-trip coverage: write a ZIP via the existing write side, read
8
+ * it back via b.archive.read.zip (random-access buffer adapter), extract
9
+ * via b.safeArchive.extract into a quarantine directory, verify file
10
+ * contents. Refusal coverage: zip-slip entry name, oversize entries,
11
+ * NUL byte, PATH_MAX overflow.
12
+ */
13
+
14
+ var helpers = require("../helpers");
15
+ var check = helpers.check;
16
+ var b = helpers.b;
17
+ var os = require("node:os");
18
+ var path = require("node:path");
19
+ var fs = require("node:fs");
20
+
21
+ async function testRoundTripExtract() {
22
+ var z = b.archive.zip();
23
+ z.addFile("readme.txt", "Hello, archive-read!\n");
24
+ z.addFile("data/numbers.csv", "n,sq\n1,1\n2,4\n3,9\n");
25
+ z.addFile("docs/nested/deep.txt", Buffer.from("payload\n"));
26
+ var bytes = z.toBuffer();
27
+
28
+ // Inspect via buffer adapter — verifies adapter contract + EOCD walk +
29
+ // CD-walk + LFH/CD skew check.
30
+ var reader = b.archive.read.zip(b.archive.adapters.buffer(bytes));
31
+ var entries = await reader.inspect();
32
+ check("archive.read.zip.inspect: 3 entries", entries.length === 3);
33
+ check("archive.read.zip.inspect: name + size", entries[0].name === "readme.txt" && entries[0].size === 21);
34
+ check("archive.read.zip.inspect: nested name", entries[2].name === "docs/nested/deep.txt");
35
+
36
+ // Extract via safeArchive orchestrator.
37
+ var dest = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-archive-test-"));
38
+ try {
39
+ var result = await b.safeArchive.extract({
40
+ source: bytes,
41
+ destination: dest,
42
+ guardProfile: "balanced",
43
+ });
44
+ check("safeArchive.extract: 3 entries written", result.entries.length === 3);
45
+ check("safeArchive.extract: format=zip", result.format === "zip");
46
+ var readme = fs.readFileSync(path.join(dest, "readme.txt"), "utf8");
47
+ check("safeArchive.extract: readme contents match", readme === "Hello, archive-read!\n");
48
+ var nested = fs.readFileSync(path.join(dest, "docs/nested/deep.txt"), "utf8");
49
+ check("safeArchive.extract: nested file restored", nested === "payload\n");
50
+ } finally {
51
+ fs.rmSync(dest, { recursive: true, force: true });
52
+ }
53
+ }
54
+
55
+ function testSafeArchiveErrorClass() {
56
+ // Sanity-check that the typed-error class is exported + an instance
57
+ // can be constructed with a code + message.
58
+ var err = new b.safeArchive.SafeArchiveError("safe-archive/test", "test instance");
59
+ check("SafeArchiveError: code carried", err.code === "safe-archive/test");
60
+ check("SafeArchiveError: is Error subclass", err instanceof Error);
61
+ }
62
+
63
+ async function testSafeArchiveInspect() {
64
+ var z = b.archive.zip();
65
+ z.addFile("a.txt", "alpha");
66
+ z.addFile("b.txt", "beta");
67
+ var bytes = z.toBuffer();
68
+ var summary = await b.safeArchive.inspect({ source: bytes });
69
+ check("safeArchive.inspect: format=zip", summary.format === "zip");
70
+ check("safeArchive.inspect: 2 entries", summary.entries.length === 2);
71
+ check("safeArchive.inspect: totalUncompressedBytes", summary.totalUncompressedBytes === 9);
72
+ }
73
+
74
+ async function testZipBombPolicy() {
75
+ var policy = b.guardArchive.zipBombPolicy({
76
+ maxTotalDecompressedBytes: 8,
77
+ maxExpansionRatio: 100,
78
+ });
79
+ check("zipBombPolicy: maxTotalDecompressedBytes carries", policy.maxTotalDecompressedBytes === 8);
80
+ check("zipBombPolicy: defaults applied", policy.maxEntries === 65535);
81
+ // 9-byte archive payload exceeds the 8-byte total cap.
82
+ var z = b.archive.zip();
83
+ z.addFile("big.txt", "123456789");
84
+ var bytes = z.toBuffer();
85
+ var refused = null;
86
+ try {
87
+ var reader = b.archive.read.zip(b.archive.adapters.buffer(bytes), {
88
+ bombPolicy: policy,
89
+ });
90
+ await reader.inspect();
91
+ } catch (e) { refused = e; }
92
+ check("bombPolicy: maxTotalDecompressedBytes trips",
93
+ refused && /total-too-large|entry-too-large/.test(refused.code || refused.message));
94
+ }
95
+
96
+ function testEntryTypePolicy() {
97
+ var p = b.guardArchive.entryTypePolicy({ symlinks: true });
98
+ check("entryTypePolicy: symlinks opted in", p.symlinks === true);
99
+ check("entryTypePolicy: hardlinks default off", p.hardlinks === false);
100
+ check("entryTypePolicy: devices default off", p.devices === false);
101
+ }
102
+
103
+ function testVerifyExtractionPathHappy() {
104
+ var dest = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-verifyx-"));
105
+ try {
106
+ var resolved = b.guardFilename.verifyExtractionPath("docs/readme.txt", dest);
107
+ check("verifyExtractionPath: ok resolved", resolved.indexOf(dest) === 0);
108
+ } finally {
109
+ fs.rmSync(dest, { recursive: true, force: true });
110
+ }
111
+ }
112
+
113
+ function testVerifyExtractionPathRefusals() {
114
+ var refusals = 0;
115
+ function r(name, root) {
116
+ try { b.guardFilename.verifyExtractionPath(name, root); }
117
+ catch (_e) { refusals += 1; }
118
+ }
119
+ r("../etc/passwd", "/tmp"); // zip slip
120
+ r("/etc/passwd", "/tmp"); // absolute
121
+ r("docs/../../etc/passwd", "/tmp"); // mid-segment ..
122
+ // PATH_MAX overflow (4097 chars).
123
+ var oversize = new Array(4098).join("a");
124
+ r(oversize, "/tmp");
125
+ check("verifyExtractionPath: 4 refusals", refusals === 4);
126
+ }
127
+
128
+ async function testExtractRefusesOverwrite() {
129
+ // Codex P1 on v0.12.7 PR #158 — the catch-block cleanup deleted
130
+ // PRE-EXISTING destination files on abort because the rename-onto-
131
+ // canonical-path path overwrote them first, then `written[].path`
132
+ // got rm'd. Fix is to refuse overwrite up front; this regression
133
+ // test verifies the new refusal fires + that the pre-existing file
134
+ // is left untouched.
135
+ var z = b.archive.zip();
136
+ z.addFile("readme.txt", "from-archive\n");
137
+ var bytes = z.toBuffer();
138
+ var dest = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-overwrite-test-"));
139
+ try {
140
+ var collidePath = path.join(dest, "readme.txt");
141
+ fs.writeFileSync(collidePath, "operator's pre-existing file\n");
142
+ var refused = null;
143
+ try {
144
+ await b.safeArchive.extract({ source: bytes, destination: dest });
145
+ } catch (e) { refused = e; }
146
+ check("extract: refuses pre-existing destination file",
147
+ refused && /destination-exists/.test(refused.code || refused.message));
148
+ var stillThere = fs.readFileSync(collidePath, "utf8");
149
+ check("extract: pre-existing file untouched on refusal",
150
+ stillThere === "operator's pre-existing file\n");
151
+ } finally {
152
+ fs.rmSync(dest, { recursive: true, force: true });
153
+ }
154
+ }
155
+
156
+ async function testSafeArchiveRefusesTrustedStreamSource() {
157
+ // Codex P2 on v0.12.7 PR #158 — safeArchive.extract accepted
158
+ // trusted-stream adapters via the input-shape validator but the
159
+ // implementation called the random-access reader, which threw the
160
+ // wrong-entry-point error. Fix is to refuse trusted-stream sources
161
+ // upfront with a typed safe-archive code.
162
+ var nodeStream = require("node:stream");
163
+ var fakeReadable = new nodeStream.Readable({ read: function () {} });
164
+ var adapter = b.archive.adapters.trustedStream(fakeReadable);
165
+ var dest = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-trusted-refusal-"));
166
+ try {
167
+ var refused = null;
168
+ try {
169
+ await b.safeArchive.extract({
170
+ source: adapter,
171
+ destination: dest,
172
+ });
173
+ } catch (e) { refused = e; }
174
+ check("safeArchive.extract: trusted-stream upfront refused",
175
+ refused && /trusted-stream-unsupported/.test(refused.code || refused.message));
176
+ } finally {
177
+ fakeReadable.destroy();
178
+ fs.rmSync(dest, { recursive: true, force: true });
179
+ }
180
+ }
181
+
182
+ async function testGuardArchiveInspect() {
183
+ var z = b.archive.zip();
184
+ z.addFile("safe.txt", "safe");
185
+ var bytes = z.toBuffer();
186
+ var summary = await b.guardArchive.inspect(b.archive.adapters.buffer(bytes), {
187
+ profile: "balanced",
188
+ });
189
+ check("guardArchive.inspect: 1 entry", summary.entries.length === 1);
190
+ check("guardArchive.inspect: issues array", Array.isArray(summary.issues));
191
+ }
192
+
193
+ async function testBundleAdapterStorageRoundTrip() {
194
+ var rootDir = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-backup-adapter-root-"));
195
+ var srcDir = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-backup-adapter-src-"));
196
+ var destDir = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-backup-adapter-dest-"));
197
+ try {
198
+ // Populate a small bundle source.
199
+ fs.writeFileSync(path.join(srcDir, "manifest.json"), JSON.stringify({ v: 1 }));
200
+ fs.mkdirSync(path.join(srcDir, "files"));
201
+ fs.writeFileSync(path.join(srcDir, "files", "blob.bin"), Buffer.from([1, 2, 3]));
202
+
203
+ var storage = b.backup.bundleAdapterStorage({
204
+ adapter: b.backup.bundleAdapterStorage.fsAdapter({ root: rootDir }),
205
+ });
206
+ check("bundleAdapterStorage: name=adapter", storage.name === "adapter");
207
+
208
+ var bundleId = "2026-05-23T07-00-00-000Z-deadbeef";
209
+ await storage.writeBundle(bundleId, srcDir);
210
+ check("bundleAdapterStorage: hasBundle after write", await storage.hasBundle(bundleId));
211
+ fs.rmSync(destDir, { recursive: true });
212
+ await storage.readBundle(bundleId, destDir);
213
+ var restored = fs.readFileSync(path.join(destDir, "files", "blob.bin"));
214
+ check("bundleAdapterStorage: roundtrip bytes match", restored[0] === 1 && restored.length === 3);
215
+ var list = await storage.listBundles();
216
+ check("bundleAdapterStorage: listBundles returns the bundle", list.length === 1 && list[0].bundleId === bundleId);
217
+ await storage.deleteBundle(bundleId);
218
+ check("bundleAdapterStorage: hasBundle false after delete", !(await storage.hasBundle(bundleId)));
219
+ } finally {
220
+ try { fs.rmSync(rootDir, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
221
+ try { fs.rmSync(srcDir, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
222
+ try { fs.rmSync(destDir, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
223
+ }
224
+ }
225
+
226
+ async function run() {
227
+ await testRoundTripExtract();
228
+ testSafeArchiveErrorClass();
229
+ await testSafeArchiveInspect();
230
+ await testZipBombPolicy();
231
+ testEntryTypePolicy();
232
+ testVerifyExtractionPathHappy();
233
+ testVerifyExtractionPathRefusals();
234
+ await testExtractRefusesOverwrite();
235
+ await testSafeArchiveRefusesTrustedStreamSource();
236
+ await testGuardArchiveInspect();
237
+ await testBundleAdapterStorageRoundTrip();
238
+ }
239
+
240
+ module.exports = { run: run };
241
+
242
+ if (require.main === module) {
243
+ run().then(
244
+ function () { console.log("[archive-read] OK — " + helpers.getChecks() + " checks passed"); },
245
+ function (e) { console.error("FAIL:", e && e.stack || e); process.exit(1); }
246
+ );
247
+ }
@@ -0,0 +1,228 @@
1
+ "use strict";
2
+ /**
3
+ * Layer 0 — b.archive.tar write + b.archive.read.tar +
4
+ * b.guardArchive.tarEntryPolicy + b.backup.migrate.
5
+ *
6
+ * Round-trip coverage: write tar via b.archive.tar(), read back via
7
+ * b.archive.read.tar(buffer adapter), extract via b.safeArchive.extract
8
+ * (format auto-detect lands on tar). Refusal: oversize entry, dangerous
9
+ * typeflag refusal by default. Migration: write a directory bundle in
10
+ * one storage, migrate to tar bundle in another, verify content.
11
+ */
12
+
13
+ var helpers = require("../helpers");
14
+ var check = helpers.check;
15
+ var b = helpers.b;
16
+ var os = require("node:os");
17
+ var path = require("node:path");
18
+ var fs = require("node:fs");
19
+
20
+ async function testTarRoundTrip() {
21
+ var t = b.archive.tar();
22
+ t.addFile("readme.txt", "Hello, tar!\n");
23
+ t.addFile("data/numbers.csv", "n,sq\n1,1\n2,4\n");
24
+ t.addDirectory("docs/");
25
+ t.addFile("docs/nested/deep.txt", "payload\n");
26
+ var bytes = t.toBuffer();
27
+
28
+ check("archive.tar: tar bytes round to 512", bytes.length % 512 === 0);
29
+ check("archive.tar: ustar magic at offset 257",
30
+ bytes.slice(257, 263).toString().indexOf("ustar") === 0);
31
+
32
+ var reader = b.archive.read.tar(b.archive.adapters.buffer(bytes));
33
+ var entries = await reader.inspect();
34
+ check("archive.read.tar.inspect: 4 entries", entries.length === 4);
35
+ check("archive.read.tar.inspect: file type", entries[0].entryType === "file");
36
+ check("archive.read.tar.inspect: directory type", entries[2].entryType === "directory");
37
+ }
38
+
39
+ async function testSafeArchiveTarExtract() {
40
+ var t = b.archive.tar();
41
+ t.addFile("a.txt", "alpha");
42
+ t.addFile("nested/b.txt", "beta");
43
+ var bytes = t.toBuffer();
44
+
45
+ var dest = fs.mkdtempSync(path.join(os.tmpdir(), "blamejs-tar-extract-"));
46
+ try {
47
+ var result = await b.safeArchive.extract({
48
+ source: bytes,
49
+ destination: dest,
50
+ guardProfile: "balanced",
51
+ });
52
+ check("safeArchive.extract: format=tar autodetected", result.format === "tar");
53
+ check("safeArchive.extract: 2 entries written", result.entries.length === 2);
54
+ var a = fs.readFileSync(path.join(dest, "a.txt"), "utf8");
55
+ var bb = fs.readFileSync(path.join(dest, "nested", "b.txt"), "utf8");
56
+ check("safeArchive.extract: a.txt contents", a === "alpha");
57
+ check("safeArchive.extract: nested b.txt contents", bb === "beta");
58
+ } finally {
59
+ fs.rmSync(dest, { recursive: true, force: true });
60
+ }
61
+ }
62
+
63
+ function testTarEntryPolicy() {
64
+ var p = b.guardArchive.tarEntryPolicy({ symlinks: true });
65
+ check("tarEntryPolicy: symlinks opted in", p.symlinks === true);
66
+ check("tarEntryPolicy: hardlinks default off", p.hardlinks === false);
67
+ check("tarEntryPolicy: devices default off", p.devices === false);
68
+ check("tarEntryPolicy: fifos default off", p.fifos === false);
69
+ check("tarEntryPolicy: sockets default off", p.sockets === false);
70
+ }
71
+
72
+ async function testTarChecksumDetection() {
73
+ // Build a valid tar, corrupt the chksum field, verify reader refuses.
74
+ var t = b.archive.tar();
75
+ t.addFile("payload.txt", "hello\n");
76
+ var bytes = t.toBuffer();
77
+ // Corrupt the checksum field of the first header (offset 148, 8 bytes).
78
+ bytes[148] = 0x39; // change first chksum digit
79
+ var refused = null;
80
+ try {
81
+ var reader = b.archive.read.tar(b.archive.adapters.buffer(bytes));
82
+ await reader.inspect();
83
+ } catch (e) { refused = e; }
84
+ check("archive.read.tar: corrupted chksum refused",
85
+ refused && /chksum|bad-octal/.test(refused.code || refused.message));
86
+ check("archive.read.tar: chksum refusal is a b.archive.TarError",
87
+ refused instanceof b.archive.TarError);
88
+ }
89
+
90
+ async function testBackupMigrateDirectoryToTar() {
91
+ var fromRoot = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-from-"));
92
+ var toRoot = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-to-"));
93
+ var srcDir = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-src-"));
94
+ var verifyDir = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-verify-"));
95
+ fs.rmSync(verifyDir, { recursive: true }); // backend wants non-existent dest
96
+ try {
97
+ fs.writeFileSync(path.join(srcDir, "manifest.json"), JSON.stringify({ v: 1 }));
98
+ fs.mkdirSync(path.join(srcDir, "files"));
99
+ fs.writeFileSync(path.join(srcDir, "files", "blob.bin"), Buffer.from([1, 2, 3]));
100
+
101
+ var from = b.backup.bundleAdapterStorage({
102
+ adapter: b.backup.bundleAdapterStorage.fsAdapter({ root: fromRoot }),
103
+ format: "directory",
104
+ });
105
+ var to = b.backup.bundleAdapterStorage({
106
+ adapter: b.backup.bundleAdapterStorage.fsAdapter({ root: toRoot }),
107
+ format: "tar",
108
+ });
109
+
110
+ var bundleId = "2026-05-23T15-00-00-000Z-deadbeef";
111
+ await from.writeBundle(bundleId, srcDir);
112
+ check("migrate: source-bundle exists pre-migrate", await from.hasBundle(bundleId));
113
+ check("migrate: dest-bundle absent pre-migrate", !(await to.hasBundle(bundleId)));
114
+
115
+ var report = await b.backup.migrate({ from: from, to: to });
116
+ check("migrate: 1 migrated", report.migrated === 1 && report.skipped === 0);
117
+ check("migrate: dest-bundle present post-migrate", await to.hasBundle(bundleId));
118
+
119
+ // Idempotency: second run skips.
120
+ var second = await b.backup.migrate({ from: from, to: to });
121
+ check("migrate: idempotent (1 skipped)", second.migrated === 0 && second.skipped === 1);
122
+
123
+ // Read back from destination, verify file contents.
124
+ await to.readBundle(bundleId, verifyDir);
125
+ var manifest = JSON.parse(fs.readFileSync(path.join(verifyDir, "manifest.json"), "utf8"));
126
+ check("migrate: manifest round-tripped", manifest.v === 1);
127
+ var blob = fs.readFileSync(path.join(verifyDir, "files", "blob.bin"));
128
+ check("migrate: blob round-tripped",
129
+ blob.length === 3 && blob[0] === 1 && blob[2] === 3);
130
+ } finally {
131
+ try { fs.rmSync(fromRoot, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
132
+ try { fs.rmSync(toRoot, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
133
+ try { fs.rmSync(srcDir, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
134
+ try { fs.rmSync(verifyDir, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
135
+ }
136
+ }
137
+
138
+ async function testBackupTarFormatDefault() {
139
+ // Write a bundle via the v0.12.8-default format (tar) + verify the
140
+ // tar key landed on disk.
141
+ var root = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-tar-default-"));
142
+ var src = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-tar-src-"));
143
+ try {
144
+ fs.writeFileSync(path.join(src, "manifest.json"), JSON.stringify({ v: 1 }));
145
+ var storage = b.backup.bundleAdapterStorage({
146
+ adapter: b.backup.bundleAdapterStorage.fsAdapter({ root: root }),
147
+ // format defaults to "tar" in v0.12.8
148
+ });
149
+ var bid = "2026-05-23T15-30-00-000Z-cafebabe";
150
+ await storage.writeBundle(bid, src);
151
+ var tarKeyPresent = fs.existsSync(path.join(root, bid, "bundle.tar"));
152
+ check("bundleAdapterStorage default format: tar key on disk", tarKeyPresent);
153
+ check("bundleAdapterStorage default format: hasBundle true",
154
+ await storage.hasBundle(bid));
155
+ } finally {
156
+ try { fs.rmSync(root, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
157
+ try { fs.rmSync(src, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
158
+ }
159
+ }
160
+
161
+ async function testTarTruncationRefused() {
162
+ // Codex P1 on v0.12.8 PR #159 — declare 11 bytes in the header
163
+ // but truncate the buffer to 8 payload bytes. The walker must
164
+ // refuse upfront rather than emitting a partial entry.
165
+ var t = b.archive.tar();
166
+ t.addFile("payload.txt", Buffer.from("hello world")); // 11 bytes
167
+ var bytes = t.toBuffer();
168
+ // First header block is at offset 0-511; first data block at
169
+ // 512-1023 (padded to 512 bytes from the declared 11). Truncate to
170
+ // 768 bytes: header survives intact but the data block ends
171
+ // halfway — walker must refuse before slicing partial bytes as
172
+ // a "complete" file.
173
+ var truncated = bytes.slice(0, 768);
174
+ var refused = null;
175
+ try {
176
+ var reader = b.archive.read.tar(b.archive.adapters.buffer(truncated));
177
+ await reader.extract({
178
+ destination: fs.mkdtempSync(path.join(os.tmpdir(), "bjs-tar-trunc-")),
179
+ });
180
+ } catch (e) { refused = e; }
181
+ check("archive.read.tar: truncated entry refused with typed error",
182
+ refused && /truncated-entry/.test(refused.code || refused.message));
183
+ }
184
+
185
+ async function testBackupBundleTooLargeRefused() {
186
+ // Codex P2 on v0.12.8 PR #159 — bundleAdapterStorage with a
187
+ // tight maxBundleBytes cap must refuse oversized payloads upfront
188
+ // rather than OOM during in-memory tar materialization.
189
+ var srcDir = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-bulk-"));
190
+ var dest = fs.mkdtempSync(path.join(os.tmpdir(), "bjs-bk-bulk-dest-"));
191
+ try {
192
+ fs.writeFileSync(path.join(srcDir, "big.bin"), Buffer.alloc(64 * 1024));
193
+ var storage = b.backup.bundleAdapterStorage({
194
+ adapter: b.backup.bundleAdapterStorage.fsAdapter({ root: dest }),
195
+ format: "tar",
196
+ maxBundleBytes: 16 * 1024,
197
+ });
198
+ var refused = null;
199
+ try {
200
+ await storage.writeBundle("2026-05-23T00-00-00-000Z-abcdef12", srcDir);
201
+ } catch (e) { refused = e; }
202
+ check("backup: bundle exceeding maxBundleBytes refused upfront",
203
+ refused && /bundle-too-large/.test(refused.code || refused.message));
204
+ } finally {
205
+ try { fs.rmSync(srcDir, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
206
+ try { fs.rmSync(dest, { recursive: true, force: true }); } catch (_e) { /* ignore */ }
207
+ }
208
+ }
209
+
210
+ async function run() {
211
+ await testTarRoundTrip();
212
+ await testSafeArchiveTarExtract();
213
+ testTarEntryPolicy();
214
+ await testTarChecksumDetection();
215
+ await testTarTruncationRefused();
216
+ await testBackupMigrateDirectoryToTar();
217
+ await testBackupTarFormatDefault();
218
+ await testBackupBundleTooLargeRefused();
219
+ }
220
+
221
+ module.exports = { run: run };
222
+
223
+ if (require.main === module) {
224
+ run().then(
225
+ function () { console.log("[archive-tar] OK — " + helpers.getChecks() + " checks passed"); },
226
+ function (e) { console.error("FAIL:", e && e.stack || e); process.exit(1); }
227
+ );
228
+ }