@git-stunts/git-cas 5.2.4 → 5.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -34,28 +34,48 @@ export default class CasService {
34
34
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
35
35
  * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
36
36
  * @param {import('../../ports/ChunkingPort.js').default} [options.chunker] - Chunking strategy (default FixedChunker).
37
+ * @param {number} [options.maxRestoreBufferSize=536870912] - Max bytes for buffered restore (default 512 MiB).
37
38
  */
38
- constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker }) {
39
+ constructor({ persistence, codec, crypto, observability, chunkSize = 256 * 1024, merkleThreshold = 1000, concurrency = 1, chunker, maxRestoreBufferSize = 512 * 1024 * 1024 }) {
39
40
  CasService._validateObservability(observability);
40
- if (chunkSize < 1024) {
41
- throw new Error('Chunk size must be at least 1024 bytes');
42
- }
41
+ CasService.#validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize });
43
42
  this.persistence = persistence;
44
43
  this.codec = codec;
45
44
  this.crypto = crypto;
46
45
  this.observability = observability;
47
46
  this.chunkSize = chunkSize;
47
+ if (chunkSize > 10 * 1024 * 1024) {
48
+ observability.log('warn', `Chunk size ${chunkSize} exceeds 10 MiB — consider a smaller value`, { chunkSize });
49
+ }
48
50
  /** @type {import('../../ports/ChunkingPort.js').default} */
49
51
  this.chunker = chunker || new FixedChunker({ chunkSize });
52
+ this.merkleThreshold = merkleThreshold;
53
+ this.concurrency = concurrency;
54
+ this.maxRestoreBufferSize = maxRestoreBufferSize;
55
+ this.#keyResolver = new KeyResolver(crypto);
56
+ }
57
+
58
+ /**
59
+ * Validates constructor numeric arguments.
60
+ * @private
61
+ */
62
+ static #validateConstructorArgs({ chunkSize, merkleThreshold, concurrency, maxRestoreBufferSize }) {
63
+ if (!Number.isInteger(chunkSize) || chunkSize < 1024) {
64
+ throw new Error('Chunk size must be an integer >= 1024 bytes');
65
+ }
66
+ const MAX_CHUNK_SIZE = 100 * 1024 * 1024;
67
+ if (chunkSize > MAX_CHUNK_SIZE) {
68
+ throw new Error(`Chunk size must not exceed ${MAX_CHUNK_SIZE} bytes (100 MiB)`);
69
+ }
50
70
  if (!Number.isInteger(merkleThreshold) || merkleThreshold < 1) {
51
71
  throw new Error('Merkle threshold must be a positive integer');
52
72
  }
53
- this.merkleThreshold = merkleThreshold;
54
73
  if (!Number.isInteger(concurrency) || concurrency < 1) {
55
74
  throw new Error('Concurrency must be a positive integer');
56
75
  }
57
- this.concurrency = concurrency;
58
- this.#keyResolver = new KeyResolver(crypto);
76
+ if (!Number.isInteger(maxRestoreBufferSize) || maxRestoreBufferSize < 1024) {
77
+ throw new Error('maxRestoreBufferSize must be a positive integer >= 1024');
78
+ }
59
79
  }
60
80
 
61
81
  /**
@@ -127,15 +147,23 @@ export default class CasService {
127
147
  launchWrite(chunk, nextIndex++);
128
148
  }
129
149
  } catch (err) {
130
- await Promise.allSettled(pending);
131
- if (err instanceof CasError) { throw err; }
150
+ const settled = await Promise.allSettled(pending);
151
+ const orphanedBlobs = settled
152
+ .filter((r) => r.status === 'fulfilled')
153
+ .map((r) => r.value.blob);
154
+ if (err instanceof CasError) {
155
+ err.meta = { ...err.meta, orphanedBlobs };
156
+ throw err;
157
+ }
132
158
  const casErr = new CasError(
133
159
  `Stream error during store: ${err.message}`,
134
160
  'STREAM_ERROR',
135
- { chunksDispatched: nextIndex, originalError: err },
161
+ { chunksDispatched: nextIndex, orphanedBlobs, originalError: err },
136
162
  );
137
- await Promise.allSettled(pending);
138
- this.observability.metric('error', { code: casErr.code, message: casErr.message });
163
+ this.observability.metric('error', {
164
+ code: casErr.code, message: casErr.message,
165
+ orphanedBlobs: orphanedBlobs.length,
166
+ });
139
167
  throw casErr;
140
168
  }
141
169
 
@@ -257,6 +285,13 @@ export default class CasService {
257
285
  const manifestData = this._buildManifestData(slug, filename, compression);
258
286
  const processedSource = compression ? this._compressStream(source) : source;
259
287
 
288
+ if (keyInfo.key && this.chunker.strategy === 'cdc') {
289
+ this.observability.log(
290
+ 'warn',
291
+ 'CDC deduplication is ineffective with encryption — ciphertext is pseudorandom',
292
+ { strategy: 'cdc' },
293
+ );
294
+ }
260
295
  if (keyInfo.key) {
261
296
  const { encrypt, finalize } = this.crypto.createEncryptionStream(keyInfo.key);
262
297
  await this._chunkAndStore(encrypt(processedSource), manifestData);
@@ -469,14 +504,38 @@ export default class CasService {
469
504
  * @private
470
505
  */
471
506
  async *_restoreBuffered(manifest, key) {
507
+ const totalSize = manifest.chunks.reduce((acc, c) => acc + c.size, 0);
508
+ if (totalSize > this.maxRestoreBufferSize) {
509
+ throw new CasError(
510
+ `Encrypted/compressed restore would buffer ${totalSize} bytes ` +
511
+ `(limit: ${this.maxRestoreBufferSize}). Increase maxRestoreBufferSize ` +
512
+ 'or store without encryption.',
513
+ 'RESTORE_TOO_LARGE',
514
+ { size: totalSize, limit: this.maxRestoreBufferSize },
515
+ );
516
+ }
472
517
  let buffer = Buffer.concat(await this._readAndVerifyChunks(manifest.chunks));
473
518
 
474
519
  if (manifest.encryption?.encrypted) {
475
- buffer = await this.decrypt({ buffer, key, meta: manifest.encryption });
520
+ try {
521
+ buffer = await this.decrypt({ buffer, key, meta: manifest.encryption });
522
+ } catch (err) {
523
+ if (err instanceof CasError && err.code === 'INTEGRITY_ERROR') {
524
+ this.observability.metric('error', { action: 'decryption_failed', slug: manifest.slug });
525
+ }
526
+ throw err;
527
+ }
476
528
  }
477
529
 
478
530
  if (manifest.compression) {
479
531
  buffer = await this._decompress(buffer);
532
+ if (buffer.length > this.maxRestoreBufferSize) {
533
+ throw new CasError(
534
+ `Decompressed restore is ${buffer.length} bytes (limit: ${this.maxRestoreBufferSize})`,
535
+ 'RESTORE_TOO_LARGE',
536
+ { size: buffer.length, limit: this.maxRestoreBufferSize },
537
+ );
538
+ }
480
539
  }
481
540
 
482
541
  this.observability.metric('file', {
@@ -626,7 +685,7 @@ export default class CasService {
626
685
  }
627
686
 
628
687
  /**
629
- * Returns deletion metadata for an asset stored in a Git tree.
688
+ * Reads a manifest from a Git tree and returns inspection metadata.
630
689
  * Does not perform any destructive Git operations.
631
690
  *
632
691
  * @param {Object} options
@@ -634,7 +693,7 @@ export default class CasService {
634
693
  * @returns {Promise<{ chunksOrphaned: number, slug: string }>}
635
694
  * @throws {CasError} MANIFEST_NOT_FOUND if the tree has no manifest
636
695
  */
637
- async deleteAsset({ treeOid }) {
696
+ async inspectAsset({ treeOid }) {
638
697
  const manifest = await this.readManifest({ treeOid });
639
698
  return {
640
699
  slug: manifest.slug,
@@ -642,6 +701,17 @@ export default class CasService {
642
701
  };
643
702
  }
644
703
 
704
+ /**
705
+ * @deprecated Use {@link inspectAsset} instead.
706
+ * @param {Object} options
707
+ * @param {string} options.treeOid - Git tree OID of the asset
708
+ * @returns {Promise<{ chunksOrphaned: number, slug: string }>}
709
+ */
710
+ async deleteAsset(options) {
711
+ this.observability.log('warn', 'deleteAsset() is deprecated — use inspectAsset()');
712
+ return await this.inspectAsset(options);
713
+ }
714
+
645
715
  /**
646
716
  * Aggregates referenced chunk blob OIDs across multiple stored assets.
647
717
  * Analysis only — does not delete or modify anything.
@@ -651,7 +721,7 @@ export default class CasService {
651
721
  * @returns {Promise<{ referenced: Set<string>, total: number }>}
652
722
  * @throws {CasError} MANIFEST_NOT_FOUND if any treeOid lacks a manifest
653
723
  */
654
- async findOrphanedChunks({ treeOids }) {
724
+ async collectReferencedChunks({ treeOids }) {
655
725
  const referenced = new Set();
656
726
  let total = 0;
657
727
 
@@ -666,6 +736,17 @@ export default class CasService {
666
736
  return { referenced, total };
667
737
  }
668
738
 
739
+ /**
740
+ * @deprecated Use {@link collectReferencedChunks} instead.
741
+ * @param {Object} options
742
+ * @param {string[]} options.treeOids - Git tree OIDs to analyze
743
+ * @returns {Promise<{ referenced: Set<string>, total: number }>}
744
+ */
745
+ async findOrphanedChunks(options) {
746
+ this.observability.log('warn', 'findOrphanedChunks() is deprecated — use collectReferencedChunks()');
747
+ return await this.collectReferencedChunks(options);
748
+ }
749
+
669
750
  /**
670
751
  * Derives an encryption key from a passphrase using PBKDF2 or scrypt.
671
752
  * @param {Object} options
@@ -80,16 +80,22 @@ function hasControlChars(str) {
80
80
  export default class VaultService {
81
81
  static VAULT_REF = VAULT_REF;
82
82
 
83
+ /** @type {number} Nonce usage warning threshold (2^31). */
84
+ static ENCRYPTION_COUNT_WARN = 2 ** 31;
85
+
83
86
  /**
84
87
  * @param {Object} options
85
88
  * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
86
89
  * @param {import('../../ports/GitRefPort.js').default} options.ref
87
90
  * @param {import('../../ports/CryptoPort.js').default} options.crypto
91
+ * @param {import('../../ports/ObservabilityPort.js').default} [options.observability]
88
92
  */
89
- constructor({ persistence, ref, crypto }) {
93
+ constructor({ persistence, ref, crypto, observability }) {
90
94
  this.persistence = persistence;
91
95
  this.ref = ref;
92
96
  this.crypto = crypto;
97
+ /** @type {import('../../ports/ObservabilityPort.js').default} */
98
+ this.observability = observability || { metric() {}, log() {}, span: () => ({ end() {} }) };
93
99
  }
94
100
 
95
101
  // ---------------------------------------------------------------------------
@@ -389,9 +395,24 @@ export default class VaultService {
389
395
  }
390
396
  const isUpdate = state.entries.has(slug);
391
397
  state.entries.set(slug, treeOid);
398
+ // Shallow copy to avoid mutating readState()'s object on CAS retries.
399
+ const metadata = { ...(state.metadata || { version: 1 }) };
400
+ if (metadata.encryption) {
401
+ // Tracks nonce-relevant operations: every addToVault on an encrypted
402
+ // vault implies an encryption occurred at the store layer.
403
+ metadata.encryptionCount = (metadata.encryptionCount || 0) + 1;
404
+ if (metadata.encryptionCount >= VaultService.ENCRYPTION_COUNT_WARN) {
405
+ this.observability.log(
406
+ 'warn',
407
+ `Vault encryption count (${metadata.encryptionCount}) exceeds ` +
408
+ `${VaultService.ENCRYPTION_COUNT_WARN} — rotate your key`,
409
+ { encryptionCount: metadata.encryptionCount },
410
+ );
411
+ }
412
+ }
392
413
  return {
393
414
  entries: state.entries,
394
- metadata: state.metadata || { version: 1 },
415
+ metadata,
395
416
  message: isUpdate ? `vault: update ${slug}` : `vault: add ${slug}`,
396
417
  };
397
418
  });
@@ -1,6 +1,7 @@
1
1
  import { createHash, createCipheriv, createDecipheriv, randomBytes, pbkdf2, scrypt } from 'node:crypto';
2
2
  import { promisify } from 'node:util';
3
3
  import CryptoPort from '../../ports/CryptoPort.js';
4
+ import CasError from '../../domain/errors/CasError.js';
4
5
 
5
6
  /**
6
7
  * Node.js implementation of CryptoPort using node:crypto.
@@ -28,9 +29,9 @@ export default class NodeCryptoAdapter extends CryptoPort {
28
29
  * @override
29
30
  * @param {Buffer|Uint8Array} buffer - Plaintext to encrypt.
30
31
  * @param {Buffer|Uint8Array} key - 32-byte encryption key.
31
- * @returns {{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }}
32
+ * @returns {Promise<{ buf: Buffer, meta: import('../../ports/CryptoPort.js').EncryptionMeta }>}
32
33
  */
33
- encryptBuffer(buffer, key) {
34
+ async encryptBuffer(buffer, key) {
34
35
  this._validateKey(key);
35
36
  const nonce = randomBytes(12);
36
37
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
@@ -50,6 +51,7 @@ export default class NodeCryptoAdapter extends CryptoPort {
50
51
  * @returns {Buffer}
51
52
  */
52
53
  decryptBuffer(buffer, key, meta) {
54
+ this._validateKey(key);
53
55
  const nonce = Buffer.from(meta.nonce, 'base64');
54
56
  const tag = Buffer.from(meta.tag, 'base64');
55
57
  const decipher = createDecipheriv('aes-256-gcm', key, nonce);
@@ -66,6 +68,7 @@ export default class NodeCryptoAdapter extends CryptoPort {
66
68
  this._validateKey(key);
67
69
  const nonce = randomBytes(12);
68
70
  const cipher = createCipheriv('aes-256-gcm', key, nonce);
71
+ let streamFinalized = false;
69
72
 
70
73
  /** @param {AsyncIterable<Buffer>} source */
71
74
  const encrypt = async function* (source) {
@@ -79,9 +82,16 @@ export default class NodeCryptoAdapter extends CryptoPort {
79
82
  if (final.length > 0) {
80
83
  yield final;
81
84
  }
85
+ streamFinalized = true;
82
86
  };
83
87
 
84
88
  const finalize = () => {
89
+ if (!streamFinalized) {
90
+ throw new CasError(
91
+ 'Cannot finalize before the encrypt stream is fully consumed',
92
+ 'STREAM_NOT_CONSUMED',
93
+ );
94
+ }
85
95
  const tag = cipher.getAuthTag();
86
96
  return this._buildMeta(nonce.toString('base64'), tag.toString('base64'));
87
97
  };
@@ -9,6 +9,21 @@ import CasError from '../../domain/errors/CasError.js';
9
9
  * AES-GCM is a one-shot API (the GCM tag is computed over the entire plaintext).
10
10
  */
11
11
  export default class WebCryptoAdapter extends CryptoPort {
12
+ /** @type {number} */
13
+ #maxEncryptionBufferSize;
14
+
15
+ /**
16
+ * @param {Object} [options]
17
+ * @param {number} [options.maxEncryptionBufferSize=536870912] - Max bytes to buffer during streaming encryption (default 512 MiB).
18
+ */
19
+ constructor({ maxEncryptionBufferSize = 512 * 1024 * 1024 } = {}) {
20
+ super();
21
+ if (!Number.isFinite(maxEncryptionBufferSize) || maxEncryptionBufferSize <= 0) {
22
+ throw new RangeError('maxEncryptionBufferSize must be a finite positive number');
23
+ }
24
+ this.#maxEncryptionBufferSize = maxEncryptionBufferSize;
25
+ }
26
+
12
27
  /**
13
28
  * @override
14
29
  * @param {Buffer|Uint8Array} buf - Data to hash.
@@ -73,6 +88,7 @@ export default class WebCryptoAdapter extends CryptoPort {
73
88
  * @returns {Promise<Buffer>}
74
89
  */
75
90
  async decryptBuffer(buffer, key, meta) {
91
+ this._validateKey(key);
76
92
  const nonce = this.#fromBase64(meta.nonce);
77
93
  const tag = this.#fromBase64(meta.tag);
78
94
  const cryptoKey = await this.#importKey(key);
@@ -104,49 +120,61 @@ export default class WebCryptoAdapter extends CryptoPort {
104
120
  this._validateKey(key);
105
121
  const nonce = this.randomBytes(12);
106
122
  const cryptoKeyPromise = this.#importKey(key);
123
+ const maxBuf = this.#maxEncryptionBufferSize;
124
+ const state = { /** @type {Uint8Array|null} */ tag: null, consumed: false };
107
125
 
108
- // Web Crypto buffers all data for the one-shot AES-GCM call (GCM tag spans the whole plaintext).
109
- /** @type {Buffer[]} */
110
- const chunks = [];
111
- /** @type {Uint8Array|null} */
112
- let finalTag = null;
113
- let streamConsumed = false;
126
+ const encrypt = WebCryptoAdapter.#makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state });
127
+
128
+ const finalize = () => {
129
+ if (!state.consumed) {
130
+ throw new CasError('Cannot finalize before the encrypt stream is fully consumed', 'STREAM_NOT_CONSUMED');
131
+ }
132
+ return this._buildMeta(this.#toBase64(nonce), this.#toBase64(/** @type {Uint8Array} */ (state.tag)));
133
+ };
134
+
135
+ return { encrypt, finalize };
136
+ }
114
137
 
115
- /** @param {AsyncIterable<Buffer>} source */
116
- const encrypt = async function* (source) {
138
+ /**
139
+ * Builds the encrypt async generator for createEncryptionStream.
140
+ *
141
+ * A static method is used (rather than closures) because `async function*`
142
+ * cannot be an arrow function — `this` binding would be lost. The `state`
143
+ * object bridges mutable data between the generator and `finalize()`.
144
+ *
145
+ * @param {{ cryptoKeyPromise: Promise<CryptoKey>, nonce: Buffer|Uint8Array, maxBuf: number, state: { tag: Uint8Array|null, consumed: boolean } }} ctx
146
+ * @returns {(source: AsyncIterable<Buffer>) => AsyncGenerator<Buffer>}
147
+ */
148
+ static #makeEncryptGenerator({ cryptoKeyPromise, nonce, maxBuf, state }) {
149
+ return async function* (source) {
150
+ /** @type {Buffer[]} */
151
+ const chunks = [];
152
+ let accumulatedBytes = 0;
117
153
  for await (const chunk of source) {
154
+ accumulatedBytes += chunk.length;
155
+ if (accumulatedBytes > maxBuf) {
156
+ throw new CasError(
157
+ `Streaming encryption buffered ${accumulatedBytes} bytes (limit: ${maxBuf}). ` +
158
+ 'Web Crypto AES-GCM buffers all data. Use Node.js/Bun or store without encryption for large files.',
159
+ 'ENCRYPTION_BUFFER_EXCEEDED',
160
+ { accumulated: accumulatedBytes, limit: maxBuf },
161
+ );
162
+ }
118
163
  chunks.push(chunk);
119
164
  }
120
-
121
165
  const buffer = Buffer.concat(chunks);
122
166
  const cryptoKey = await cryptoKeyPromise;
123
167
  const encrypted = await globalThis.crypto.subtle.encrypt(
124
168
  // @ts-ignore -- Uint8Array satisfies BufferSource at runtime
125
169
  { name: 'AES-GCM', iv: /** @type {Uint8Array} */ (nonce) },
126
- cryptoKey,
127
- buffer
170
+ cryptoKey, buffer,
128
171
  );
129
-
130
172
  const fullBuffer = new Uint8Array(encrypted);
131
173
  const tagLength = 16;
132
- const ciphertext = fullBuffer.slice(0, -tagLength);
133
- finalTag = fullBuffer.slice(-tagLength);
134
- streamConsumed = true;
135
-
136
- yield Buffer.from(ciphertext);
174
+ state.tag = fullBuffer.slice(-tagLength);
175
+ state.consumed = true;
176
+ yield Buffer.from(fullBuffer.slice(0, -tagLength));
137
177
  };
138
-
139
- const finalize = () => {
140
- if (!streamConsumed) {
141
- throw new CasError(
142
- 'Cannot finalize before the encrypt stream is fully consumed',
143
- 'STREAM_NOT_CONSUMED',
144
- );
145
- }
146
- return this._buildMeta(this.#toBase64(nonce), this.#toBase64(/** @type {Uint8Array} */ (finalTag)));
147
- };
148
-
149
- return { encrypt, finalize };
150
178
  }
151
179
 
152
180
  /**
@@ -277,6 +277,11 @@ export default class CdcChunker extends ChunkingPort {
277
277
  `targetChunkSize (${targetChunkSize}) must be in [${minChunkSize}, ${maxChunkSize}]`,
278
278
  );
279
279
  }
280
+ if (maxChunkSize > 100 * 1024 * 1024) {
281
+ throw new RangeError(
282
+ `maxChunkSize must not exceed 104857600 bytes (100 MiB), got ${maxChunkSize}`,
283
+ );
284
+ }
280
285
 
281
286
  this.#minChunkSize = minChunkSize;
282
287
  this.#maxChunkSize = maxChunkSize;
@@ -17,6 +17,14 @@ export default class FixedChunker extends ChunkingPort {
17
17
  */
18
18
  constructor({ chunkSize = 262144 } = {}) {
19
19
  super();
20
+ if (!Number.isInteger(chunkSize) || chunkSize < 1) {
21
+ throw new RangeError(`chunkSize must be a positive integer, got ${chunkSize}`);
22
+ }
23
+ if (chunkSize > 100 * 1024 * 1024) {
24
+ throw new RangeError(
25
+ `Chunk size must not exceed 104857600 bytes (100 MiB), got ${chunkSize}`,
26
+ );
27
+ }
20
28
  this.#chunkSize = chunkSize;
21
29
  }
22
30
 
@@ -36,18 +44,26 @@ export default class FixedChunker extends ChunkingPort {
36
44
  * @yields {Buffer}
37
45
  */
38
46
  async *chunk(source) {
39
- let buffer = Buffer.alloc(0);
47
+ const cs = this.#chunkSize;
48
+ const buf = Buffer.allocUnsafe(cs);
49
+ let offset = 0;
40
50
 
41
51
  for await (const data of source) {
42
- buffer = Buffer.concat([buffer, data]);
43
- while (buffer.length >= this.#chunkSize) {
44
- yield buffer.slice(0, this.#chunkSize);
45
- buffer = buffer.slice(this.#chunkSize);
52
+ let srcPos = 0;
53
+ while (srcPos < data.length) {
54
+ const n = Math.min(cs - offset, data.length - srcPos);
55
+ data.copy(buf, offset, srcPos, srcPos + n);
56
+ offset += n;
57
+ srcPos += n;
58
+ if (offset === cs) {
59
+ yield Buffer.from(buf);
60
+ offset = 0;
61
+ }
46
62
  }
47
63
  }
48
64
 
49
- if (buffer.length > 0) {
50
- yield buffer;
65
+ if (offset > 0) {
66
+ yield Buffer.from(buf.subarray(0, offset));
51
67
  }
52
68
  }
53
69
  }