@git-stunts/git-cas 5.1.0 → 5.2.4

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 (45) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +144 -7
  3. package/bin/actions.js +25 -7
  4. package/bin/git-cas.js +150 -26
  5. package/bin/ui/context.js +13 -0
  6. package/bin/ui/dashboard-cmds.js +14 -6
  7. package/bin/ui/dashboard-view.js +55 -6
  8. package/bin/ui/dashboard.js +109 -7
  9. package/bin/ui/encryption-card.js +2 -2
  10. package/bin/ui/heatmap.js +20 -2
  11. package/bin/ui/history-timeline.js +8 -6
  12. package/bin/ui/manifest-view.js +37 -8
  13. package/bin/ui/progress.js +60 -38
  14. package/index.d.ts +22 -1
  15. package/index.js +80 -114
  16. package/package.json +2 -1
  17. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  18. package/src/domain/schemas/ManifestSchema.d.ts +2 -0
  19. package/src/domain/schemas/ManifestSchema.js +2 -0
  20. package/src/domain/services/CasService.d.ts +8 -1
  21. package/src/domain/services/CasService.js +123 -210
  22. package/src/domain/services/KeyResolver.js +220 -0
  23. package/src/domain/services/Semaphore.js +2 -2
  24. package/src/domain/services/VaultService.js +49 -27
  25. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  26. package/src/domain/value-objects/Manifest.d.ts +2 -0
  27. package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
  28. package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
  29. package/src/infrastructure/adapters/FileIOHelper.js +64 -0
  30. package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
  31. package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
  32. package/src/infrastructure/adapters/NodeCryptoAdapter.js +38 -7
  33. package/src/infrastructure/adapters/SilentObserver.js +15 -0
  34. package/src/infrastructure/adapters/StatsCollector.js +15 -1
  35. package/src/infrastructure/adapters/WebCryptoAdapter.js +68 -18
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/FixedChunker.js +5 -1
  38. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  39. package/src/infrastructure/codecs/CborCodec.js +11 -3
  40. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  41. package/src/ports/CodecPort.js +3 -3
  42. package/src/ports/CryptoPort.js +56 -23
  43. package/src/ports/GitPersistencePort.js +4 -4
  44. package/src/ports/GitRefPort.js +10 -10
  45. package/src/types/ambient.d.ts +37 -0
@@ -10,6 +10,7 @@ import Manifest from '../value-objects/Manifest.js';
10
10
  import CasError from '../errors/CasError.js';
11
11
  import Semaphore from './Semaphore.js';
12
12
  import FixedChunker from '../../infrastructure/chunkers/FixedChunker.js';
13
+ import KeyResolver from './KeyResolver.js';
13
14
 
14
15
  const gunzipAsync = promisify(gunzip);
15
16
 
@@ -20,6 +21,9 @@ const gunzipAsync = promisify(gunzip);
20
21
  * arbitrary data in Git's object database.
21
22
  */
22
23
  export default class CasService {
24
+ /** @type {KeyResolver} */
25
+ #keyResolver;
26
+
23
27
  /**
24
28
  * @param {Object} options
25
29
  * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
@@ -51,6 +55,7 @@ export default class CasService {
51
55
  throw new Error('Concurrency must be a positive integer');
52
56
  }
53
57
  this.concurrency = concurrency;
58
+ this.#keyResolver = new KeyResolver(crypto);
54
59
  }
55
60
 
56
61
  /**
@@ -190,129 +195,6 @@ export default class CasService {
190
195
  }
191
196
  }
192
197
 
193
- /**
194
- * Wraps a DEK with a KEK using AES-256-GCM.
195
- * @private
196
- * @param {Buffer} dek - 32-byte data encryption key.
197
- * @param {Buffer} kek - 32-byte key encryption key.
198
- * @returns {Promise<{ wrappedDek: string, nonce: string, tag: string }>}
199
- */
200
- async _wrapDek(dek, kek) {
201
- const { buf, meta } = await this.crypto.encryptBuffer(dek, kek);
202
- return {
203
- wrappedDek: buf.toString('base64'),
204
- nonce: meta.nonce,
205
- tag: meta.tag,
206
- };
207
- }
208
-
209
- /**
210
- * Unwraps a DEK from a recipient entry using the given KEK.
211
- * @private
212
- * @param {{ wrappedDek: string, nonce: string, tag: string }} recipientEntry
213
- * @param {Buffer} kek - 32-byte key encryption key.
214
- * @returns {Promise<Buffer>} The unwrapped DEK.
215
- * @throws {CasError} DEK_UNWRAP_FAILED if decryption fails.
216
- */
217
- async _unwrapDek(recipientEntry, kek) {
218
- try {
219
- const ciphertext = Buffer.from(recipientEntry.wrappedDek, 'base64');
220
- const meta = {
221
- algorithm: 'aes-256-gcm',
222
- nonce: recipientEntry.nonce,
223
- tag: recipientEntry.tag,
224
- encrypted: true,
225
- };
226
- return await this.crypto.decryptBuffer(ciphertext, kek, meta);
227
- } catch (err) {
228
- if (err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED') { throw err; }
229
- throw new CasError(
230
- 'Failed to unwrap DEK: authentication failed',
231
- 'DEK_UNWRAP_FAILED',
232
- { originalError: err },
233
- );
234
- }
235
- }
236
-
237
- /**
238
- * Resolves the decryption key from a manifest, handling both legacy and
239
- * envelope (multi-recipient) encrypted manifests.
240
- * @private
241
- * @param {import('../value-objects/Manifest.js').default} manifest
242
- * @param {Buffer} [encryptionKey]
243
- * @param {string} [passphrase]
244
- * @returns {Promise<Buffer|undefined>}
245
- */
246
- async _resolveDecryptionKey(manifest, encryptionKey, passphrase) {
247
- this._validateKeySourceExclusive(encryptionKey, passphrase);
248
-
249
- const key = passphrase
250
- ? await this._resolvePassphraseForDecryption(manifest, passphrase)
251
- : encryptionKey;
252
-
253
- if (!key) {
254
- if (manifest.encryption?.encrypted) {
255
- throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
256
- }
257
- return undefined;
258
- }
259
-
260
- this.crypto._validateKey(key);
261
- return await this._resolveKeyForRecipients(manifest, key);
262
- }
263
-
264
- /**
265
- * Resolves passphrase to a key for decryption.
266
- * @private
267
- */
268
- async _resolvePassphraseForDecryption(manifest, passphrase) {
269
- if (!manifest.encryption?.kdf) {
270
- throw new CasError(
271
- 'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
272
- 'MISSING_KEY',
273
- );
274
- }
275
- return this._resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
276
- }
277
-
278
- /**
279
- * If manifest uses envelope encryption, unwraps the DEK. Otherwise returns key directly.
280
- * @private
281
- */
282
- async _resolveKeyForRecipients(manifest, key) {
283
- const recipients = manifest.encryption?.recipients;
284
- if (!recipients || recipients.length === 0) {
285
- return key;
286
- }
287
-
288
- for (const entry of recipients) {
289
- try {
290
- return await this._unwrapDek(entry, key);
291
- } catch (err) {
292
- if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
293
- // Not this recipient's KEK, try next
294
- }
295
- }
296
-
297
- throw new CasError(
298
- 'No recipient entry could be unwrapped with the provided key',
299
- 'NO_MATCHING_RECIPIENT',
300
- );
301
- }
302
-
303
- /**
304
- * Validates that passphrase and encryptionKey are not both provided.
305
- * @private
306
- */
307
- _validateKeySourceExclusive(encryptionKey, passphrase) {
308
- if (passphrase && encryptionKey) {
309
- throw new CasError(
310
- 'Provide either encryptionKey or passphrase, not both',
311
- 'INVALID_OPTIONS',
312
- );
313
- }
314
- }
315
-
316
198
  /**
317
199
  * Validates and normalizes compression options.
318
200
  * @private
@@ -365,12 +247,12 @@ export default class CasService {
365
247
  if (recipients && (encryptionKey || passphrase)) {
366
248
  throw new CasError('Provide recipients or encryptionKey/passphrase, not both', 'INVALID_OPTIONS');
367
249
  }
368
- this._validateKeySourceExclusive(encryptionKey, passphrase);
250
+ KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
369
251
  this._validateCompression(compression);
370
252
 
371
253
  const keyInfo = recipients
372
- ? await this._resolveRecipientsForStore(recipients)
373
- : await this._resolveKeyForStore(encryptionKey, passphrase, kdfOptions);
254
+ ? await this.#keyResolver.resolveRecipients(recipients)
255
+ : await this.#keyResolver.resolveForStore(encryptionKey, passphrase, kdfOptions);
374
256
 
375
257
  const manifestData = this._buildManifestData(slug, filename, compression);
376
258
  const processedSource = compression ? this._compressStream(source) : source;
@@ -390,42 +272,6 @@ export default class CasService {
390
272
  return manifest;
391
273
  }
392
274
 
393
- /**
394
- * Resolves envelope recipients into a DEK and wrapped entries for store().
395
- * @private
396
- */
397
- async _resolveRecipientsForStore(recipients) {
398
- if (!Array.isArray(recipients) || recipients.length === 0) {
399
- throw new CasError('At least one recipient is required', 'INVALID_OPTIONS');
400
- }
401
- const labels = recipients.map((r) => r.label);
402
- if (new Set(labels).size !== labels.length) {
403
- throw new CasError('Duplicate recipient labels are not allowed', 'INVALID_OPTIONS');
404
- }
405
- const dek = this.crypto.randomBytes(32);
406
- const entries = [];
407
- for (const r of recipients) {
408
- this.crypto._validateKey(r.key);
409
- entries.push({ label: r.label, ...(await this._wrapDek(dek, r.key)) });
410
- }
411
- return { key: dek, encExtra: { recipients: entries } };
412
- }
413
-
414
- /**
415
- * Resolves encryptionKey/passphrase into a key and optional KDF params for store().
416
- * @private
417
- */
418
- async _resolveKeyForStore(encryptionKey, passphrase, kdfOptions) {
419
- let kdfParams;
420
- if (passphrase) {
421
- const derived = await this.deriveKey({ passphrase, ...kdfOptions });
422
- encryptionKey = derived.key;
423
- kdfParams = derived.params;
424
- }
425
- if (encryptionKey) { this.crypto._validateKey(encryptionKey); }
426
- return { key: encryptionKey, encExtra: kdfParams ? { kdf: kdfParams } : {} };
427
- }
428
-
429
275
  /**
430
276
  * Builds initial manifest data with optional chunking and compression metadata.
431
277
  * @private
@@ -519,6 +365,28 @@ export default class CasService {
519
365
  return await this.persistence.writeTree(treeEntries);
520
366
  }
521
367
 
368
+ /**
369
+ * Reads a single chunk blob from Git and verifies its SHA-256 digest.
370
+ * @private
371
+ * @param {{ index: number, size: number, digest: string, blob: string }} chunk - Chunk metadata.
372
+ * @returns {Promise<Buffer>} Verified chunk buffer.
373
+ * @throws {CasError} INTEGRITY_ERROR if the chunk digest does not match.
374
+ */
375
+ async _readAndVerifyChunk(chunk) {
376
+ const blob = await this.persistence.readBlob(chunk.blob);
377
+ const digest = await this._sha256(blob);
378
+ if (digest !== chunk.digest) {
379
+ const err = new CasError(
380
+ `Chunk ${chunk.index} integrity check failed`,
381
+ 'INTEGRITY_ERROR',
382
+ { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
383
+ );
384
+ this.observability.metric('error', { code: err.code, message: err.message });
385
+ throw err;
386
+ }
387
+ return blob;
388
+ }
389
+
522
390
  /**
523
391
  * Reads chunk blobs from Git and verifies their SHA-256 digests.
524
392
  * @private
@@ -529,43 +397,13 @@ export default class CasService {
529
397
  async _readAndVerifyChunks(chunks) {
530
398
  const buffers = [];
531
399
  for (const chunk of chunks) {
532
- const blob = await this.persistence.readBlob(chunk.blob);
533
- const digest = await this._sha256(blob);
534
- if (digest !== chunk.digest) {
535
- const err = new CasError(
536
- `Chunk ${chunk.index} integrity check failed`,
537
- 'INTEGRITY_ERROR',
538
- { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
539
- );
540
- this.observability.metric('error', { code: err.code, message: err.message });
541
- throw err;
542
- }
400
+ const blob = await this._readAndVerifyChunk(chunk);
543
401
  buffers.push(blob);
544
402
  this.observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
545
403
  }
546
404
  return buffers;
547
405
  }
548
406
 
549
- /**
550
- * Resolves the encryption key from a passphrase using KDF params from the manifest.
551
- * @private
552
- * @param {string} passphrase
553
- * @param {Object} kdf - KDF params from manifest.encryption.kdf.
554
- * @returns {Promise<Buffer>}
555
- */
556
- async _resolveKeyFromPassphrase(passphrase, kdf) {
557
- const { key } = await this.deriveKey({
558
- passphrase,
559
- salt: Buffer.from(kdf.salt, 'base64'),
560
- algorithm: kdf.algorithm,
561
- iterations: kdf.iterations,
562
- cost: kdf.cost,
563
- blockSize: kdf.blockSize,
564
- parallelization: kdf.parallelization,
565
- });
566
- return key;
567
- }
568
-
569
407
  /**
570
408
  * Restores a file from its manifest by reading and reassembling chunks.
571
409
  *
@@ -610,7 +448,7 @@ export default class CasService {
610
448
  * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
611
449
  */
612
450
  async *restoreStream({ manifest, encryptionKey, passphrase }) {
613
- const key = await this._resolveDecryptionKey(manifest, encryptionKey, passphrase);
451
+ const key = await this.#keyResolver.resolveForDecryption(manifest, encryptionKey, passphrase);
614
452
 
615
453
  if (manifest.chunks.length === 0) {
616
454
  this.observability.metric('file', {
@@ -659,20 +497,7 @@ export default class CasService {
659
497
  const readAhead = this.concurrency;
660
498
  let totalSize = 0;
661
499
 
662
- const readAndVerify = async (chunk) => {
663
- const blob = await this.persistence.readBlob(chunk.blob);
664
- const digest = await this._sha256(blob);
665
- if (digest !== chunk.digest) {
666
- const err = new CasError(
667
- `Chunk ${chunk.index} integrity check failed`,
668
- 'INTEGRITY_ERROR',
669
- { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
670
- );
671
- this.observability.metric('error', { code: err.code, message: err.message });
672
- throw err;
673
- }
674
- return blob;
675
- };
500
+ const readAndVerify = (chunk) => this._readAndVerifyChunk(chunk);
676
501
 
677
502
  const ahead = [];
678
503
  for (let i = 0; i < Math.min(readAhead, chunks.length); i++) {
@@ -897,7 +722,7 @@ export default class CasService {
897
722
  // Unwrap DEK using the existing key
898
723
  let dek;
899
724
  try {
900
- dek = await this._resolveKeyForRecipients(manifest, existingKey);
725
+ dek = await this.#keyResolver.resolveKeyForRecipients(manifest, existingKey);
901
726
  } catch (err) {
902
727
  if (err instanceof CasError && err.code === 'NO_MATCHING_RECIPIENT') {
903
728
  throw new CasError('Failed to unwrap DEK: authentication failed', 'DEK_UNWRAP_FAILED', { originalError: err });
@@ -906,7 +731,7 @@ export default class CasService {
906
731
  }
907
732
 
908
733
  // Wrap DEK for the new recipient
909
- const newEntry = { label, ...(await this._wrapDek(dek, newRecipientKey)) };
734
+ const newEntry = { label, ...(await this.#keyResolver.wrapDek(dek, newRecipientKey)) };
910
735
 
911
736
  const json = manifest.toJSON();
912
737
  const updatedEncryption = {
@@ -976,6 +801,94 @@ export default class CasService {
976
801
  return (manifest.encryption?.recipients || []).map((r) => r.label);
977
802
  }
978
803
 
804
+ /**
805
+ * Rotates a recipient's key without re-encrypting data blobs.
806
+ *
807
+ * Re-wraps the DEK with `newKey` for the matched recipient entry.
808
+ * Increments `keyVersion` at both manifest-level and recipient-level.
809
+ *
810
+ * @param {Object} options
811
+ * @param {import('../value-objects/Manifest.js').default} options.manifest
812
+ * @param {Buffer} options.oldKey - Current KEK of the recipient to rotate.
813
+ * @param {Buffer} options.newKey - New KEK to wrap the DEK with.
814
+ * @param {string} [options.label] - If provided, only rotate the named recipient.
815
+ * @returns {Promise<import('../value-objects/Manifest.js').default>}
816
+ * @throws {CasError} ROTATION_NOT_SUPPORTED if manifest has no recipients.
817
+ * @throws {CasError} RECIPIENT_NOT_FOUND if label doesn't exist.
818
+ * @throws {CasError} DEK_UNWRAP_FAILED if oldKey doesn't match the recipient.
819
+ * @throws {CasError} NO_MATCHING_RECIPIENT if no label and oldKey matches no entry.
820
+ */
821
+ async rotateKey({ manifest, oldKey, newKey, label }) {
822
+ const recipients = manifest.encryption?.recipients;
823
+ if (!recipients || recipients.length === 0) {
824
+ throw new CasError(
825
+ 'Key rotation requires envelope encryption (recipients)',
826
+ 'ROTATION_NOT_SUPPORTED',
827
+ );
828
+ }
829
+
830
+ this.crypto._validateKey(oldKey);
831
+ this.crypto._validateKey(newKey);
832
+
833
+ const { matchIndex, dek } = label
834
+ ? await this.#findRecipientByLabel(recipients, label, oldKey)
835
+ : await this.#findRecipientByKey(recipients, oldKey);
836
+
837
+ return this.#buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey });
838
+ }
839
+
840
+ /**
841
+ * Finds a recipient by label and unwraps the DEK.
842
+ */
843
+ async #findRecipientByLabel(recipients, label, oldKey) {
844
+ const matchIndex = recipients.findIndex((r) => r.label === label);
845
+ if (matchIndex === -1) {
846
+ throw new CasError(`Recipient "${label}" not found`, 'RECIPIENT_NOT_FOUND', { label });
847
+ }
848
+ const dek = await this.#keyResolver.unwrapDek(recipients[matchIndex], oldKey);
849
+ return { matchIndex, dek };
850
+ }
851
+
852
+ /**
853
+ * Finds the first recipient whose DEK can be unwrapped with the given key.
854
+ */
855
+ async #findRecipientByKey(recipients, oldKey) {
856
+ for (let i = 0; i < recipients.length; i++) {
857
+ try {
858
+ const dek = await this.#keyResolver.unwrapDek(recipients[i], oldKey);
859
+ return { matchIndex: i, dek };
860
+ } catch (err) {
861
+ if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
862
+ }
863
+ }
864
+ throw new CasError(
865
+ 'No recipient entry could be unwrapped with the provided key',
866
+ 'NO_MATCHING_RECIPIENT',
867
+ );
868
+ }
869
+
870
+ /**
871
+ * Builds a new Manifest with the rotated recipient entry and updated keyVersions.
872
+ */
873
+ async #buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey }) {
874
+ const newWrapped = await this.#keyResolver.wrapDek(dek, newKey);
875
+ const manifestKeyVersion = (manifest.encryption.keyVersion || 0) + 1;
876
+ const recipientKeyVersion = (recipients[matchIndex].keyVersion || 0) + 1;
877
+
878
+ const json = manifest.toJSON();
879
+ const updatedRecipients = recipients.map((r, i) => {
880
+ if (i === matchIndex) {
881
+ return { ...r, ...newWrapped, keyVersion: recipientKeyVersion };
882
+ }
883
+ return { ...r };
884
+ });
885
+
886
+ return new Manifest({
887
+ ...json,
888
+ encryption: { ...json.encryption, recipients: updatedRecipients, keyVersion: manifestKeyVersion },
889
+ });
890
+ }
891
+
979
892
  /**
980
893
  * Verifies the integrity of a stored file by re-hashing its chunks.
981
894
  * @param {import('../value-objects/Manifest.js').default} manifest
@@ -0,0 +1,220 @@
1
+ /**
2
+ * @fileoverview Key resolution service extracted from CasService.
3
+ *
4
+ * Handles all key-related logic: validation, wrapping/unwrapping DEKs,
5
+ * resolving encryption keys from passphrases, and envelope recipient management.
6
+ */
7
+ import CasError from '../errors/CasError.js';
8
+
9
+ /**
10
+ * Resolves encryption keys for store and restore operations.
11
+ *
12
+ * Encapsulates the key resolution responsibility that was previously
13
+ * spread across ~170 lines of CasService. Receives a CryptoPort via
14
+ * constructor injection.
15
+ *
16
+ * **Design note:** KeyResolver calls `CryptoPort.deriveKey()` directly
17
+ * rather than going through `CasService.deriveKey()`. If CasService ever
18
+ * adds validation or observability around its `deriveKey()` wrapper,
19
+ * KeyResolver will need updating to route through the service instead.
20
+ */
21
+ export default class KeyResolver {
22
+ /** @type {import('../../ports/CryptoPort.js').default} */
23
+ #crypto;
24
+
25
+ /**
26
+ * @param {import('../../ports/CryptoPort.js').default} crypto - CryptoPort adapter.
27
+ */
28
+ constructor(crypto) {
29
+ this.#crypto = crypto;
30
+ }
31
+
32
+ /**
33
+ * Validates that passphrase and encryptionKey are not both provided.
34
+ * @param {Buffer} [encryptionKey]
35
+ * @param {string} [passphrase]
36
+ * @throws {CasError} INVALID_OPTIONS if both are provided.
37
+ */
38
+ static validateKeySourceExclusive(encryptionKey, passphrase) {
39
+ if (passphrase && encryptionKey) {
40
+ throw new CasError(
41
+ 'Provide either encryptionKey or passphrase, not both',
42
+ 'INVALID_OPTIONS',
43
+ );
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Wraps a DEK with a KEK using AES-256-GCM.
49
+ * @param {Buffer} dek - 32-byte data encryption key.
50
+ * @param {Buffer} kek - 32-byte key encryption key.
51
+ * @returns {Promise<{ wrappedDek: string, nonce: string, tag: string }>}
52
+ */
53
+ async wrapDek(dek, kek) {
54
+ const { buf, meta } = await this.#crypto.encryptBuffer(dek, kek);
55
+ return {
56
+ wrappedDek: buf.toString('base64'),
57
+ nonce: meta.nonce,
58
+ tag: meta.tag,
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Unwraps a DEK from a recipient entry using the given KEK.
64
+ * @param {{ wrappedDek: string, nonce: string, tag: string }} recipientEntry
65
+ * @param {Buffer} kek - 32-byte key encryption key.
66
+ * @returns {Promise<Buffer>} The unwrapped DEK.
67
+ * @throws {CasError} DEK_UNWRAP_FAILED if decryption fails.
68
+ */
69
+ async unwrapDek(recipientEntry, kek) {
70
+ try {
71
+ const ciphertext = Buffer.from(recipientEntry.wrappedDek, 'base64');
72
+ const meta = {
73
+ algorithm: 'aes-256-gcm',
74
+ nonce: recipientEntry.nonce,
75
+ tag: recipientEntry.tag,
76
+ encrypted: true,
77
+ };
78
+ return await this.#crypto.decryptBuffer(ciphertext, kek, meta);
79
+ } catch (err) {
80
+ if (err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED') { throw err; }
81
+ throw new CasError(
82
+ 'Failed to unwrap DEK: authentication failed',
83
+ 'DEK_UNWRAP_FAILED',
84
+ { originalError: err },
85
+ );
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Resolves the decryption key from a manifest, handling both legacy and
91
+ * envelope (multi-recipient) encrypted manifests.
92
+ * @param {import('../value-objects/Manifest.js').default} manifest
93
+ * @param {Buffer} [encryptionKey]
94
+ * @param {string} [passphrase]
95
+ * @returns {Promise<Buffer|undefined>}
96
+ */
97
+ async resolveForDecryption(manifest, encryptionKey, passphrase) {
98
+ KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
99
+
100
+ const key = passphrase
101
+ ? await this.#resolvePassphraseForDecryption(manifest, passphrase)
102
+ : encryptionKey;
103
+
104
+ if (!key) {
105
+ if (manifest.encryption?.encrypted) {
106
+ throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ this.#crypto._validateKey(key);
112
+ return await this.resolveKeyForRecipients(manifest, key);
113
+ }
114
+
115
+ /**
116
+ * Resolves encryptionKey/passphrase into a key and optional KDF params for store().
117
+ * @param {Buffer} [encryptionKey]
118
+ * @param {string} [passphrase]
119
+ * @param {Object} [kdfOptions] - KDF options when using passphrase.
120
+ * @returns {Promise<{ key: Buffer|undefined, encExtra: Object }>}
121
+ */
122
+ async resolveForStore(encryptionKey, passphrase, kdfOptions) {
123
+ let kdfParams;
124
+ if (passphrase) {
125
+ const derived = await this.#crypto.deriveKey({ passphrase, ...kdfOptions });
126
+ encryptionKey = derived.key;
127
+ kdfParams = derived.params;
128
+ }
129
+ if (encryptionKey) { this.#crypto._validateKey(encryptionKey); }
130
+ return { key: encryptionKey, encExtra: kdfParams ? { kdf: kdfParams } : {} };
131
+ }
132
+
133
+ /**
134
+ * Resolves envelope recipients into a DEK and wrapped entries for store().
135
+ * @param {Array<{label: string, key: Buffer}>} recipients
136
+ * @returns {Promise<{ key: Buffer, encExtra: { recipients: Array } }>}
137
+ * @throws {CasError} INVALID_OPTIONS if recipients is empty, non-array, or has duplicate labels.
138
+ */
139
+ async resolveRecipients(recipients) {
140
+ if (!Array.isArray(recipients) || recipients.length === 0) {
141
+ throw new CasError('At least one recipient is required', 'INVALID_OPTIONS');
142
+ }
143
+ const labels = recipients.map((r) => r.label);
144
+ if (new Set(labels).size !== labels.length) {
145
+ throw new CasError('Duplicate recipient labels are not allowed', 'INVALID_OPTIONS');
146
+ }
147
+ const dek = this.#crypto.randomBytes(32);
148
+ const entries = [];
149
+ for (const r of recipients) {
150
+ this.#crypto._validateKey(r.key);
151
+ entries.push({ label: r.label, ...(await this.wrapDek(dek, r.key)) });
152
+ }
153
+ return { key: dek, encExtra: { recipients: entries } };
154
+ }
155
+
156
+ /**
157
+ * If manifest uses envelope encryption, unwraps the DEK. Otherwise returns key directly.
158
+ * @param {import('../value-objects/Manifest.js').default} manifest
159
+ * @param {Buffer} key
160
+ * @returns {Promise<Buffer>}
161
+ * @throws {CasError} NO_MATCHING_RECIPIENT if no recipient entry can be unwrapped.
162
+ */
163
+ async resolveKeyForRecipients(manifest, key) {
164
+ const recipients = manifest.encryption?.recipients;
165
+ if (!recipients || recipients.length === 0) {
166
+ return key;
167
+ }
168
+
169
+ for (const entry of recipients) {
170
+ try {
171
+ return await this.unwrapDek(entry, key);
172
+ } catch (err) {
173
+ if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
174
+ // Not this recipient's KEK, try next
175
+ }
176
+ }
177
+
178
+ throw new CasError(
179
+ 'No recipient entry could be unwrapped with the provided key',
180
+ 'NO_MATCHING_RECIPIENT',
181
+ );
182
+ }
183
+
184
+ /**
185
+ * Resolves passphrase to a key for decryption.
186
+ * @param {import('../value-objects/Manifest.js').default} manifest
187
+ * @param {string} passphrase
188
+ * @returns {Promise<Buffer>}
189
+ * @throws {CasError} MISSING_KEY if manifest has no KDF params.
190
+ */
191
+ async #resolvePassphraseForDecryption(manifest, passphrase) {
192
+ if (!manifest.encryption?.kdf) {
193
+ throw new CasError(
194
+ 'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
195
+ 'MISSING_KEY',
196
+ );
197
+ }
198
+ return this.#resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
199
+ }
200
+
201
+ /**
202
+ * Derives a key from a passphrase using stored KDF params.
203
+ * @param {string} passphrase
204
+ * @param {Object} kdf - KDF params from manifest.encryption.kdf.
205
+ * @returns {Promise<Buffer>}
206
+ */
207
+ async #resolveKeyFromPassphrase(passphrase, kdf) {
208
+ const { key } = await this.#crypto.deriveKey({
209
+ passphrase,
210
+ salt: Buffer.from(kdf.salt, 'base64'),
211
+ algorithm: kdf.algorithm,
212
+ iterations: kdf.iterations,
213
+ cost: kdf.cost,
214
+ blockSize: kdf.blockSize,
215
+ parallelization: kdf.parallelization,
216
+ keyLength: kdf.keyLength,
217
+ });
218
+ return key;
219
+ }
220
+ }
@@ -4,6 +4,7 @@
4
4
  export default class Semaphore {
5
5
  #max;
6
6
  #active = 0;
7
+ /** @type {Array<() => void>} */
7
8
  #queue = [];
8
9
 
9
10
  /**
@@ -35,8 +36,7 @@ export default class Semaphore {
35
36
  */
36
37
  release() {
37
38
  if (this.#queue.length > 0) {
38
- const next = this.#queue.shift();
39
- next();
39
+ /** @type {() => void} */ (this.#queue.shift())();
40
40
  } else {
41
41
  if (this.#active === 0) {
42
42
  throw new Error('Semaphore release called without an active permit');