@coderook/cli 0.47.0 → 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.
@@ -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.47.0",
5
+ "version": "0.47.1",
6
6
  "author": {
7
7
  "name": "ACCA Gaming Productions",
8
8
  "url": "https://coderook.com"
@@ -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
  }
@@ -372,7 +416,10 @@ options = {}) {
372
416
  if (!options.replace && (await occupied(destination)))
373
417
  throw new DestinationOccupied(destination);
374
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));
375
421
  const handle = await (0, promises_1.open)(source, "r");
422
+ const bundleSize = (await handle.stat()).size;
376
423
  const staging = `${destination}.incoming`;
377
424
  await (0, promises_1.rm)(staging, { recursive: true, force: true });
378
425
  // Solid packs mean several small files share one decoded chunk, so a
@@ -386,12 +433,23 @@ options = {}) {
386
433
  const record = manifest.chunks[digest];
387
434
  if (!record)
388
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
+ }
389
447
  const stored = Buffer.alloc(record.stored_size);
390
448
  await handle.read(stored, 0, record.stored_size, record.payload_offset);
391
449
  if (sha256(stored) !== record.stored_sha256) {
392
450
  throw new Error("A chunk in that bundle is damaged");
393
451
  }
394
- 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;
395
453
  if (raw.length !== record.raw_size || sha256(raw) !== digest) {
396
454
  throw new Error("A chunk in that bundle does not match its identity");
397
455
  }
@@ -423,6 +481,21 @@ options = {}) {
423
481
  const full = (0, safe_path_js_1.inside)(staging, record.path);
424
482
  await (0, promises_1.mkdir)(node_path_1.default.dirname(full), { recursive: true });
425
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
+ }
426
499
  if (record.segments) {
427
500
  for (const segment of record.segments) {
428
501
  const raw = await chunkBytes(segment.chunk);
@@ -430,12 +503,12 @@ options = {}) {
430
503
  if (segment.offset < 0 || end > raw.length) {
431
504
  throw new Error(`Invalid solid segment in ${record.path}`);
432
505
  }
433
- pieces.push(raw.subarray(segment.offset, end));
506
+ add(raw.subarray(segment.offset, end));
434
507
  }
435
508
  }
436
509
  else {
437
510
  for (const digest of record.chunks ?? [])
438
- pieces.push(await chunkBytes(digest));
511
+ add(await chunkBytes(digest));
439
512
  }
440
513
  const contents = Buffer.concat(pieces);
441
514
  if (contents.length !== record.size || sha256(contents) !== record.sha256) {
@@ -155,6 +155,49 @@ async function pruneEmpty(root, removed) {
155
155
  * genuinely slow call is one repeated request.
156
156
  */
157
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
+ }
158
201
  /**
159
202
  * And how long a whole-version archive may take to arrive.
160
203
  *
@@ -236,6 +279,8 @@ const PLAIN = {
236
279
  function plainReason(error) {
237
280
  if (!(error instanceof Error))
238
281
  return String(error);
282
+ if (error instanceof TooLarge)
283
+ return error.message;
239
284
  const status = error.status;
240
285
  if (typeof status === "number") {
241
286
  /* The fallback message is only the route; the service's own words are better. */
@@ -345,12 +390,16 @@ class Downloader {
345
390
  }
346
391
  }
347
392
  /** A whole response body and its headers, under the retry rule. */
348
- async bytes(route, what, halt) {
393
+ async bytes(route, what, halt,
394
+ /* The most this body may decode to; see PACK_FLOOR. */
395
+ limit) {
349
396
  return this.repeat(async () => {
350
397
  const reply = await this.attempt(route, REQUEST_DEADLINE_MS, halt);
351
398
  const raw = Buffer.from(await reply.arrayBuffer());
352
399
  /* Sent as stored (see attempt): unpacked here instead of in the service. */
353
- 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);
354
403
  return { body, headers: reply.headers };
355
404
  }, { what, halt });
356
405
  }
@@ -635,7 +684,7 @@ class Downloader {
635
684
  if (packId && restoredPacks.has(packId))
636
685
  continue;
637
686
  if (packId) {
638
- 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) ?? []));
639
688
  const body = reply.body;
640
689
  const packDigest = (0, node_crypto_1.createHash)("sha256").update(body).digest("hex");
641
690
  const expectedPackDigest = reply.headers.get("x-coderook-sha256");
@@ -651,7 +700,7 @@ class Downloader {
651
700
  const digest = (0, node_crypto_1.createHash)("sha256")
652
701
  .update(body.subarray(offset, offset + length))
653
702
  .digest("hex");
654
- if (member.sha256 && digest !== member.sha256) {
703
+ if (!matches(digest, member.sha256)) {
655
704
  throw new Error(`${member.path} did not arrive intact`);
656
705
  }
657
706
  manifest[member.path] = digest;
@@ -663,7 +712,7 @@ class Downloader {
663
712
  continue;
664
713
  }
665
714
  const digest = await this.fetchInto(repositoryId, versionId, file, temporary);
666
- if (file.sha256 && digest !== file.sha256) {
715
+ if (!matches(digest, file.sha256)) {
667
716
  throw new Error(`${file.path} did not arrive intact`);
668
717
  }
669
718
  manifest[file.path] = digest;
@@ -704,7 +753,7 @@ class Downloader {
704
753
  try {
705
754
  for (const [packId, members] of packs) {
706
755
  this.check();
707
- 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));
708
757
  const body = reply.body;
709
758
  const expected = reply.headers.get("x-coderook-sha256");
710
759
  if (expected && (0, node_crypto_1.createHash)("sha256").update(body).digest("hex") !== expected) {
@@ -716,7 +765,7 @@ class Downloader {
716
765
  throw new Error(`${member.path} points outside its solid pack`);
717
766
  }
718
767
  const bytes = Buffer.from(body.subarray(offset, offset + length));
719
- 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)) {
720
769
  throw new Error(`${member.path} did not arrive intact`);
721
770
  }
722
771
  await visit(member, { bytes });
@@ -725,7 +774,7 @@ class Downloader {
725
774
  for (const file of single) {
726
775
  this.check();
727
776
  const digest = await this.fetchInto(repositoryId, versionId, file, temporary);
728
- if (digest !== file.sha256)
777
+ if (!matches(digest, file.sha256))
729
778
  throw new Error(`${file.path} did not arrive intact`);
730
779
  await visit(file, { path: temporary });
731
780
  await (0, promises_1.rm)(temporary, { force: true });
@@ -812,9 +861,9 @@ class Downloader {
812
861
  const digest = await this.streamTo(file.objectId && !file.sealed
813
862
  ? `/v1/repositories/${repositoryId}/objects/${file.objectId}`
814
863
  : `/v1/repositories/${repositoryId}/versions/${versionId}/file` +
815
- `?path=${encodeURIComponent(file.path)}`, file.path, target, halt);
864
+ `?path=${encodeURIComponent(file.path)}`, file.path, target, halt, file.sourceSize);
816
865
  if (file.sha256 && digest !== file.sha256) {
817
- if (await recoverGzipFile(target, file.sha256)) {
866
+ if (await recoverGzipFile(target, file.sha256, file.sourceSize)) {
818
867
  this.recoveredFromGzip.push(file.path);
819
868
  return file.sha256;
820
869
  }
@@ -824,7 +873,7 @@ class Downloader {
824
873
  const whole = (0, node_crypto_1.createHash)("sha256");
825
874
  let recovered = false;
826
875
  // Captured so the generator below does not need `this` rebound.
827
- const fetchPiece = (route, what) => this.bytes(route, what, halt);
876
+ const fetchPiece = (route, what, limit) => this.bytes(route, what, halt, limit);
828
877
  const check = () => this.check();
829
878
  /*
830
879
  Each piece is its own retried request, so a connection lost partway
@@ -870,7 +919,7 @@ class Downloader {
870
919
  counted();
871
920
  return local;
872
921
  }
873
- 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);
874
923
  });
875
924
  /* Awaited in turn below; this only stops an early stop leaving it unhandled. */
876
925
  reply.catch(() => undefined);
@@ -893,8 +942,8 @@ class Downloader {
893
942
  in seven gigabytes is wrong and nothing about what.
894
943
  */
895
944
  const digest = (0, node_crypto_1.createHash)("sha256").update(body).digest("hex");
896
- if (piece.sha256 && digest !== piece.sha256) {
897
- const plain = gunzippedMatching(body, piece.sha256);
945
+ if (!matches(digest, piece.sha256)) {
946
+ const plain = gunzippedMatching(body, piece.sha256, piece.sourceSize);
898
947
  if (!plain) {
899
948
  throw new Error(`${file.path}: piece ${at + 1} of ${pieces.length} ` +
900
949
  `did not arrive intact`);
@@ -933,7 +982,9 @@ class Downloader {
933
982
  * different answers spliced together; the digest is checked by the caller
934
983
  * either way.
935
984
  */
936
- 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) {
937
988
  let resumable = false;
938
989
  let before = 0;
939
990
  let hash = (0, node_crypto_1.createHash)("sha256");
@@ -958,13 +1009,35 @@ class Downloader {
958
1009
  from = 0;
959
1010
  reply = await this.attempt(route, REQUEST_DEADLINE_MS, halt);
960
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
+ }
961
1022
  before = from;
962
- const append = from > 0 && reply.status === 206 && rangeStart(reply.headers) === from;
963
- 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) {
964
1036
  resumable = reply.headers.get("accept-ranges") === "bytes";
965
1037
  }
966
1038
  hash = append ? await digestPrefix(target) : (0, node_crypto_1.createHash)("sha256");
967
1039
  const sink = (0, node_fs_1.createWriteStream)(target, { flags: append ? "a" : "w" });
1040
+ let decoded = append ? from : 0;
968
1041
  if (!reply.body) {
969
1042
  sink.end();
970
1043
  await new Promise((resolve, reject) => {
@@ -983,12 +1056,17 @@ class Downloader {
983
1056
  return;
984
1057
  }
985
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
+ }
986
1064
  hash.update(buffer);
987
1065
  done(null, buffer);
988
1066
  },
989
1067
  });
990
1068
  /* Sent as stored (see attempt): unpacked on the way to the disk. */
991
- if (reply.headers.get("x-coderook-encoding") === "gzip") {
1069
+ if (gzipped) {
992
1070
  await (0, promises_2.pipeline)(source, (0, node_zlib_1.createGunzip)(), hashing, sink);
993
1071
  }
994
1072
  else {
@@ -1145,7 +1223,13 @@ class Downloader {
1145
1223
  if (reason) {
1146
1224
  throw new Error(`That version contains an unsafe path (${reason}): ${file.path}`);
1147
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
+ }
1148
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));
1149
1233
  const told = { at: 0 };
1150
1234
  const sayProgress = (where) => {
1151
1235
  const now = Date.now();
@@ -1171,7 +1255,7 @@ class Downloader {
1171
1255
  so fetch the decoded pack once, verify it, and materialise every
1172
1256
  member before releasing the buffer.
1173
1257
  */
1174
- 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) ?? []));
1175
1259
  const body = reply.body;
1176
1260
  const packDigest = (0, node_crypto_1.createHash)("sha256").update(body).digest("hex");
1177
1261
  const expectedPackDigest = reply.headers.get("x-coderook-sha256");
@@ -1190,7 +1274,7 @@ class Downloader {
1190
1274
  }
1191
1275
  const contents = body.subarray(offset, offset + length);
1192
1276
  const digest = (0, node_crypto_1.createHash)("sha256").update(contents).digest("hex");
1193
- if (member.sha256 && digest !== member.sha256) {
1277
+ if (!matches(digest, member.sha256)) {
1194
1278
  throw new Error(`${member.path} did not arrive intact`);
1195
1279
  }
1196
1280
  const full = (0, safe_path_js_1.inside)(staging, member.path);
@@ -1216,7 +1300,7 @@ class Downloader {
1216
1300
  which is the failure that produces bytes that are all present, all
1217
1301
  verified, and wrong.
1218
1302
  */
1219
- if (file.sha256 && digest !== file.sha256) {
1303
+ if (!matches(digest, file.sha256)) {
1220
1304
  throw new Error(`${file.path} did not arrive intact`);
1221
1305
  }
1222
1306
  manifest[file.path] = digest;
@@ -1481,11 +1565,11 @@ function packName(members) {
1481
1565
  : first;
1482
1566
  }
1483
1567
  /** The gunzipped bytes when they hash to `expected`, otherwise null. */
1484
- function gunzippedMatching(body, expected) {
1568
+ function gunzippedMatching(body, expected, limit) {
1485
1569
  if (body.length < 2 || body[0] !== 0x1f || body[1] !== 0x8b)
1486
1570
  return null;
1487
1571
  try {
1488
- const plain = (0, node_zlib_1.gunzipSync)(body);
1572
+ const plain = (0, node_zlib_1.gunzipSync)(body, { maxOutputLength: Math.max(1, limit) });
1489
1573
  return (0, node_crypto_1.createHash)("sha256").update(plain).digest("hex") === expected ? plain : null;
1490
1574
  }
1491
1575
  catch {
@@ -1496,7 +1580,7 @@ function gunzippedMatching(body, expected) {
1496
1580
  * Replace a file that arrived still gzip-compressed with its contents, when
1497
1581
  * those contents hash to `expected`. Streamed, so a large file is never held.
1498
1582
  */
1499
- async function recoverGzipFile(target, expected) {
1583
+ async function recoverGzipFile(target, expected, limit) {
1500
1584
  const handle = await (0, promises_1.open)(target, "r");
1501
1585
  const magic = Buffer.alloc(2);
1502
1586
  try {
@@ -1509,9 +1593,15 @@ async function recoverGzipFile(target, expected) {
1509
1593
  return false;
1510
1594
  const temporary = `${target}.gunzip`;
1511
1595
  const hash = (0, node_crypto_1.createHash)("sha256");
1596
+ let decoded = 0;
1512
1597
  try {
1513
1598
  await (0, promises_2.pipeline)((0, node_fs_1.createReadStream)(target), (0, node_zlib_1.createGunzip)(), new node_stream_1.Transform({
1514
1599
  transform(chunk, _encoding, done) {
1600
+ decoded += chunk.length;
1601
+ if (decoded > limit) {
1602
+ done(new TooLarge(target));
1603
+ return;
1604
+ }
1515
1605
  hash.update(chunk);
1516
1606
  done(null, chunk);
1517
1607
  },
@@ -0,0 +1,66 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.syncDirectory = syncDirectory;
7
+ exports.writeDurably = writeDurably;
8
+ /**
9
+ * Writes a local history can rely on after a power cut.
10
+ *
11
+ * A rename makes a write atomic, not durable: until the file's bytes and the
12
+ * folder's entry reach the disk, a crash can leave a line pointing at a save
13
+ * whose pack was never written, or a pack index naming bytes that are not
14
+ * there. Git syncs its refs and packs for the same reason. Here the bytes are
15
+ * synced before the rename, and the folder after it, so whatever survives a
16
+ * crash is either the old state or the new one (audit, 16 November 2026).
17
+ *
18
+ * Windows cannot open a folder to sync it; there the rename is already
19
+ * journalled by NTFS, and the folder sync is skipped.
20
+ */
21
+ const node_crypto_1 = require("node:crypto");
22
+ const promises_1 = require("node:fs/promises");
23
+ const node_path_1 = __importDefault(require("node:path"));
24
+ /** Sync a folder's entries to disk, where the system allows it. */
25
+ async function syncDirectory(directory) {
26
+ if (process.platform === "win32")
27
+ return;
28
+ let handle;
29
+ try {
30
+ handle = await (0, promises_1.open)(directory, "r");
31
+ await handle.sync();
32
+ }
33
+ catch {
34
+ /* Some filesystems refuse to sync a directory; the rename still happened. */
35
+ }
36
+ finally {
37
+ await handle?.close().catch(() => undefined);
38
+ }
39
+ }
40
+ /**
41
+ * Write `contents` to `target` so that a crash leaves either the old file or
42
+ * the new one, both durable: written beside it, synced, renamed over it, and
43
+ * the folder synced.
44
+ */
45
+ async function writeDurably(target, contents) {
46
+ const partial = `${target}.${(0, node_crypto_1.randomBytes)(4).toString("hex")}.partial`;
47
+ const handle = await (0, promises_1.open)(partial, "w");
48
+ try {
49
+ await handle.writeFile(contents);
50
+ await handle.sync();
51
+ }
52
+ catch (error) {
53
+ await handle.close().catch(() => undefined);
54
+ await (0, promises_1.rm)(partial, { force: true });
55
+ throw error;
56
+ }
57
+ await handle.close();
58
+ try {
59
+ await (0, promises_1.rename)(partial, target);
60
+ }
61
+ catch (error) {
62
+ await (0, promises_1.rm)(partial, { force: true });
63
+ throw error;
64
+ }
65
+ await syncDirectory(node_path_1.default.dirname(target));
66
+ }