@git-stunts/git-cas 5.0.0 → 5.2.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.
@@ -190,6 +190,116 @@ export default class CasService {
190
190
  }
191
191
  }
192
192
 
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
+
193
303
  /**
194
304
  * Validates that passphrase and encryptionKey are not both provided.
195
305
  * @private
@@ -237,8 +347,8 @@ export default class CasService {
237
347
  /**
238
348
  * Chunks an async iterable source and stores it in Git.
239
349
  *
240
- * If `encryptionKey` is provided, the content (and manifest) will be encrypted
241
- * using AES-256-GCM, and the `encryption` field in the manifest will be populated.
350
+ * Supports two encryption modes: direct key/passphrase or envelope encryption
351
+ * via `recipients` (DEK/KEK model). The modes are mutually exclusive.
242
352
  *
243
353
  * @param {Object} options
244
354
  * @param {AsyncIterable<Buffer>} options.source
@@ -248,58 +358,87 @@ export default class CasService {
248
358
  * @param {string} [options.passphrase] - Derive encryption key from passphrase instead.
249
359
  * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
250
360
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
361
+ * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
251
362
  * @returns {Promise<import('../value-objects/Manifest.js').default>}
252
363
  */
253
- async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
364
+ async store({ source, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
365
+ if (recipients && (encryptionKey || passphrase)) {
366
+ throw new CasError('Provide recipients or encryptionKey/passphrase, not both', 'INVALID_OPTIONS');
367
+ }
254
368
  this._validateKeySourceExclusive(encryptionKey, passphrase);
255
369
  this._validateCompression(compression);
256
370
 
257
- let kdfParams;
258
- if (passphrase) {
259
- const derived = await this.deriveKey({ passphrase, ...kdfOptions });
260
- encryptionKey = derived.key;
261
- kdfParams = derived.params;
262
- }
371
+ const keyInfo = recipients
372
+ ? await this._resolveRecipientsForStore(recipients)
373
+ : await this._resolveKeyForStore(encryptionKey, passphrase, kdfOptions);
263
374
 
264
- if (encryptionKey) {
265
- this.crypto._validateKey(encryptionKey);
266
- }
267
-
268
- const manifestData = { slug, filename, size: 0, chunks: [] };
269
-
270
- // Record chunking metadata for non-default strategies
271
- if (this.chunker.strategy !== 'fixed') {
272
- manifestData.chunking = {
273
- strategy: this.chunker.strategy,
274
- params: this.chunker.params,
275
- };
276
- }
375
+ const manifestData = this._buildManifestData(slug, filename, compression);
376
+ const processedSource = compression ? this._compressStream(source) : source;
277
377
 
278
- let processedSource = source;
279
- if (compression) {
280
- processedSource = this._compressStream(processedSource);
281
- manifestData.compression = { algorithm: 'gzip' };
282
- }
283
-
284
- if (encryptionKey) {
285
- const { encrypt, finalize } = this.crypto.createEncryptionStream(encryptionKey);
378
+ if (keyInfo.key) {
379
+ const { encrypt, finalize } = this.crypto.createEncryptionStream(keyInfo.key);
286
380
  await this._chunkAndStore(encrypt(processedSource), manifestData);
287
- const encMeta = finalize();
288
- if (kdfParams) {
289
- encMeta.kdf = kdfParams;
290
- }
291
- manifestData.encryption = encMeta;
381
+ manifestData.encryption = { ...finalize(), ...keyInfo.encExtra };
292
382
  } else {
293
383
  await this._chunkAndStore(processedSource, manifestData);
294
384
  }
295
385
 
296
386
  const manifest = new Manifest(manifestData);
297
387
  this.observability.metric('file', {
298
- action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!encryptionKey,
388
+ action: 'stored', slug, size: manifest.size, chunkCount: manifest.chunks.length, encrypted: !!keyInfo.key,
299
389
  });
300
390
  return manifest;
301
391
  }
302
392
 
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
+ /**
430
+ * Builds initial manifest data with optional chunking and compression metadata.
431
+ * @private
432
+ */
433
+ _buildManifestData(slug, filename, compression) {
434
+ const data = { slug, filename, size: 0, chunks: [] };
435
+ if (this.chunker.strategy !== 'fixed') {
436
+ data.chunking = { strategy: this.chunker.strategy, params: this.chunker.params };
437
+ }
438
+ if (compression) { data.compression = { algorithm: 'gzip' }; }
439
+ return data;
440
+ }
441
+
303
442
  /**
304
443
  * Creates a Git tree object from a manifest.
305
444
  *
@@ -427,30 +566,6 @@ export default class CasService {
427
566
  return key;
428
567
  }
429
568
 
430
- /**
431
- * Resolves the encryption key from passphrase or validates the provided key.
432
- * @private
433
- */
434
- async _resolveEncryptionKey(manifest, encryptionKey, passphrase) {
435
- this._validateKeySourceExclusive(encryptionKey, passphrase);
436
-
437
- if (passphrase) {
438
- if (manifest.encryption?.kdf) {
439
- return this._resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
440
- }
441
- throw new CasError(
442
- 'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
443
- 'MISSING_KEY',
444
- );
445
- }
446
- if (encryptionKey) {
447
- this.crypto._validateKey(encryptionKey);
448
- } else if (manifest.encryption?.encrypted) {
449
- throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
450
- }
451
- return encryptionKey;
452
- }
453
-
454
569
  /**
455
570
  * Restores a file from its manifest by reading and reassembling chunks.
456
571
  *
@@ -495,7 +610,7 @@ export default class CasService {
495
610
  * @throws {CasError} INTEGRITY_ERROR if chunk verification or decryption fails.
496
611
  */
497
612
  async *restoreStream({ manifest, encryptionKey, passphrase }) {
498
- const key = await this._resolveEncryptionKey(manifest, encryptionKey, passphrase);
613
+ const key = await this._resolveDecryptionKey(manifest, encryptionKey, passphrase);
499
614
 
500
615
  if (manifest.chunks.length === 0) {
501
616
  this.observability.metric('file', {
@@ -743,6 +858,212 @@ export default class CasService {
743
858
  return await this.crypto.deriveKey(options);
744
859
  }
745
860
 
861
+ /**
862
+ * Adds a new recipient to an envelope-encrypted manifest.
863
+ *
864
+ * Unwraps the DEK using `existingKey`, wraps it with `newRecipientKey`,
865
+ * and returns a new Manifest with the appended recipient entry.
866
+ *
867
+ * @param {Object} options
868
+ * @param {import('../value-objects/Manifest.js').default} options.manifest
869
+ * @param {Buffer} options.existingKey - KEK of an existing recipient.
870
+ * @param {Buffer} options.newRecipientKey - KEK for the new recipient.
871
+ * @param {string} options.label - Label for the new recipient.
872
+ * @returns {Promise<import('../value-objects/Manifest.js').default>}
873
+ * @throws {CasError} INVALID_OPTIONS if manifest has no recipients.
874
+ * @throws {CasError} RECIPIENT_ALREADY_EXISTS if label is a duplicate.
875
+ * @throws {CasError} DEK_UNWRAP_FAILED if existingKey doesn't match any recipient.
876
+ */
877
+ async addRecipient({ manifest, existingKey, newRecipientKey, label }) {
878
+ const recipients = manifest.encryption?.recipients;
879
+ if (!recipients || recipients.length === 0) {
880
+ throw new CasError(
881
+ 'Manifest does not use envelope encryption (no recipients)',
882
+ 'INVALID_OPTIONS',
883
+ );
884
+ }
885
+
886
+ if (recipients.some((r) => r.label === label)) {
887
+ throw new CasError(
888
+ `Recipient "${label}" already exists`,
889
+ 'RECIPIENT_ALREADY_EXISTS',
890
+ { label },
891
+ );
892
+ }
893
+
894
+ this.crypto._validateKey(existingKey);
895
+ this.crypto._validateKey(newRecipientKey);
896
+
897
+ // Unwrap DEK using the existing key
898
+ let dek;
899
+ try {
900
+ dek = await this._resolveKeyForRecipients(manifest, existingKey);
901
+ } catch (err) {
902
+ if (err instanceof CasError && err.code === 'NO_MATCHING_RECIPIENT') {
903
+ throw new CasError('Failed to unwrap DEK: authentication failed', 'DEK_UNWRAP_FAILED', { originalError: err });
904
+ }
905
+ throw err;
906
+ }
907
+
908
+ // Wrap DEK for the new recipient
909
+ const newEntry = { label, ...(await this._wrapDek(dek, newRecipientKey)) };
910
+
911
+ const json = manifest.toJSON();
912
+ const updatedEncryption = {
913
+ ...json.encryption,
914
+ recipients: [...recipients.map((r) => ({ ...r })), newEntry],
915
+ };
916
+
917
+ return new Manifest({ ...json, encryption: updatedEncryption });
918
+ }
919
+
920
+ /**
921
+ * Removes a recipient from an envelope-encrypted manifest.
922
+ *
923
+ * Returns a new Manifest with the recipient entry removed. Does not
924
+ * require a key — this is a manifest-only mutation.
925
+ *
926
+ * @param {Object} options
927
+ * @param {import('../value-objects/Manifest.js').default} options.manifest
928
+ * @param {string} options.label - Label of the recipient to remove.
929
+ * @returns {Promise<import('../value-objects/Manifest.js').default>}
930
+ * @throws {CasError} RECIPIENT_NOT_FOUND if label doesn't exist.
931
+ * @throws {CasError} CANNOT_REMOVE_LAST_RECIPIENT if only one recipient remains.
932
+ */
933
+ async removeRecipient({ manifest, label }) {
934
+ const recipients = manifest.encryption?.recipients;
935
+ if (!recipients || recipients.length === 0) {
936
+ throw new CasError(
937
+ 'Manifest does not use envelope encryption (no recipients)',
938
+ 'INVALID_OPTIONS',
939
+ );
940
+ }
941
+ if (!recipients.some((r) => r.label === label)) {
942
+ throw new CasError(
943
+ `Recipient "${label}" not found`,
944
+ 'RECIPIENT_NOT_FOUND',
945
+ { label },
946
+ );
947
+ }
948
+
949
+ if (recipients.length === 1) {
950
+ throw new CasError(
951
+ 'Cannot remove the last recipient',
952
+ 'CANNOT_REMOVE_LAST_RECIPIENT',
953
+ );
954
+ }
955
+
956
+ const filtered = recipients.filter((r) => r.label !== label).map((r) => ({ ...r }));
957
+ if (filtered.length === 0) {
958
+ throw new CasError(
959
+ 'Cannot remove the last recipient',
960
+ 'CANNOT_REMOVE_LAST_RECIPIENT',
961
+ );
962
+ }
963
+ const json = manifest.toJSON();
964
+ const updatedEncryption = { ...json.encryption, recipients: filtered };
965
+
966
+ return new Manifest({ ...json, encryption: updatedEncryption });
967
+ }
968
+
969
+ /**
970
+ * Lists recipient labels from an envelope-encrypted manifest.
971
+ *
972
+ * @param {import('../value-objects/Manifest.js').default} manifest
973
+ * @returns {string[]} Recipient labels, or empty array if not envelope-encrypted.
974
+ */
975
+ listRecipients(manifest) {
976
+ return (manifest.encryption?.recipients || []).map((r) => r.label);
977
+ }
978
+
979
+ /**
980
+ * Rotates a recipient's key without re-encrypting data blobs.
981
+ *
982
+ * Re-wraps the DEK with `newKey` for the matched recipient entry.
983
+ * Increments `keyVersion` at both manifest-level and recipient-level.
984
+ *
985
+ * @param {Object} options
986
+ * @param {import('../value-objects/Manifest.js').default} options.manifest
987
+ * @param {Buffer} options.oldKey - Current KEK of the recipient to rotate.
988
+ * @param {Buffer} options.newKey - New KEK to wrap the DEK with.
989
+ * @param {string} [options.label] - If provided, only rotate the named recipient.
990
+ * @returns {Promise<import('../value-objects/Manifest.js').default>}
991
+ * @throws {CasError} ROTATION_NOT_SUPPORTED if manifest has no recipients.
992
+ * @throws {CasError} RECIPIENT_NOT_FOUND if label doesn't exist.
993
+ * @throws {CasError} DEK_UNWRAP_FAILED if oldKey doesn't match the recipient.
994
+ * @throws {CasError} NO_MATCHING_RECIPIENT if no label and oldKey matches no entry.
995
+ */
996
+ async rotateKey({ manifest, oldKey, newKey, label }) {
997
+ const recipients = manifest.encryption?.recipients;
998
+ if (!recipients || recipients.length === 0) {
999
+ throw new CasError(
1000
+ 'Key rotation requires envelope encryption (recipients)',
1001
+ 'ROTATION_NOT_SUPPORTED',
1002
+ );
1003
+ }
1004
+
1005
+ this.crypto._validateKey(oldKey);
1006
+ this.crypto._validateKey(newKey);
1007
+
1008
+ const { matchIndex, dek } = label
1009
+ ? await this.#findRecipientByLabel(recipients, label, oldKey)
1010
+ : await this.#findRecipientByKey(recipients, oldKey);
1011
+
1012
+ return this.#buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey });
1013
+ }
1014
+
1015
+ /**
1016
+ * Finds a recipient by label and unwraps the DEK.
1017
+ */
1018
+ async #findRecipientByLabel(recipients, label, oldKey) {
1019
+ const matchIndex = recipients.findIndex((r) => r.label === label);
1020
+ if (matchIndex === -1) {
1021
+ throw new CasError(`Recipient "${label}" not found`, 'RECIPIENT_NOT_FOUND', { label });
1022
+ }
1023
+ const dek = await this._unwrapDek(recipients[matchIndex], oldKey);
1024
+ return { matchIndex, dek };
1025
+ }
1026
+
1027
+ /**
1028
+ * Finds the first recipient whose DEK can be unwrapped with the given key.
1029
+ */
1030
+ async #findRecipientByKey(recipients, oldKey) {
1031
+ for (let i = 0; i < recipients.length; i++) {
1032
+ try {
1033
+ const dek = await this._unwrapDek(recipients[i], oldKey);
1034
+ return { matchIndex: i, dek };
1035
+ } catch (err) {
1036
+ if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
1037
+ }
1038
+ }
1039
+ throw new CasError(
1040
+ 'No recipient entry could be unwrapped with the provided key',
1041
+ 'NO_MATCHING_RECIPIENT',
1042
+ );
1043
+ }
1044
+
1045
+ /**
1046
+ * Builds a new Manifest with the rotated recipient entry and updated keyVersions.
1047
+ */
1048
+ async #buildRotatedManifest({ manifest, recipients, matchIndex, dek, newKey }) {
1049
+ const newWrapped = await this._wrapDek(dek, newKey);
1050
+ const manifestKeyVersion = (manifest.encryption.keyVersion || 0) + 1;
1051
+ const recipientKeyVersion = (recipients[matchIndex].keyVersion || 0) + 1;
1052
+
1053
+ const json = manifest.toJSON();
1054
+ const updatedRecipients = recipients.map((r, i) => {
1055
+ if (i === matchIndex) {
1056
+ return { ...r, ...newWrapped, keyVersion: recipientKeyVersion };
1057
+ }
1058
+ return { ...r };
1059
+ });
1060
+
1061
+ return new Manifest({
1062
+ ...json,
1063
+ encryption: { ...json.encryption, recipients: updatedRecipients, keyVersion: manifestKeyVersion },
1064
+ });
1065
+ }
1066
+
746
1067
  /**
747
1068
  * Verifies the integrity of a stored file by re-hashing its chunks.
748
1069
  * @param {import('../value-objects/Manifest.js').default} manifest
@@ -11,6 +11,16 @@ export interface KdfParams {
11
11
  keyLength: number;
12
12
  }
13
13
 
14
+ /** A single recipient entry in an envelope-encrypted manifest. */
15
+ export interface RecipientEntry {
16
+ label: string;
17
+ wrappedDek: string;
18
+ nonce: string;
19
+ tag: string;
20
+ kekType?: string;
21
+ keyVersion?: number;
22
+ }
23
+
14
24
  /** AES-256-GCM encryption metadata attached to an encrypted manifest. */
15
25
  export interface EncryptionMeta {
16
26
  algorithm: string;
@@ -18,6 +28,8 @@ export interface EncryptionMeta {
18
28
  tag: string;
19
29
  encrypted: boolean;
20
30
  kdf?: KdfParams;
31
+ recipients?: RecipientEntry[];
32
+ keyVersion?: number;
21
33
  }
22
34
 
23
35
  /** Compression metadata. */
@@ -27,7 +27,9 @@ export default class Manifest {
27
27
  this.filename = data.filename;
28
28
  this.size = data.size;
29
29
  this.chunks = data.chunks.map((c) => new Chunk(c));
30
- this.encryption = data.encryption ? { ...data.encryption } : undefined;
30
+ this.encryption = data.encryption
31
+ ? { ...data.encryption, recipients: data.encryption.recipients?.map((r) => ({ ...r })) }
32
+ : undefined;
31
33
  this.compression = data.compression ? { ...data.compression } : undefined;
32
34
  this.chunking = data.chunking
33
35
  ? { strategy: data.chunking.strategy, params: { ...data.chunking.params } }