@git-stunts/git-cas 5.1.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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,30 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [5.2.1] — Carousel polish (2026-02-28)
9
+
10
+ ### Added
11
+ - CLI reference in `docs/API.md` for `git cas rotate` and `git cas vault rotate` flags.
12
+
13
+ ### Changed
14
+ - Rotation helpers in `CasService` use native `#private` methods, matching the facade's style.
15
+ - `VAULT_CONFLICT` and `VAULT_METADATA_INVALID` error code docs now list `rotateVaultPassphrase()`.
16
+
17
+ ### Fixed
18
+ - `rotateVaultPassphrase` now honours `kdfOptions.algorithm` instead of silently using the old algorithm.
19
+ - Rotation integration test no longer flaps under CI load (reduced test-only KDF iterations).
20
+
21
+ ## [5.2.0] — Carousel (2026-02-28)
22
+
23
+ ### Added
24
+ - **Key rotation without re-encrypting data** — `CasService.rotateKey()` re-wraps the DEK with a new KEK, leaving data blobs untouched. Enables key compromise response without re-storing assets.
25
+ - **`keyVersion` tracking** — manifest-level and per-recipient `keyVersion` counters track rotation history for audit compliance. Optional field, backward-compatible with existing manifests.
26
+ - **`git cas rotate` CLI command** — rotate a recipient's key via `--slug` (vault round-trip) or `--oid` (manifest-only). Supports `--label` for targeted single-recipient rotation.
27
+ - **`rotateVaultPassphrase()`** — rotate the vault-level encryption passphrase across all envelope-encrypted entries in a single atomic commit. Non-envelope entries are skipped with reporting.
28
+ - **`git cas vault rotate` CLI command** — rotate vault passphrase from the command line with `--old-passphrase` and `--new-passphrase`.
29
+ - **`ROTATION_NOT_SUPPORTED` error code** — thrown when `rotateKey()` is called on a manifest without envelope encryption (legacy/direct-key).
30
+ - 27 new unit tests covering key rotation, schema validation, and vault passphrase rotation.
31
+
8
32
  ## [5.1.0] — Locksmith (2026-02-28)
9
33
 
10
34
  ### Added
package/README.md CHANGED
@@ -19,8 +19,10 @@ We use the object database.
19
19
  ## What you get
20
20
 
21
21
  - **Dedupe for free** Git already hashes objects. We just lean into it.
22
- - **Chunked storage** big files become stable, reusable blobs.
22
+ - **Chunked storage** big files become stable, reusable blobs. Fixed-size or content-defined chunking (CDC).
23
23
  - **Optional AES-256-GCM encryption** store secrets without leaking plaintext into the ODB.
24
+ - **Multi-recipient encryption** envelope model (DEK/KEK) — add/remove access without re-encrypting data.
25
+ - **Key rotation** rotate keys without re-encrypting data blobs. Respond to compromise in seconds.
24
26
  - **Compression** gzip before encryption — smaller blobs, same round-trip.
25
27
  - **Passphrase encryption** derive keys from passphrases via PBKDF2 or scrypt — no raw key management.
26
28
  - **Merkle manifests** large files auto-split into sub-manifests for scalability.
@@ -29,18 +31,81 @@ We use the object database.
29
31
  - **Full round-trip** store, tree, and restore — get your bytes back, verified.
30
32
  - **Lifecycle management** `readManifest`, `deleteAsset`, `findOrphanedChunks` — inspect trees, plan deletions, audit storage.
31
33
  - **Vault** GC-safe ref-based storage. One ref (`refs/cas/vault`) indexes all assets by slug. No more silent data loss from `git gc`.
34
+ - **Interactive dashboard** `git cas inspect` with chunk heatmap, animated progress bars, and rich manifest views.
35
+ - **Verify & JSON output** `git cas verify` checks integrity; `--json` on all commands for CI/scripting.
32
36
 
33
37
  **Use it for:** binary assets, build artifacts, model weights, data packs, secret bundles, weird experiments, etc.
34
38
 
35
39
  <img src="./docs/demo.gif" alt="git-cas demo" />
36
40
 
37
- ## What's new in v2.0.0
41
+ ## What's new in v5.2.1
38
42
 
39
- **Compression** — `compression: { algorithm: 'gzip' }` on `store()`. Compression runs before encryption. Decompression on `restore()` is automatic.
43
+ Bug fix: `rotateVaultPassphrase` now honours `kdfOptions.algorithm` — previously the `--algorithm` flag was silently ignored, always reusing the old KDF algorithm. CLI flag tables in `docs/API.md` are now split per command with `--cwd` documented.
40
44
 
41
- **Passphrase-based encryption** — Pass `passphrase` instead of `encryptionKey`. Keys are derived via PBKDF2 (default) or scrypt. KDF parameters are stored in the manifest for deterministic re-derivation. Use `deriveKey()` directly for manual control.
45
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
42
46
 
43
- **Merkle tree manifests** — When chunk count exceeds `merkleThreshold` (default: 1000), manifests are automatically split into sub-manifests stored as separate blobs. `readManifest()` transparently reconstitutes them. Full backward compatibility with v1 manifests.
47
+ ## What's new in v5.2.0
48
+
49
+ **Key rotation without re-encrypting data** — Rotate a recipient's key by re-wrapping the DEK. Data blobs are never touched. Respond to key compromise in seconds, not hours.
50
+
51
+ ```js
52
+ // Rotate a single recipient's key
53
+ const rotated = await cas.rotateKey({
54
+ manifest, oldKey: aliceOldKey, newKey: aliceNewKey, label: 'alice',
55
+ });
56
+
57
+ // Rotate the vault passphrase (all entries, atomic commit)
58
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase({
59
+ oldPassphrase: 'old-secret', newPassphrase: 'new-secret',
60
+ });
61
+ ```
62
+
63
+ ```bash
64
+ # Rotate a recipient key
65
+ git cas rotate --slug prod-secrets --old-key-file old.key --new-key-file new.key
66
+
67
+ # Rotate vault passphrase
68
+ git cas vault rotate --old-passphrase old-secret --new-passphrase new-secret
69
+ ```
70
+
71
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
72
+
73
+ ## What's new in v5.1.0
74
+
75
+ **Multi-recipient envelope encryption** — Each file is encrypted with a random DEK; recipient KEKs wrap the DEK. Add or remove team members without re-encrypting data.
76
+
77
+ ```js
78
+ // API: store for multiple recipients
79
+ const manifest = await cas.storeFile({
80
+ filePath: './secrets.tar.gz',
81
+ slug: 'prod-secrets',
82
+ recipients: [
83
+ { label: 'alice', key: aliceKey },
84
+ { label: 'bob', key: bobKey },
85
+ ],
86
+ });
87
+
88
+ // Add a recipient later (no re-encryption)
89
+ const updated = await cas.addRecipient({
90
+ manifest, existingKey: aliceKey, newRecipientKey: carolKey, label: 'carol',
91
+ });
92
+
93
+ // List / remove recipients
94
+ const labels = await cas.listRecipients({ manifest });
95
+ const trimmed = await cas.removeRecipient({ manifest, label: 'bob' });
96
+ ```
97
+
98
+ ```bash
99
+ # CLI: store with multiple recipients
100
+ git cas store ./secrets.tar.gz --slug prod-secrets \
101
+ --recipient alice:./keys/alice.key \
102
+ --recipient bob:./keys/bob.key --tree
103
+
104
+ # Manage recipients
105
+ git cas recipient list prod-secrets
106
+ git cas recipient add prod-secrets --label carol --key-file ./keys/carol.key --existing-key-file ./keys/alice.key
107
+ git cas recipient remove prod-secrets --label bob
108
+ ```
44
109
 
45
110
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
46
111
 
@@ -83,6 +148,28 @@ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
83
148
 
84
149
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
85
150
 
151
+ ## What's new in v3.1.0
152
+
153
+ **Interactive vault dashboard** — `git cas inspect --slug my-asset` renders a rich TUI with chunk heatmap, encryption card, and history timeline. Animated progress bars for long store/restore operations.
154
+
155
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
156
+
157
+ ## What's new in v3.0.0
158
+
159
+ **Vault** — GC-safe ref-based storage under `refs/cas/vault`. Assets are indexed by slug and survive `git gc`. Full CLI: `git cas vault init`, `list`, `info`, `remove`, `history`. Store with `--tree` to vault automatically.
160
+
161
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
162
+
163
+ ## What's new in v2.0.0
164
+
165
+ **Compression** — `compression: { algorithm: 'gzip' }` on `store()`. Compression runs before encryption. Decompression on `restore()` is automatic.
166
+
167
+ **Passphrase-based encryption** — Pass `passphrase` instead of `encryptionKey`. Keys are derived via PBKDF2 (default) or scrypt. KDF parameters are stored in the manifest for deterministic re-derivation. Use `deriveKey()` directly for manual control.
168
+
169
+ **Merkle tree manifests** — When chunk count exceeds `merkleThreshold` (default: 1000), manifests are automatically split into sub-manifests stored as separate blobs. `readManifest()` transparently reconstitutes them. Full backward compatibility with v1 manifests.
170
+
171
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
172
+
86
173
  ## Install
87
174
 
88
175
  ```bash
@@ -148,18 +235,44 @@ git cas restore --slug my-image --out ./restored.png
148
235
  # Restore from a direct tree OID
149
236
  git cas restore --oid <tree-oid> --out ./restored.png
150
237
 
238
+ # Verify integrity without restoring
239
+ git cas verify --slug my-image
240
+
241
+ # Inspect manifest (interactive dashboard)
242
+ git cas inspect --slug my-image
243
+
151
244
  # Vault management
152
245
  git cas vault init
153
- git cas vault list
246
+ git cas vault list # TTY table
247
+ git cas vault list --json # structured JSON
248
+ git cas vault list --filter "photos/*" # glob filter
154
249
  git cas vault info my-image
155
250
  git cas vault remove my-image
156
251
  git cas vault history
157
252
 
253
+ # Multi-recipient encryption
254
+ git cas store ./secret.bin --slug shared \
255
+ --recipient alice:./keys/alice.key \
256
+ --recipient bob:./keys/bob.key --tree
257
+ git cas recipient list shared
258
+ git cas recipient add shared --label carol --key-file ./keys/carol.key --existing-key-file ./keys/alice.key
259
+ git cas recipient remove shared --label bob
260
+
261
+ # Key rotation (no re-encryption)
262
+ git cas rotate --slug shared --old-key-file old.key --new-key-file new.key
263
+ git cas rotate --slug shared --old-key-file old.key --new-key-file new.key --label alice
264
+
265
+ # Vault passphrase rotation
266
+ git cas vault rotate --old-passphrase old-secret --new-passphrase new-secret
267
+
158
268
  # Encrypted vault round-trip (passphrase via env var or --vault-passphrase flag)
159
269
  export GIT_CAS_PASSPHRASE="secret"
160
270
  git cas vault init
161
271
  git cas store ./secret.bin --slug vault-entry --tree
162
272
  git cas restore --slug vault-entry --out ./decrypted.bin
273
+
274
+ # JSON output on any command (for CI/scripting)
275
+ git cas store ./data.bin --slug my-data --tree --json
163
276
  ```
164
277
 
165
278
  ## Documentation
@@ -181,7 +294,7 @@ That's git-cas. The orphan branch gives you none of:
181
294
 
182
295
  | | Orphan branch | git-cas |
183
296
  |---|---|---|
184
- | **Encryption** | None — plaintext forever in history | AES-256-GCM + passphrase KDF |
297
+ | **Encryption** | None — plaintext forever in history | AES-256-GCM + passphrase KDF + multi-recipient + key rotation |
185
298
  | **Large files** | Bloats `git clone` for everyone | Chunked, restored on demand |
186
299
  | **Dedup** | None | Chunk-level content addressing |
187
300
  | **Integrity** | Git SHA-1 | SHA-256 per chunk + GCM auth tag |
package/bin/actions.js CHANGED
@@ -13,6 +13,7 @@ const HINTS = {
13
13
  RECIPIENT_NOT_FOUND: 'No recipient with that label exists in the manifest',
14
14
  RECIPIENT_ALREADY_EXISTS: 'A recipient with that label already exists',
15
15
  CANNOT_REMOVE_LAST_RECIPIENT: 'At least one recipient must remain in the manifest',
16
+ ROTATION_NOT_SUPPORTED: 'Key rotation requires envelope encryption — store with --recipient first',
16
17
  };
17
18
 
18
19
  /**
package/bin/git-cas.js CHANGED
@@ -18,7 +18,7 @@ const getJson = () => program.opts().json;
18
18
  program
19
19
  .name('git-cas')
20
20
  .description('Content Addressable Storage backed by Git')
21
- .version('5.0.0')
21
+ .version('5.2.1')
22
22
  .option('-q, --quiet', 'Suppress progress output')
23
23
  .option('--json', 'Output results as JSON');
24
24
 
@@ -429,6 +429,40 @@ vault
429
429
  }
430
430
  }, getJson));
431
431
 
432
+ // ---------------------------------------------------------------------------
433
+ // vault rotate
434
+ // ---------------------------------------------------------------------------
435
+ vault
436
+ .command('rotate')
437
+ .description('Rotate vault-level encryption passphrase')
438
+ .requiredOption('--old-passphrase <pass>', 'Current vault passphrase')
439
+ .requiredOption('--new-passphrase <pass>', 'New vault passphrase')
440
+ .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)')
441
+ .option('--cwd <dir>', 'Git working directory', '.')
442
+ .action(runAction(async (opts) => {
443
+ const cas = createCas(opts.cwd);
444
+ const rotateOpts = {
445
+ oldPassphrase: opts.oldPassphrase,
446
+ newPassphrase: opts.newPassphrase,
447
+ };
448
+ if (opts.algorithm) {
449
+ rotateOpts.kdfOptions = { algorithm: opts.algorithm };
450
+ }
451
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase(rotateOpts);
452
+ const json = program.opts().json;
453
+ if (json) {
454
+ process.stdout.write(`${JSON.stringify({ commitOid, rotatedSlugs, skippedSlugs })}\n`);
455
+ } else {
456
+ process.stdout.write(`${commitOid}\n`);
457
+ if (rotatedSlugs.length) {
458
+ process.stderr.write(`rotated: ${rotatedSlugs.join(', ')}\n`);
459
+ }
460
+ if (skippedSlugs.length) {
461
+ process.stderr.write(`skipped: ${skippedSlugs.join(', ')}\n`);
462
+ }
463
+ }
464
+ }, getJson));
465
+
432
466
  // ---------------------------------------------------------------------------
433
467
  // vault dashboard
434
468
  // ---------------------------------------------------------------------------
@@ -442,6 +476,48 @@ vault
442
476
  await launchDashboard(cas);
443
477
  }, getJson));
444
478
 
479
+ // ---------------------------------------------------------------------------
480
+ // rotate
481
+ // ---------------------------------------------------------------------------
482
+ program
483
+ .command('rotate')
484
+ .description('Rotate an encryption key without re-encrypting data')
485
+ .option('--slug <slug>', 'Resolve tree OID from vault slug')
486
+ .option('--oid <tree-oid>', 'Direct tree OID')
487
+ .requiredOption('--old-key-file <path>', 'Path to current 32-byte key file')
488
+ .requiredOption('--new-key-file <path>', 'Path to new 32-byte key file')
489
+ .option('--label <label>', 'Rotate only the named recipient')
490
+ .option('--cwd <dir>', 'Git working directory', '.')
491
+ .action(runAction(async (opts) => {
492
+ validateRestoreFlags(opts);
493
+ const cas = createCas(opts.cwd);
494
+ const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
495
+ const manifest = await cas.readManifest({ treeOid });
496
+
497
+ const oldKey = readKeyFile(opts.oldKeyFile);
498
+ const newKey = readKeyFile(opts.newKeyFile);
499
+
500
+ const rotateOpts = { manifest, oldKey, newKey };
501
+ if (opts.label) { rotateOpts.label = opts.label; }
502
+
503
+ const updated = await cas.rotateKey(rotateOpts);
504
+ const json = program.opts().json;
505
+
506
+ if (opts.slug) {
507
+ const newTreeOid = await cas.createTree({ manifest: updated });
508
+ await cas.addToVault({ slug: opts.slug, treeOid: newTreeOid, force: true });
509
+ if (json) {
510
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid, keyVersion: updated.encryption.keyVersion })}\n`);
511
+ } else {
512
+ process.stdout.write(`${newTreeOid}\n`);
513
+ }
514
+ } else if (json) {
515
+ process.stdout.write(`${JSON.stringify(updated.toJSON())}\n`);
516
+ } else {
517
+ process.stdout.write(`${JSON.stringify(updated.toJSON(), null, 2)}\n`);
518
+ }
519
+ }, getJson));
520
+
445
521
  // ---------------------------------------------------------------------------
446
522
  // recipient add / remove / list
447
523
  // ---------------------------------------------------------------------------
package/index.d.ts CHANGED
@@ -365,6 +365,13 @@ export default class ContentAddressableStore {
365
365
 
366
366
  listRecipients(manifest: Manifest): Promise<string[]>;
367
367
 
368
+ rotateKey(options: {
369
+ manifest: Manifest;
370
+ oldKey: Buffer;
371
+ newKey: Buffer;
372
+ label?: string;
373
+ }): Promise<Manifest>;
374
+
368
375
  // Vault — delegates to VaultService
369
376
 
370
377
  static VAULT_REF: string;
@@ -389,4 +396,14 @@ export default class ContentAddressableStore {
389
396
  resolveVaultEntry(options: { slug: string }): Promise<string>;
390
397
 
391
398
  getVaultMetadata(): Promise<VaultMetadata | null>;
399
+
400
+ rotateVaultPassphrase(options: {
401
+ oldPassphrase: string;
402
+ newPassphrase: string;
403
+ kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
404
+ }): Promise<{
405
+ commitOid: string;
406
+ rotatedSlugs: string[];
407
+ skippedSlugs: string[];
408
+ }>;
392
409
  }
package/index.js CHANGED
@@ -9,6 +9,7 @@ import { Readable, Transform } from 'node:stream';
9
9
  import { pipeline } from 'node:stream/promises';
10
10
  import CasService from './src/domain/services/CasService.js';
11
11
  import VaultService from './src/domain/services/VaultService.js';
12
+ import CasError from './src/domain/errors/CasError.js';
12
13
  import GitPersistenceAdapter from './src/infrastructure/adapters/GitPersistenceAdapter.js';
13
14
  import GitRefAdapter from './src/infrastructure/adapters/GitRefAdapter.js';
14
15
  import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.js';
@@ -464,6 +465,20 @@ export default class ContentAddressableStore {
464
465
  return service.listRecipients(manifest);
465
466
  }
466
467
 
468
+ /**
469
+ * Rotates a recipient's key without re-encrypting data blobs.
470
+ * @param {Object} options
471
+ * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest
472
+ * @param {Buffer} options.oldKey - Current KEK of the recipient to rotate.
473
+ * @param {Buffer} options.newKey - New KEK to wrap the DEK with.
474
+ * @param {string} [options.label] - If provided, only rotate the named recipient.
475
+ * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>}
476
+ */
477
+ async rotateKey(options) {
478
+ const service = await this.#getService();
479
+ return await service.rotateKey(options);
480
+ }
481
+
467
482
  // ---------------------------------------------------------------------------
468
483
  // Vault — delegates to VaultService
469
484
  // ---------------------------------------------------------------------------
@@ -505,4 +520,123 @@ export default class ContentAddressableStore {
505
520
  const vault = await this.#getVault();
506
521
  return vault.getVaultMetadata();
507
522
  }
523
+
524
+ // ---------------------------------------------------------------------------
525
+ // Key rotation — orchestrates CasService + VaultService
526
+ // ---------------------------------------------------------------------------
527
+
528
+ /**
529
+ * Rotates the vault-level passphrase. Re-wraps every envelope-encrypted
530
+ * entry's DEK with a new KEK derived from `newPassphrase`. Entries using
531
+ * direct-key encryption are skipped.
532
+ *
533
+ * @param {Object} options
534
+ * @param {string} options.oldPassphrase - Current vault passphrase.
535
+ * @param {string} options.newPassphrase - New vault passphrase.
536
+ * @param {Object} [options.kdfOptions] - KDF options for new passphrase.
537
+ * @returns {Promise<{ commitOid: string, rotatedSlugs: string[], skippedSlugs: string[] }>}
538
+ */
539
+ async rotateVaultPassphrase({ oldPassphrase, newPassphrase, kdfOptions }) {
540
+ const service = await this.#getService();
541
+ const vault = await this.#getVault();
542
+
543
+ const MAX_RETRIES = 3;
544
+ const RETRY_BASE_MS = 50;
545
+
546
+ for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {
547
+ const state = await vault.readState();
548
+ if (!state.metadata?.encryption) {
549
+ throw new CasError('Vault is not encrypted — nothing to rotate', 'VAULT_METADATA_INVALID');
550
+ }
551
+
552
+ const { kdf } = state.metadata.encryption;
553
+ const oldKek = await ContentAddressableStore.#deriveKekFromKdf(service, oldPassphrase, kdf);
554
+ const { key: newKek, salt: newSalt, params: newParams } = await service.deriveKey({
555
+ passphrase: newPassphrase, ...kdfOptions, algorithm: kdfOptions?.algorithm || kdf.algorithm,
556
+ });
557
+
558
+ const result = await ContentAddressableStore.#rotateEntries({ service, entries: state.entries, oldKek, newKek });
559
+ const newMetadata = ContentAddressableStore.#buildRotatedMetadata(state.metadata, newSalt, newParams);
560
+
561
+ try {
562
+ const { commitOid } = await vault.writeCommit({
563
+ entries: result.updatedEntries,
564
+ metadata: newMetadata,
565
+ parentCommitOid: state.parentCommitOid,
566
+ message: `vault: rotate passphrase (${result.rotatedSlugs.length} rotated, ${result.skippedSlugs.length} skipped)`,
567
+ });
568
+ return { commitOid, rotatedSlugs: result.rotatedSlugs, skippedSlugs: result.skippedSlugs };
569
+ } catch (err) {
570
+ if (err instanceof CasError && err.code === 'VAULT_CONFLICT' && attempt < MAX_RETRIES - 1) {
571
+ await new Promise((r) => setTimeout(r, RETRY_BASE_MS * (2 ** attempt)));
572
+ continue;
573
+ }
574
+ throw err;
575
+ }
576
+ }
577
+ /* c8 ignore next 2 */
578
+ throw new CasError('Vault CAS retries exhausted', 'VAULT_CONFLICT');
579
+ }
580
+
581
+ /**
582
+ * Derives a KEK from a passphrase using stored KDF params.
583
+ * @private
584
+ */
585
+ static async #deriveKekFromKdf(service, passphrase, kdf) {
586
+ const { key } = await service.deriveKey({
587
+ passphrase,
588
+ salt: Buffer.from(kdf.salt, 'base64'),
589
+ algorithm: kdf.algorithm,
590
+ iterations: kdf.iterations,
591
+ cost: kdf.cost,
592
+ blockSize: kdf.blockSize,
593
+ parallelization: kdf.parallelization,
594
+ });
595
+ return key;
596
+ }
597
+
598
+ /**
599
+ * Iterates vault entries, rotating envelope-encrypted ones and skipping others.
600
+ * @private
601
+ */
602
+ static async #rotateEntries({ service, entries, oldKek, newKek }) {
603
+ const rotatedSlugs = [];
604
+ const skippedSlugs = [];
605
+ const updatedEntries = new Map(entries);
606
+
607
+ for (const [slug, treeOid] of entries) {
608
+ const manifest = await service.readManifest({ treeOid });
609
+ if (!manifest.encryption?.recipients?.length) {
610
+ skippedSlugs.push(slug);
611
+ continue;
612
+ }
613
+ const rotated = await service.rotateKey({ manifest, oldKey: oldKek, newKey: newKek });
614
+ updatedEntries.set(slug, await service.createTree({ manifest: rotated }));
615
+ rotatedSlugs.push(slug);
616
+ }
617
+
618
+ return { updatedEntries, rotatedSlugs, skippedSlugs };
619
+ }
620
+
621
+ /**
622
+ * Builds updated vault metadata with new KDF params.
623
+ * @private
624
+ */
625
+ static #buildRotatedMetadata(metadata, newSalt, newParams) {
626
+ return {
627
+ ...metadata,
628
+ encryption: {
629
+ cipher: metadata.encryption.cipher,
630
+ kdf: {
631
+ algorithm: newParams.algorithm,
632
+ salt: newSalt.toString('base64'),
633
+ ...('iterations' in newParams && { iterations: newParams.iterations }),
634
+ ...('cost' in newParams && { cost: newParams.cost }),
635
+ ...('blockSize' in newParams && { blockSize: newParams.blockSize }),
636
+ ...('parallelization' in newParams && { parallelization: newParams.parallelization }),
637
+ keyLength: newParams.keyLength,
638
+ },
639
+ },
640
+ };
641
+ }
508
642
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "5.1.0",
3
+ "version": "5.2.1",
4
4
  "description": "Content-addressed storage backed by Git's object database, with optional encryption and pluggable codecs",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -31,6 +31,7 @@ export declare const RecipientSchema: z.ZodObject<{
31
31
  nonce: z.ZodString;
32
32
  tag: z.ZodString;
33
33
  kekType: z.ZodOptional<z.ZodString>;
34
+ keyVersion: z.ZodOptional<z.ZodNumber>;
34
35
  }>;
35
36
 
36
37
  /** Validates the encryption metadata attached to an encrypted manifest. */
@@ -41,6 +42,7 @@ export declare const EncryptionSchema: z.ZodObject<{
41
42
  encrypted: z.ZodDefault<z.ZodBoolean>;
42
43
  kdf: z.ZodOptional<typeof KdfSchema>;
43
44
  recipients: z.ZodOptional<z.ZodArray<typeof RecipientSchema>>;
45
+ keyVersion: z.ZodOptional<z.ZodNumber>;
44
46
  }>;
45
47
 
46
48
  /** Validates compression metadata. */
@@ -31,6 +31,7 @@ export const RecipientSchema = z.object({
31
31
  nonce: z.string().min(1),
32
32
  tag: z.string().min(1),
33
33
  kekType: z.string().optional(),
34
+ keyVersion: z.number().int().min(0).optional(),
34
35
  });
35
36
 
36
37
  /** Validates the encryption metadata attached to an encrypted manifest. */
@@ -41,6 +42,7 @@ export const EncryptionSchema = z.object({
41
42
  encrypted: z.boolean().default(true),
42
43
  kdf: KdfSchema.optional(),
43
44
  recipients: z.array(RecipientSchema).min(1).optional(),
45
+ keyVersion: z.number().int().min(0).optional(),
44
46
  });
45
47
 
46
48
  /** Validates compression metadata. */
@@ -153,6 +153,13 @@ export default class CasService {
153
153
 
154
154
  listRecipients(manifest: Manifest): string[];
155
155
 
156
+ rotateKey(options: {
157
+ manifest: Manifest;
158
+ oldKey: Buffer;
159
+ newKey: Buffer;
160
+ label?: string;
161
+ }): Promise<Manifest>;
162
+
156
163
  verifyIntegrity(manifest: Manifest): Promise<boolean>;
157
164
 
158
165
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
@@ -976,6 +976,94 @@ export default class CasService {
976
976
  return (manifest.encryption?.recipients || []).map((r) => r.label);
977
977
  }
978
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
+
979
1067
  /**
980
1068
  * Verifies the integrity of a stored file by re-hashing its chunks.
981
1069
  * @param {import('../value-objects/Manifest.js').default} manifest
@@ -18,6 +18,7 @@ export interface RecipientEntry {
18
18
  nonce: string;
19
19
  tag: string;
20
20
  kekType?: string;
21
+ keyVersion?: number;
21
22
  }
22
23
 
23
24
  /** AES-256-GCM encryption metadata attached to an encrypted manifest. */
@@ -28,6 +29,7 @@ export interface EncryptionMeta {
28
29
  encrypted: boolean;
29
30
  kdf?: KdfParams;
30
31
  recipients?: RecipientEntry[];
32
+ keyVersion?: number;
31
33
  }
32
34
 
33
35
  /** Compression metadata. */