@coderook/cli 0.46.12 → 0.47.1

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.
Files changed (38) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/dist/cbx/src/core/cbx.js +110 -7
  3. package/dist/cbx/src/core/download.js +194 -27
  4. package/dist/cbx/src/core/tracks.js +4 -0
  5. package/dist/cbx/src/core/upload.js +2 -0
  6. package/dist/cbx/src/core/worktree.js +8 -1
  7. package/dist/cbx/src/local/durable.js +66 -0
  8. package/dist/cbx/src/local/repository.js +116 -11
  9. package/dist/cbx/src/local/store.js +84 -17
  10. package/dist/cbx/src/local/store_v2.js +7 -2
  11. package/dist/cbx/src/shared/native_engine.js +68 -12
  12. package/dist/cbx/src/shared/path_rules.js +231 -0
  13. package/dist/cbx/src/shared/safe_path.js +61 -24
  14. package/dist/cli/src/api.js +25 -2
  15. package/dist/cli/src/bin.js +2 -0
  16. package/dist/cli/src/build_command.js +48 -3
  17. package/dist/cli/src/build_pins.js +162 -0
  18. package/dist/cli/src/cli.js +65 -10
  19. package/dist/cli/src/config.js +47 -7
  20. package/dist/cli/src/import_command.js +24 -1
  21. package/dist/cli/src/mcp.js +12 -1
  22. package/dist/cli/src/mods_command.js +2 -0
  23. package/dist/cli/src/portable_python.js +29 -21
  24. package/dist/cli/src/runner.js +3 -1
  25. package/dist/cli/src/service_commands.js +4 -3
  26. package/dist/cli/src/settings_commands.js +1 -1
  27. package/dist/cli/src/terminal_guard.js +37 -0
  28. package/dist/cli/src/transfer_command.js +12 -2
  29. package/dist/cli/src/verify_command.js +14 -0
  30. package/dist/cli/src/workspace_machine.js +28 -4
  31. package/dist/cli/src/workspace_review.js +2 -0
  32. package/dist/cli.bundle.cjs +28322 -0
  33. package/engine-bin/darwin-arm64/cbx-engine +0 -0
  34. package/engine-bin/darwin-x64/cbx-engine +0 -0
  35. package/engine-bin/linux-arm64/cbx-engine +0 -0
  36. package/engine-bin/linux-x64/cbx-engine +0 -0
  37. package/engine-bin/win32-x64/cbx-engine.exe +0 -0
  38. package/package.json +1 -1
@@ -2,7 +2,7 @@
2
2
  "name": "coderook",
3
3
  "displayName": "CodeRook",
4
4
  "description": "Save, browse and restore whole-snapshot versions of a project on CodeRook, with cbx or plain git, from Claude Code.",
5
- "version": "0.46.12",
5
+ "version": "0.47.1",
6
6
  "author": {
7
7
  "name": "ACCA Gaming Productions",
8
8
  "url": "https://coderook.com"
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.FOOTER_MAGIC = exports.MANIFEST_MAGIC = exports.CHUNK_MAGIC = exports.HEADER_MAGIC = exports.cutPoints = void 0;
6
+ exports.DestinationOccupied = exports.FOOTER_MAGIC = exports.MANIFEST_MAGIC = exports.CHUNK_MAGIC = exports.HEADER_MAGIC = exports.cutPoints = void 0;
7
7
  exports.chunkFrame = chunkFrame;
8
8
  exports.openChunkFrame = openChunkFrame;
9
9
  exports.packBundle = packBundle;
@@ -33,6 +33,7 @@ const promises_1 = require("node:fs/promises");
33
33
  const node_path_1 = __importDefault(require("node:path"));
34
34
  const node_process_1 = __importDefault(require("node:process"));
35
35
  const safe_path_js_1 = require("../shared/safe_path.js");
36
+ const node_buffer_1 = require("node:buffer");
36
37
  const node_zlib_1 = require("node:zlib");
37
38
  const download_js_1 = require("./download.js");
38
39
  const chunking_js_1 = require("../shared/chunking.js");
@@ -51,6 +52,31 @@ const WRITTEN_FORMAT_VERSION = 1;
51
52
  const SUPPORTED_FORMAT_VERSIONS = new Set([1, 2]);
52
53
  const CODEC_NONE = 0;
53
54
  const CODEC_ZSTD = 1;
55
+ /*
56
+ Ceilings for what a bundle may declare. The largest chunk any profile cuts
57
+ is 32 MiB and a whole small file is under 8 MiB; a manifest for the
58
+ largest version the service accepts is far below its limit.
59
+ */
60
+ const MAX_CHUNK_BYTES = 256 * 1024 * 1024;
61
+ const MAX_MANIFEST_BYTES = 512 * 1024 * 1024;
62
+ /* A file is assembled in memory here, so it can be no larger than a Buffer. */
63
+ const BUFFER_LIMIT = node_buffer_1.constants.MAX_LENGTH;
64
+ /**
65
+ * zstd-decompress `stored`, refusing to produce more than `declared` bytes.
66
+ * Without the cap a few kilobytes of crafted zstd inflate until the process
67
+ * runs out of memory, whatever the record said it held.
68
+ */
69
+ function inflateAtMost(stored, declared, what) {
70
+ try {
71
+ return (0, node_zlib_1.zstdDecompressSync)(stored, { maxOutputLength: Math.max(1, declared) });
72
+ }
73
+ catch (error) {
74
+ if (error.code === "ERR_BUFFER_TOO_LARGE") {
75
+ throw new Error(`${what} inflates past the size it declares`);
76
+ }
77
+ throw error;
78
+ }
79
+ }
54
80
  const ZSTD_LEVEL = 3;
55
81
  const MIN_COMPRESSION_SAVING = 0.02;
56
82
  const READ_SIZE = 8 * 1024 * 1024;
@@ -121,7 +147,10 @@ function openChunkFrame(frame, expected) {
121
147
  if (codec !== CODEC_NONE && codec !== CODEC_ZSTD) {
122
148
  throw new Error(`Chunk ${expected.slice(0, 12)} uses an unknown codec (${codec})`);
123
149
  }
124
- const raw = codec === CODEC_ZSTD ? (0, node_zlib_1.zstdDecompressSync)(stored) : stored;
150
+ if (rawSize > MAX_CHUNK_BYTES) {
151
+ throw new Error(`Chunk ${expected.slice(0, 12)} declares a size it cannot have`);
152
+ }
153
+ const raw = codec === CODEC_ZSTD ? inflateAtMost(stored, rawSize, `Chunk ${expected.slice(0, 12)}`) : stored;
125
154
  if (raw.length !== rawSize || sha256(raw) !== expected) {
126
155
  throw new Error(`Chunk ${expected.slice(0, 12)} does not match its identity`);
127
156
  }
@@ -313,6 +342,18 @@ async function readManifest(source) {
313
342
  const manifestOffset = Number(footer.readBigUInt64LE(4));
314
343
  const recordLength = Number(footer.readBigUInt64LE(12));
315
344
  const expected = footer.subarray(20, 52).toString("hex");
345
+ /*
346
+ Sizes a bundle declares are checked against the file before anything is
347
+ allocated or decompressed for them. A footer naming a sixteen-exabyte
348
+ record, or a manifest that inflates to gigabytes, used to be believed
349
+ (audit, 16 November 2026).
350
+ */
351
+ if (recordLength < MANIFEST_HEADER_BYTES ||
352
+ manifestOffset < HEADER_BYTES ||
353
+ manifestOffset + recordLength > size - FOOTER_BYTES ||
354
+ recordLength > MAX_MANIFEST_BYTES) {
355
+ throw new Error("That bundle's manifest record is not where it should be");
356
+ }
316
357
  const record = Buffer.alloc(recordLength);
317
358
  await handle.read(record, 0, recordLength, manifestOffset);
318
359
  if (record.subarray(0, 4).toString("latin1") !== exports.MANIFEST_MAGIC) {
@@ -323,8 +364,11 @@ async function readManifest(source) {
323
364
  if (record.subarray(20, 52).toString("hex") !== expected) {
324
365
  throw new Error("That bundle's manifest digests disagree");
325
366
  }
367
+ if (storedLength > recordLength - MANIFEST_HEADER_BYTES || rawLength > MAX_MANIFEST_BYTES) {
368
+ throw new Error("That bundle's manifest declares more than it holds");
369
+ }
326
370
  const stored = record.subarray(MANIFEST_HEADER_BYTES, MANIFEST_HEADER_BYTES + storedLength);
327
- const raw = (0, node_zlib_1.zstdDecompressSync)(stored);
371
+ const raw = inflateAtMost(stored, rawLength, "That bundle's manifest");
328
372
  if (raw.length !== rawLength || sha256(raw) !== expected) {
329
373
  throw new Error("That bundle's manifest does not match its checksum");
330
374
  }
@@ -340,9 +384,42 @@ async function readManifest(source) {
340
384
  * verified against the digest the manifest recorded, so a damaged archive
341
385
  * cannot leave a half-written tree looking like a finished project.
342
386
  */
343
- async function unpackBundle(source, destination, report) {
387
+ /** Thrown when a bundle would replace a folder that already has something in it. */
388
+ class DestinationOccupied extends Error {
389
+ destination;
390
+ constructor(destination) {
391
+ super(`${destination} already exists and is not empty`);
392
+ this.destination = destination;
393
+ }
394
+ }
395
+ exports.DestinationOccupied = DestinationOccupied;
396
+ /** Whether something is already at this path: a file, or a folder with anything in it. */
397
+ async function occupied(destination) {
398
+ try {
399
+ const found = await (0, promises_1.stat)(destination);
400
+ return !found.isDirectory() || (await (0, promises_1.readdir)(destination)).length > 0;
401
+ }
402
+ catch (error) {
403
+ if (error.code === "ENOENT")
404
+ return false;
405
+ throw error;
406
+ }
407
+ }
408
+ async function unpackBundle(source, destination, report,
409
+ /*
410
+ The folder is replaced whole at the end. A bundle from somebody else
411
+ names that folder, so unpacking one into a folder that already held
412
+ work deleted it (audit, 16 November 2026). Replacing is now something
413
+ the person asks for.
414
+ */
415
+ options = {}) {
416
+ if (!options.replace && (await occupied(destination)))
417
+ throw new DestinationOccupied(destination);
344
418
  const manifest = await readManifest(source);
419
+ /* README.md and readme.md would be one file here; refused before anything is written. */
420
+ (0, safe_path_js_1.refuseClashes)(manifest.files.map((file) => file.path));
345
421
  const handle = await (0, promises_1.open)(source, "r");
422
+ const bundleSize = (await handle.stat()).size;
346
423
  const staging = `${destination}.incoming`;
347
424
  await (0, promises_1.rm)(staging, { recursive: true, force: true });
348
425
  // Solid packs mean several small files share one decoded chunk, so a
@@ -356,12 +433,23 @@ async function unpackBundle(source, destination, report) {
356
433
  const record = manifest.chunks[digest];
357
434
  if (!record)
358
435
  throw new Error(`The bundle is missing chunk ${digest.slice(0, 12)}`);
436
+ /* Inside the file and under the ceiling, before a byte is allocated for it. */
437
+ if (!Number.isSafeInteger(record.stored_size) ||
438
+ !Number.isSafeInteger(record.payload_offset) ||
439
+ !Number.isSafeInteger(record.raw_size) ||
440
+ record.stored_size < 0 ||
441
+ record.raw_size < 0 ||
442
+ record.payload_offset < HEADER_BYTES ||
443
+ record.payload_offset + record.stored_size > bundleSize ||
444
+ record.raw_size > MAX_CHUNK_BYTES) {
445
+ throw new Error("A chunk in that bundle declares a size it cannot have");
446
+ }
359
447
  const stored = Buffer.alloc(record.stored_size);
360
448
  await handle.read(stored, 0, record.stored_size, record.payload_offset);
361
449
  if (sha256(stored) !== record.stored_sha256) {
362
450
  throw new Error("A chunk in that bundle is damaged");
363
451
  }
364
- const raw = record.codec === CODEC_ZSTD ? (0, node_zlib_1.zstdDecompressSync)(stored) : stored;
452
+ const raw = record.codec === CODEC_ZSTD ? inflateAtMost(stored, record.raw_size, "A chunk in that bundle") : stored;
365
453
  if (raw.length !== record.raw_size || sha256(raw) !== digest) {
366
454
  throw new Error("A chunk in that bundle does not match its identity");
367
455
  }
@@ -393,6 +481,21 @@ async function unpackBundle(source, destination, report) {
393
481
  const full = (0, safe_path_js_1.inside)(staging, record.path);
394
482
  await (0, promises_1.mkdir)(node_path_1.default.dirname(full), { recursive: true });
395
483
  const pieces = [];
484
+ /*
485
+ A file is built only up to the size it declares: one chunk listed a
486
+ million times otherwise assembled into memory before the digest
487
+ check could fail.
488
+ */
489
+ let assembled = 0;
490
+ const add = (piece) => {
491
+ assembled += piece.length;
492
+ if (assembled > record.size)
493
+ throw new Error(`${record.path} did not survive the bundle intact`);
494
+ pieces.push(piece);
495
+ };
496
+ if (!Number.isSafeInteger(record.size) || record.size < 0 || record.size > BUFFER_LIMIT) {
497
+ throw new Error(`${record.path} declares a size the bundle cannot hold`);
498
+ }
396
499
  if (record.segments) {
397
500
  for (const segment of record.segments) {
398
501
  const raw = await chunkBytes(segment.chunk);
@@ -400,12 +503,12 @@ async function unpackBundle(source, destination, report) {
400
503
  if (segment.offset < 0 || end > raw.length) {
401
504
  throw new Error(`Invalid solid segment in ${record.path}`);
402
505
  }
403
- pieces.push(raw.subarray(segment.offset, end));
506
+ add(raw.subarray(segment.offset, end));
404
507
  }
405
508
  }
406
509
  else {
407
510
  for (const digest of record.chunks ?? [])
408
- pieces.push(await chunkBytes(digest));
511
+ add(await chunkBytes(digest));
409
512
  }
410
513
  const contents = Buffer.concat(pieces);
411
514
  if (contents.length !== record.size || sha256(contents) !== record.sha256) {
@@ -4,6 +4,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.Downloader = exports.DownloadFailed = exports.DownloadCancelled = void 0;
7
+ exports.placementProblem = placementProblem;
7
8
  exports.underway = underway;
8
9
  exports.plainReason = plainReason;
9
10
  exports.applyMode = applyMode;
@@ -23,6 +24,40 @@ const node_stream_1 = require("node:stream");
23
24
  const node_zlib_1 = require("node:zlib");
24
25
  const node_path_1 = __importDefault(require("node:path"));
25
26
  const safe_path_js_1 = require("../shared/safe_path.js");
27
+ const promises_3 = require("node:fs/promises");
28
+ /**
29
+ * Why a file of the version cannot be put at this path without harm, or null.
30
+ *
31
+ * Walks the path one name at a time from the folder: a link or junction on
32
+ * the way would carry the write somewhere else, a file where a folder is
33
+ * needed cannot hold it, and a folder where the file goes would have to be
34
+ * deleted whole. Nothing that does not exist yet is a problem.
35
+ */
36
+ async function placementProblem(destination, relative) {
37
+ const names = relative.split("/");
38
+ let at = destination;
39
+ for (const [index, name] of names.entries()) {
40
+ at = node_path_1.default.join(at, name);
41
+ const shown = names.slice(0, index + 1).join("/");
42
+ let found;
43
+ try {
44
+ found = await (0, promises_3.lstat)(at);
45
+ }
46
+ catch (error) {
47
+ if (error.code === "ENOENT")
48
+ return null;
49
+ throw error;
50
+ }
51
+ if (found.isSymbolicLink())
52
+ return `${shown} is a link to somewhere else`;
53
+ const last = index === names.length - 1;
54
+ if (last && found.isDirectory())
55
+ return `${shown} is a folder here, and the version has a file there`;
56
+ if (!last && !found.isDirectory())
57
+ return `${shown} is a file here, and the version has a folder there`;
58
+ }
59
+ return null;
60
+ }
26
61
  const chunking_js_1 = require("../shared/chunking.js");
27
62
  const identify_js_1 = require("./identify.js");
28
63
  const faults_js_1 = require("./faults.js");
@@ -120,6 +155,49 @@ async function pruneEmpty(root, removed) {
120
155
  * genuinely slow call is one repeated request.
121
156
  */
122
157
  const REQUEST_DEADLINE_MS = 180_000;
158
+ /*
159
+ How much a body may decode to. A gzip-stored object inflates by up to a
160
+ thousand times, and nothing said how far before the digest check, so one
161
+ small crafted answer could fill memory or the disk (audit, 16 November
162
+ 2026). A piece or file is capped at its own listed size; a solid pack at
163
+ the furthest member window it is asked for, never under PACK_FLOOR (packs
164
+ are cut at about 32 MiB) and never over PACK_CEILING.
165
+ */
166
+ const PACK_FLOOR = 64 * 1024 * 1024;
167
+ const PACK_CEILING = 1024 * 1024 * 1024;
168
+ /** A body that decoded to more than it may hold. */
169
+ class TooLarge extends Error {
170
+ /* Not worth repeating (retry.ts): the same answer would be just as large. */
171
+ status = 413;
172
+ constructor(what) {
173
+ super(`${what} is larger than the version says it is`);
174
+ }
175
+ }
176
+ /*
177
+ Whether `actual` is the digest a version listed. A file or piece listed
178
+ with no digest, or with something that is not one, matches nothing: the
179
+ checks here used to read "if there is a digest, compare", so an answer
180
+ that left it out was written unchecked (audit, 16 November 2026).
181
+ */
182
+ const DIGEST = /^[0-9a-f]{64}$/i;
183
+ function matches(actual, expected) {
184
+ return typeof expected === "string" && DIGEST.test(expected) && actual.toLowerCase() === expected.toLowerCase();
185
+ }
186
+ function packLimit(members) {
187
+ const furthest = members.reduce((most, member) => Math.max(most, (member.pack?.offset ?? 0) + (member.pack?.length ?? 0)), 0);
188
+ return Math.min(PACK_CEILING, Math.max(PACK_FLOOR, furthest));
189
+ }
190
+ /** gunzip `body`, refusing to produce more than `limit` bytes. */
191
+ function gunzipAtMost(body, limit, what) {
192
+ try {
193
+ return (0, node_zlib_1.gunzipSync)(body, { maxOutputLength: Math.max(1, limit) });
194
+ }
195
+ catch (error) {
196
+ if (error.code === "ERR_BUFFER_TOO_LARGE")
197
+ throw new TooLarge(what);
198
+ throw error;
199
+ }
200
+ }
123
201
  /**
124
202
  * And how long a whole-version archive may take to arrive.
125
203
  *
@@ -201,6 +279,8 @@ const PLAIN = {
201
279
  function plainReason(error) {
202
280
  if (!(error instanceof Error))
203
281
  return String(error);
282
+ if (error instanceof TooLarge)
283
+ return error.message;
204
284
  const status = error.status;
205
285
  if (typeof status === "number") {
206
286
  /* The fallback message is only the route; the service's own words are better. */
@@ -310,12 +390,16 @@ class Downloader {
310
390
  }
311
391
  }
312
392
  /** A whole response body and its headers, under the retry rule. */
313
- async bytes(route, what, halt) {
393
+ async bytes(route, what, halt,
394
+ /* The most this body may decode to; see PACK_FLOOR. */
395
+ limit) {
314
396
  return this.repeat(async () => {
315
397
  const reply = await this.attempt(route, REQUEST_DEADLINE_MS, halt);
316
398
  const raw = Buffer.from(await reply.arrayBuffer());
317
399
  /* Sent as stored (see attempt): unpacked here instead of in the service. */
318
- const body = reply.headers.get("x-coderook-encoding") === "gzip" ? (0, node_zlib_1.gunzipSync)(raw) : raw;
400
+ const body = reply.headers.get("x-coderook-encoding") === "gzip" ? gunzipAtMost(raw, limit, what) : raw;
401
+ if (body.length > limit)
402
+ throw new TooLarge(what);
319
403
  return { body, headers: reply.headers };
320
404
  }, { what, halt });
321
405
  }
@@ -533,10 +617,29 @@ class Downloader {
533
617
  * belongs to in order to find out whether it survives the trip.
534
618
  */
535
619
  async fileTo(repositoryId, versionId, file, target) {
620
+ /*
621
+ Fetched beside the file and checked before it replaces anything. It
622
+ was streamed straight over the file and never compared, so a cut or
623
+ wrong download destroyed the copy it was meant to restore
624
+ (audit, 16 November 2026).
625
+ */
626
+ if (!/^[0-9a-f]{64}$/i.test(file.sha256 ?? "")) {
627
+ throw new Error(`${file.path} has no digest to check it against; nothing was written.`);
628
+ }
536
629
  await (0, promises_1.mkdir)(node_path_1.default.dirname(target), { recursive: true });
537
- const digest = await this.fetchInto(repositoryId, versionId, file, target);
538
- await applyMode(target, file.executable === true);
539
- return digest;
630
+ const incoming = `${target}.cbx-incoming-${process.pid}-${Date.now()}`;
631
+ try {
632
+ const digest = await this.fetchInto(repositoryId, versionId, file, incoming);
633
+ if (digest.toLowerCase() !== file.sha256.toLowerCase()) {
634
+ throw new Error(`${file.path} did not arrive intact; the file here was left as it was.`);
635
+ }
636
+ await applyMode(incoming, file.executable === true);
637
+ await (0, promises_1.rename)(incoming, target);
638
+ return digest;
639
+ }
640
+ finally {
641
+ await (0, promises_1.rm)(incoming, { force: true });
642
+ }
540
643
  }
541
644
  /**
542
645
  * Reconstruct and verify every file in a Version without materialising the
@@ -581,7 +684,7 @@ class Downloader {
581
684
  if (packId && restoredPacks.has(packId))
582
685
  continue;
583
686
  if (packId) {
584
- const reply = await this.bytes(`/v1/repositories/${repositoryId}/objects/${packId}`, packName(packed.get(packId) ?? []));
687
+ const reply = await this.bytes(`/v1/repositories/${repositoryId}/objects/${packId}`, packName(packed.get(packId) ?? []), undefined, packLimit(packed.get(packId) ?? []));
585
688
  const body = reply.body;
586
689
  const packDigest = (0, node_crypto_1.createHash)("sha256").update(body).digest("hex");
587
690
  const expectedPackDigest = reply.headers.get("x-coderook-sha256");
@@ -597,7 +700,7 @@ class Downloader {
597
700
  const digest = (0, node_crypto_1.createHash)("sha256")
598
701
  .update(body.subarray(offset, offset + length))
599
702
  .digest("hex");
600
- if (member.sha256 && digest !== member.sha256) {
703
+ if (!matches(digest, member.sha256)) {
601
704
  throw new Error(`${member.path} did not arrive intact`);
602
705
  }
603
706
  manifest[member.path] = digest;
@@ -609,7 +712,7 @@ class Downloader {
609
712
  continue;
610
713
  }
611
714
  const digest = await this.fetchInto(repositoryId, versionId, file, temporary);
612
- if (file.sha256 && digest !== file.sha256) {
715
+ if (!matches(digest, file.sha256)) {
613
716
  throw new Error(`${file.path} did not arrive intact`);
614
717
  }
615
718
  manifest[file.path] = digest;
@@ -650,7 +753,7 @@ class Downloader {
650
753
  try {
651
754
  for (const [packId, members] of packs) {
652
755
  this.check();
653
- const reply = await this.bytes(`/v1/repositories/${repositoryId}/objects/${packId}`, packName(members));
756
+ const reply = await this.bytes(`/v1/repositories/${repositoryId}/objects/${packId}`, packName(members), undefined, packLimit(members));
654
757
  const body = reply.body;
655
758
  const expected = reply.headers.get("x-coderook-sha256");
656
759
  if (expected && (0, node_crypto_1.createHash)("sha256").update(body).digest("hex") !== expected) {
@@ -662,7 +765,7 @@ class Downloader {
662
765
  throw new Error(`${member.path} points outside its solid pack`);
663
766
  }
664
767
  const bytes = Buffer.from(body.subarray(offset, offset + length));
665
- if ((0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex") !== member.sha256) {
768
+ if (!matches((0, node_crypto_1.createHash)("sha256").update(bytes).digest("hex"), member.sha256)) {
666
769
  throw new Error(`${member.path} did not arrive intact`);
667
770
  }
668
771
  await visit(member, { bytes });
@@ -671,7 +774,7 @@ class Downloader {
671
774
  for (const file of single) {
672
775
  this.check();
673
776
  const digest = await this.fetchInto(repositoryId, versionId, file, temporary);
674
- if (digest !== file.sha256)
777
+ if (!matches(digest, file.sha256))
675
778
  throw new Error(`${file.path} did not arrive intact`);
676
779
  await visit(file, { path: temporary });
677
780
  await (0, promises_1.rm)(temporary, { force: true });
@@ -758,9 +861,9 @@ class Downloader {
758
861
  const digest = await this.streamTo(file.objectId && !file.sealed
759
862
  ? `/v1/repositories/${repositoryId}/objects/${file.objectId}`
760
863
  : `/v1/repositories/${repositoryId}/versions/${versionId}/file` +
761
- `?path=${encodeURIComponent(file.path)}`, file.path, target, halt);
864
+ `?path=${encodeURIComponent(file.path)}`, file.path, target, halt, file.sourceSize);
762
865
  if (file.sha256 && digest !== file.sha256) {
763
- if (await recoverGzipFile(target, file.sha256)) {
866
+ if (await recoverGzipFile(target, file.sha256, file.sourceSize)) {
764
867
  this.recoveredFromGzip.push(file.path);
765
868
  return file.sha256;
766
869
  }
@@ -770,7 +873,7 @@ class Downloader {
770
873
  const whole = (0, node_crypto_1.createHash)("sha256");
771
874
  let recovered = false;
772
875
  // Captured so the generator below does not need `this` rebound.
773
- const fetchPiece = (route, what) => this.bytes(route, what, halt);
876
+ const fetchPiece = (route, what, limit) => this.bytes(route, what, halt, limit);
774
877
  const check = () => this.check();
775
878
  /*
776
879
  Each piece is its own retried request, so a connection lost partway
@@ -816,7 +919,7 @@ class Downloader {
816
919
  counted();
817
920
  return local;
818
921
  }
819
- return fetchPiece(`/v1/repositories/${repositoryId}/objects/${piece.objectId}`, `${file.path} (piece ${at + 1} of ${pieces.length})`);
922
+ return fetchPiece(`/v1/repositories/${repositoryId}/objects/${piece.objectId}`, `${file.path} (piece ${at + 1} of ${pieces.length})`, piece.sourceSize);
820
923
  });
821
924
  /* Awaited in turn below; this only stops an early stop leaving it unhandled. */
822
925
  reply.catch(() => undefined);
@@ -839,8 +942,8 @@ class Downloader {
839
942
  in seven gigabytes is wrong and nothing about what.
840
943
  */
841
944
  const digest = (0, node_crypto_1.createHash)("sha256").update(body).digest("hex");
842
- if (piece.sha256 && digest !== piece.sha256) {
843
- const plain = gunzippedMatching(body, piece.sha256);
945
+ if (!matches(digest, piece.sha256)) {
946
+ const plain = gunzippedMatching(body, piece.sha256, piece.sourceSize);
844
947
  if (!plain) {
845
948
  throw new Error(`${file.path}: piece ${at + 1} of ${pieces.length} ` +
846
949
  `did not arrive intact`);
@@ -879,7 +982,9 @@ class Downloader {
879
982
  * different answers spliced together; the digest is checked by the caller
880
983
  * either way.
881
984
  */
882
- async streamTo(route, what, target, halt) {
985
+ async streamTo(route, what, target, halt,
986
+ /* The most the file may be once decoded: its listed size. */
987
+ limit) {
883
988
  let resumable = false;
884
989
  let before = 0;
885
990
  let hash = (0, node_crypto_1.createHash)("sha256");
@@ -904,13 +1009,35 @@ class Downloader {
904
1009
  from = 0;
905
1010
  reply = await this.attempt(route, REQUEST_DEADLINE_MS, halt);
906
1011
  }
1012
+ /*
1013
+ A partial answer that cannot be appended (see below) is no use as
1014
+ a whole file either: asked for again from the start.
1015
+ */
1016
+ const usablePart = (one) => one.headers.get("x-coderook-encoding") !== "gzip" && rangeStart(one.headers) === from;
1017
+ if (from > 0 && reply.status === 206 && !usablePart(reply)) {
1018
+ await reply.body?.cancel().catch(() => undefined);
1019
+ from = 0;
1020
+ reply = await this.attempt(route, REQUEST_DEADLINE_MS, halt);
1021
+ }
907
1022
  before = from;
908
- const append = from > 0 && reply.status === 206 && rangeStart(reply.headers) === from;
909
- if (reply.status !== 206) {
1023
+ /*
1024
+ A gzip-stored body arrives compressed and is written decompressed,
1025
+ so what reached the disk is counted in one byte space and a range
1026
+ is asked for in the other. Resuming from the disk's length then
1027
+ spliced a later part of the compressed stream onto the decoded
1028
+ start (audit, 16 November 2026). Such a body is fetched whole.
1029
+ */
1030
+ const gzipped = reply.headers.get("x-coderook-encoding") === "gzip";
1031
+ const append = !gzipped && from > 0 && reply.status === 206 && rangeStart(reply.headers) === from;
1032
+ if (gzipped) {
1033
+ resumable = false;
1034
+ }
1035
+ else if (reply.status !== 206) {
910
1036
  resumable = reply.headers.get("accept-ranges") === "bytes";
911
1037
  }
912
1038
  hash = append ? await digestPrefix(target) : (0, node_crypto_1.createHash)("sha256");
913
1039
  const sink = (0, node_fs_1.createWriteStream)(target, { flags: append ? "a" : "w" });
1040
+ let decoded = append ? from : 0;
914
1041
  if (!reply.body) {
915
1042
  sink.end();
916
1043
  await new Promise((resolve, reject) => {
@@ -929,12 +1056,17 @@ class Downloader {
929
1056
  return;
930
1057
  }
931
1058
  const buffer = Buffer.from(block);
1059
+ decoded += buffer.length;
1060
+ if (decoded > Math.max(0, limit)) {
1061
+ done(new TooLarge(what));
1062
+ return;
1063
+ }
932
1064
  hash.update(buffer);
933
1065
  done(null, buffer);
934
1066
  },
935
1067
  });
936
1068
  /* Sent as stored (see attempt): unpacked on the way to the disk. */
937
- if (reply.headers.get("x-coderook-encoding") === "gzip") {
1069
+ if (gzipped) {
938
1070
  await (0, promises_2.pipeline)(source, (0, node_zlib_1.createGunzip)(), hashing, sink);
939
1071
  }
940
1072
  else {
@@ -1091,7 +1223,13 @@ class Downloader {
1091
1223
  if (reason) {
1092
1224
  throw new Error(`That version contains an unsafe path (${reason}): ${file.path}`);
1093
1225
  }
1226
+ /* And every file has a digest to be checked against, as collect() requires. */
1227
+ if (!DIGEST.test(file.sha256 ?? "")) {
1228
+ throw new Error(`${file.path} has no digest to check it against; nothing was written.`);
1229
+ }
1094
1230
  }
1231
+ /* Two paths that are one file here would overwrite each other in staging. */
1232
+ (0, safe_path_js_1.refuseClashes)(files.map((file) => file.path));
1095
1233
  const told = { at: 0 };
1096
1234
  const sayProgress = (where) => {
1097
1235
  const now = Date.now();
@@ -1117,7 +1255,7 @@ class Downloader {
1117
1255
  so fetch the decoded pack once, verify it, and materialise every
1118
1256
  member before releasing the buffer.
1119
1257
  */
1120
- const reply = await this.bytes(`/v1/repositories/${repositoryId}/objects/${packId}`, packName(packed.get(packId) ?? []), halt.signal);
1258
+ const reply = await this.bytes(`/v1/repositories/${repositoryId}/objects/${packId}`, packName(packed.get(packId) ?? []), halt.signal, packLimit(packed.get(packId) ?? []));
1121
1259
  const body = reply.body;
1122
1260
  const packDigest = (0, node_crypto_1.createHash)("sha256").update(body).digest("hex");
1123
1261
  const expectedPackDigest = reply.headers.get("x-coderook-sha256");
@@ -1136,7 +1274,7 @@ class Downloader {
1136
1274
  }
1137
1275
  const contents = body.subarray(offset, offset + length);
1138
1276
  const digest = (0, node_crypto_1.createHash)("sha256").update(contents).digest("hex");
1139
- if (member.sha256 && digest !== member.sha256) {
1277
+ if (!matches(digest, member.sha256)) {
1140
1278
  throw new Error(`${member.path} did not arrive intact`);
1141
1279
  }
1142
1280
  const full = (0, safe_path_js_1.inside)(staging, member.path);
@@ -1162,7 +1300,7 @@ class Downloader {
1162
1300
  which is the failure that produces bytes that are all present, all
1163
1301
  verified, and wrong.
1164
1302
  */
1165
- if (file.sha256 && digest !== file.sha256) {
1303
+ if (!matches(digest, file.sha256)) {
1166
1304
  throw new Error(`${file.path} did not arrive intact`);
1167
1305
  }
1168
1306
  manifest[file.path] = digest;
@@ -1291,6 +1429,26 @@ class Downloader {
1291
1429
  }
1292
1430
  return made;
1293
1431
  };
1432
+ /*
1433
+ Looked at before anything here changes. A file arriving where the
1434
+ folder holds a directory used to remove the directory, recursively,
1435
+ with whatever unsaved or ignored work was in it; and a path through a
1436
+ link or junction already in the folder wrote or deleted outside it
1437
+ (audit, 16 November 2026). Either way the fetch now stops untouched.
1438
+ */
1439
+ const blocked = [];
1440
+ for (const file of files) {
1441
+ if (kept.has(file.path))
1442
+ continue;
1443
+ const problem = await placementProblem(destination, file.path);
1444
+ if (problem)
1445
+ blocked.push(problem);
1446
+ if (blocked.length >= 5)
1447
+ break;
1448
+ }
1449
+ if (blocked.length) {
1450
+ throw new Error(`Nothing was changed, because placing this version would remove or write through something already here:\n ${blocked.join("\n ")}\nMove those aside and fetch again.`);
1451
+ }
1294
1452
  let nextToPlace = 0;
1295
1453
  let placingFailed = false;
1296
1454
  const placeLane = async () => {
@@ -1347,6 +1505,9 @@ class Downloader {
1347
1505
  /* A path it must not write is not one it may delete either. */
1348
1506
  if ((0, safe_path_js_1.whyUnsafe)(gone))
1349
1507
  continue;
1508
+ /* Nor one reached through a link, or one that is now a folder. */
1509
+ if (await placementProblem(destination, gone))
1510
+ continue;
1350
1511
  const target = (0, safe_path_js_1.inside)(destination, gone);
1351
1512
  /*
1352
1513
  The version dropped it — but if the bytes here are no longer the
@@ -1404,11 +1565,11 @@ function packName(members) {
1404
1565
  : first;
1405
1566
  }
1406
1567
  /** The gunzipped bytes when they hash to `expected`, otherwise null. */
1407
- function gunzippedMatching(body, expected) {
1568
+ function gunzippedMatching(body, expected, limit) {
1408
1569
  if (body.length < 2 || body[0] !== 0x1f || body[1] !== 0x8b)
1409
1570
  return null;
1410
1571
  try {
1411
- const plain = (0, node_zlib_1.gunzipSync)(body);
1572
+ const plain = (0, node_zlib_1.gunzipSync)(body, { maxOutputLength: Math.max(1, limit) });
1412
1573
  return (0, node_crypto_1.createHash)("sha256").update(plain).digest("hex") === expected ? plain : null;
1413
1574
  }
1414
1575
  catch {
@@ -1419,7 +1580,7 @@ function gunzippedMatching(body, expected) {
1419
1580
  * Replace a file that arrived still gzip-compressed with its contents, when
1420
1581
  * those contents hash to `expected`. Streamed, so a large file is never held.
1421
1582
  */
1422
- async function recoverGzipFile(target, expected) {
1583
+ async function recoverGzipFile(target, expected, limit) {
1423
1584
  const handle = await (0, promises_1.open)(target, "r");
1424
1585
  const magic = Buffer.alloc(2);
1425
1586
  try {
@@ -1432,9 +1593,15 @@ async function recoverGzipFile(target, expected) {
1432
1593
  return false;
1433
1594
  const temporary = `${target}.gunzip`;
1434
1595
  const hash = (0, node_crypto_1.createHash)("sha256");
1596
+ let decoded = 0;
1435
1597
  try {
1436
1598
  await (0, promises_2.pipeline)((0, node_fs_1.createReadStream)(target), (0, node_zlib_1.createGunzip)(), new node_stream_1.Transform({
1437
1599
  transform(chunk, _encoding, done) {
1600
+ decoded += chunk.length;
1601
+ if (decoded > limit) {
1602
+ done(new TooLarge(target));
1603
+ return;
1604
+ }
1438
1605
  hash.update(chunk);
1439
1606
  done(null, chunk);
1440
1607
  },
@@ -85,6 +85,8 @@ class Tracks {
85
85
  if (!token)
86
86
  throw new Error("Sign in again");
87
87
  const response = await fetch(`${this.credentials.origin()}${route}`, {
88
+ /* Every outward request has a deadline (audit, 16 November 2026). */
89
+ signal: AbortSignal.timeout(120_000),
88
90
  method: init?.method ?? "GET",
89
91
  headers: {
90
92
  accept: "application/json",
@@ -301,6 +303,7 @@ class Tracks {
301
303
  throw new Error("Sign in again");
302
304
  const response = await fetch(`${this.credentials.origin()}/v1/repositories/${repositoryId}` +
303
305
  `/versions/${versionId}/file?path=${encodeURIComponent(path)}`, {
306
+ signal: AbortSignal.timeout(10 * 60_000),
304
307
  headers: {
305
308
  authorization: `Bearer ${token}`,
306
309
  "user-agent": "CodeRook/0.1",
@@ -344,6 +347,7 @@ class Tracks {
344
347
  const response = await fetch(`${this.credentials.origin()}/v1/repositories/${repositoryId}` +
345
348
  `/objects/${digest}?kind=chunk&role=chunk&logicalSize=${bytes.byteLength}` +
346
349
  `&mediaType=${encodeURIComponent(mediaTypeForPath(path))}`, {
350
+ signal: AbortSignal.timeout(10 * 60_000),
347
351
  method: "PUT",
348
352
  headers: {
349
353
  authorization: `Bearer ${token}`,