@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.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,55 @@ 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
+
32
+ ## [5.1.0] — Locksmith (2026-02-28)
33
+
34
+ ### Added
35
+ - **Envelope encryption (DEK/KEK)** — multi-recipient model where a random DEK encrypts content and per-recipient KEKs wrap the DEK. Recipients can be added/removed without re-encrypting data.
36
+ - **`RecipientSchema`** — Zod schema for validating recipient entries in manifests.
37
+ - **`recipients` field on `EncryptionSchema`** — optional array of `{ label, wrappedDek, nonce, tag }` entries.
38
+ - **`CasService.addRecipient()` / `removeRecipient()` / `listRecipients()`** — manage envelope recipients on existing manifests.
39
+ - **`--recipient <label:keyfile>` CLI flag** — repeatable flag on `git cas store` for envelope encryption.
40
+ - **`git cas recipient add/remove/list`** subcommands — CLI management of envelope recipients.
41
+ - **`RecipientEntry` type re-exported** from `index.d.ts`.
42
+ - 48 new unit tests covering envelope store/restore, recipient management, edge cases, and fuzz round-trips.
43
+
44
+ ### Fixed
45
+ - **`_wrapDek` / `_unwrapDek` missing `await`** — these called async `encryptBuffer()` / `decryptBuffer()` without `await`, silently producing garbage on Bun/Deno runtimes where crypto is async.
46
+ - **`--recipient` + `--vault-passphrase` not guarded** — CLI now rejects combining `--recipient` with `--key-file` or `--vault-passphrase`.
47
+ - **Dead `_resolveEncryptionKey` method removed** — superseded by `_resolveDecryptionKey` but left behind.
48
+ - **Redundant `RECIPIENT_NOT_FOUND` guards** in `removeRecipient` collapsed into one.
49
+ - **`addRecipient` duplicated unwrap loop** replaced with `_resolveKeyForRecipients` reuse.
50
+ - **`removeRecipient` post-filter guard** — defense-in-depth check prevents zero recipients when duplicate labels exist in corrupted/crafted manifests.
51
+ - **`EncryptionSchema` empty recipients** — `recipients` array now enforces `min(1)` to reject undecryptable envelope manifests.
52
+ - **`parseRecipient` empty keyfile** — CLI now rejects `--recipient alice:` (missing keyfile path) with a clear error.
53
+ - **CLI 30s hang in Docker** — `process.exit()` with I/O flushing prevents `setTimeout` leak in containerized runtimes.
54
+ - **Deno Dockerfile** — multi-stage Node 22 copy replaces `apt install nodejs`, improving layer caching and image size.
55
+ - **Runtime-neutral Docker hint** in integration tests; `afterAll` guards `rmSync` against partial `beforeAll` failures.
56
+
8
57
  ## [5.0.0] — Hydra (2026-02-28)
9
58
 
10
59
  ### Breaking Changes
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
@@ -8,6 +8,12 @@ const HINTS = {
8
8
  VAULT_ENTRY_NOT_FOUND: "Run 'git cas vault list' to see available entries",
9
9
  VAULT_ENTRY_EXISTS: 'Use --force to overwrite',
10
10
  INTEGRITY_ERROR: 'Check that the correct key or passphrase was used',
11
+ NO_MATCHING_RECIPIENT: 'The provided key does not match any recipient in the manifest',
12
+ DEK_UNWRAP_FAILED: 'The existing key does not match any recipient — cannot unwrap DEK',
13
+ RECIPIENT_NOT_FOUND: 'No recipient with that label exists in the manifest',
14
+ RECIPIENT_ALREADY_EXISTS: 'A recipient with that label already exists',
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',
11
17
  };
12
18
 
13
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('4.0.1')
21
+ .version('5.2.1')
22
22
  .option('-q, --quiet', 'Suppress progress output')
23
23
  .option('--json', 'Output results as JSON');
24
24
 
@@ -96,52 +96,75 @@ function validateRestoreFlags(opts) {
96
96
  // ---------------------------------------------------------------------------
97
97
  // store
98
98
  // ---------------------------------------------------------------------------
99
+ /**
100
+ * Build store options, resolving encryption key or recipients.
101
+ */
102
+ async function buildStoreOpts(cas, file, opts) {
103
+ const storeOpts = { filePath: file, slug: opts.slug };
104
+ if (opts.recipient) {
105
+ storeOpts.recipients = opts.recipient;
106
+ } else {
107
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
108
+ if (encryptionKey) { storeOpts.encryptionKey = encryptionKey; }
109
+ }
110
+ return storeOpts;
111
+ }
112
+
113
+ /**
114
+ * Parse a --recipient flag value into { label, key }.
115
+ * Format: label:keyfile
116
+ */
117
+ function parseRecipient(value, previous) {
118
+ const sep = value.indexOf(':');
119
+ if (sep < 1) {
120
+ throw new Error(`Invalid --recipient format "${value}": expected label:keyfile`);
121
+ }
122
+ const label = value.slice(0, sep);
123
+ const keyfile = value.slice(sep + 1);
124
+ if (!keyfile) {
125
+ throw new Error(`Invalid --recipient format "${value}": missing keyfile path`);
126
+ }
127
+ const key = readKeyFile(keyfile);
128
+ const list = previous || [];
129
+ list.push({ label, key });
130
+ return list;
131
+ }
132
+
99
133
  program
100
134
  .command('store <file>')
101
135
  .description('Store a file into Git CAS')
102
136
  .requiredOption('--slug <slug>', 'Asset slug identifier')
103
137
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
138
+ .option('--recipient <label:keyfile>', 'Envelope recipient (repeatable)', parseRecipient)
104
139
  .option('--tree', 'Also create a Git tree and print its OID')
105
140
  .option('--force', 'Overwrite existing vault entry')
106
141
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption (prefer GIT_CAS_PASSPHRASE env var)')
107
142
  .option('--cwd <dir>', 'Git working directory', '.')
108
143
  .action(runAction(async (file, opts) => {
144
+ if (opts.recipient && (opts.keyFile || resolvePassphrase(opts))) {
145
+ throw new Error('Provide --key-file/--vault-passphrase or --recipient, not both');
146
+ }
147
+ if (opts.force && !opts.tree) {
148
+ throw new Error('--force requires --tree');
149
+ }
109
150
  const json = program.opts().json;
110
151
  const quiet = program.opts().quiet || json;
111
152
  const observer = new EventEmitterObserver();
112
153
  const cas = createCas(opts.cwd, { observability: observer });
113
- const encryptionKey = await resolveEncryptionKey(cas, opts);
114
- if (opts.force && !opts.tree) {
115
- throw new Error('--force requires --tree');
116
- }
117
- const storeOpts = { filePath: file, slug: opts.slug };
118
- if (encryptionKey) {
119
- storeOpts.encryptionKey = encryptionKey;
120
- }
121
154
 
122
- const progress = createStoreProgress({
123
- filePath: file, chunkSize: cas.chunkSize, quiet,
124
- });
155
+ const storeOpts = await buildStoreOpts(cas, file, opts);
156
+ const progress = createStoreProgress({ filePath: file, chunkSize: cas.chunkSize, quiet });
125
157
  progress.attach(observer);
126
158
  let manifest;
127
- try {
128
- manifest = await cas.storeFile(storeOpts);
129
- } finally {
130
- progress.detach();
131
- }
159
+ try { manifest = await cas.storeFile(storeOpts); } finally { progress.detach(); }
132
160
 
133
161
  if (opts.tree) {
134
162
  const treeOid = await cas.createTree({ manifest });
135
163
  await cas.addToVault({ slug: opts.slug, treeOid, force: !!opts.force });
136
- if (json) {
137
- process.stdout.write(`${JSON.stringify({ treeOid })}\n`);
138
- } else {
139
- process.stdout.write(`${treeOid}\n`);
140
- }
141
- } else if (json) {
142
- process.stdout.write(`${JSON.stringify({ manifest: manifest.toJSON() })}\n`);
164
+ process.stdout.write(json ? `${JSON.stringify({ treeOid })}\n` : `${treeOid}\n`);
143
165
  } else {
144
- process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
166
+ const output = json ? JSON.stringify({ manifest: manifest.toJSON() }) : JSON.stringify(manifest.toJSON(), null, 2);
167
+ process.stdout.write(`${output}\n`);
145
168
  }
146
169
  }, getJson));
147
170
 
@@ -406,6 +429,40 @@ vault
406
429
  }
407
430
  }, getJson));
408
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
+
409
466
  // ---------------------------------------------------------------------------
410
467
  // vault dashboard
411
468
  // ---------------------------------------------------------------------------
@@ -419,4 +476,134 @@ vault
419
476
  await launchDashboard(cas);
420
477
  }, getJson));
421
478
 
422
- await program.parseAsync();
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
+
521
+ // ---------------------------------------------------------------------------
522
+ // recipient add / remove / list
523
+ // ---------------------------------------------------------------------------
524
+ const recipient = program
525
+ .command('recipient')
526
+ .description('Manage envelope encryption recipients');
527
+
528
+ recipient
529
+ .command('add <slug>')
530
+ .description('Add a recipient to an envelope-encrypted asset')
531
+ .requiredOption('--label <label>', 'Label for the new recipient')
532
+ .requiredOption('--key-file <path>', 'Path to 32-byte key file for the new recipient')
533
+ .requiredOption('--existing-key-file <path>', 'Path to key file of an existing recipient')
534
+ .option('--cwd <dir>', 'Git working directory', '.')
535
+ .action(runAction(async (slug, opts) => {
536
+ const cas = createCas(opts.cwd);
537
+ const treeOid = await cas.resolveVaultEntry({ slug });
538
+ const manifest = await cas.readManifest({ treeOid });
539
+
540
+ const existingKey = readKeyFile(opts.existingKeyFile);
541
+ const newRecipientKey = readKeyFile(opts.keyFile);
542
+
543
+ const updated = await cas.addRecipient({
544
+ manifest,
545
+ existingKey,
546
+ newRecipientKey,
547
+ label: opts.label,
548
+ });
549
+
550
+ const newTreeOid = await cas.createTree({ manifest: updated });
551
+ await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
552
+
553
+ const json = program.opts().json;
554
+ if (json) {
555
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
556
+ } else {
557
+ process.stdout.write(`${newTreeOid}\n`);
558
+ }
559
+ }, getJson));
560
+
561
+ recipient
562
+ .command('remove <slug>')
563
+ .description('Remove a recipient from an envelope-encrypted asset')
564
+ .requiredOption('--label <label>', 'Label of the recipient to remove')
565
+ .option('--cwd <dir>', 'Git working directory', '.')
566
+ .action(runAction(async (slug, opts) => {
567
+ const cas = createCas(opts.cwd);
568
+ const treeOid = await cas.resolveVaultEntry({ slug });
569
+ const manifest = await cas.readManifest({ treeOid });
570
+
571
+ const updated = await cas.removeRecipient({ manifest, label: opts.label });
572
+
573
+ const newTreeOid = await cas.createTree({ manifest: updated });
574
+ await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
575
+
576
+ const json = program.opts().json;
577
+ if (json) {
578
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
579
+ } else {
580
+ process.stdout.write(`${newTreeOid}\n`);
581
+ }
582
+ }, getJson));
583
+
584
+ recipient
585
+ .command('list <slug>')
586
+ .description('List recipients of an envelope-encrypted asset')
587
+ .option('--cwd <dir>', 'Git working directory', '.')
588
+ .action(runAction(async (slug, opts) => {
589
+ const cas = createCas(opts.cwd);
590
+ const treeOid = await cas.resolveVaultEntry({ slug });
591
+ const manifest = await cas.readManifest({ treeOid });
592
+
593
+ const labels = await cas.listRecipients(manifest);
594
+ const json = program.opts().json;
595
+ if (json) {
596
+ process.stdout.write(`${JSON.stringify(labels)}\n`);
597
+ } else {
598
+ for (const label of labels) {
599
+ process.stdout.write(`${label}\n`);
600
+ }
601
+ }
602
+ }, getJson));
603
+
604
+ await program.parseAsync();
605
+
606
+ // Flush stdout/stderr before exiting — spawned git child processes leave
607
+ // libuv handles that prevent natural exit in containerized environments.
608
+ const code = process.exitCode || 0;
609
+ process.stdout.write('', () => process.stderr.write('', () => process.exit(code)));
package/index.d.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import Manifest from "./src/domain/value-objects/Manifest.js";
7
- import type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef } from "./src/domain/value-objects/Manifest.js";
7
+ import type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, RecipientEntry } from "./src/domain/value-objects/Manifest.js";
8
8
  import Chunk from "./src/domain/value-objects/Chunk.js";
9
9
  import CasService from "./src/domain/services/CasService.js";
10
10
  import type {
@@ -18,7 +18,7 @@ import type {
18
18
  } from "./src/domain/services/CasService.js";
19
19
 
20
20
  export { CasService, Manifest, Chunk };
21
- export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, CryptoPort, CodecPort, GitPersistencePort, ObservabilityPort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
21
+ export type { EncryptionMeta, ManifestData, CompressionMeta, KdfParams, SubManifestRef, RecipientEntry, CryptoPort, CodecPort, GitPersistencePort, ObservabilityPort, CasServiceOptions, DeriveKeyOptions, DeriveKeyResult };
22
22
 
23
23
  /** Abstract port for splitting a byte stream into chunks. */
24
24
  export declare class ChunkingPort {
@@ -302,6 +302,7 @@ export default class ContentAddressableStore {
302
302
  passphrase?: string;
303
303
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
304
304
  compression?: { algorithm: "gzip" };
305
+ recipients?: Array<{ label: string; key: Buffer }>;
305
306
  }): Promise<Manifest>;
306
307
 
307
308
  store(options: {
@@ -312,6 +313,7 @@ export default class ContentAddressableStore {
312
313
  passphrase?: string;
313
314
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
314
315
  compression?: { algorithm: "gzip" };
316
+ recipients?: Array<{ label: string; key: Buffer }>;
315
317
  }): Promise<Manifest>;
316
318
 
317
319
  restoreFile(options: {
@@ -349,6 +351,27 @@ export default class ContentAddressableStore {
349
351
 
350
352
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
351
353
 
354
+ addRecipient(options: {
355
+ manifest: Manifest;
356
+ existingKey: Buffer;
357
+ newRecipientKey: Buffer;
358
+ label: string;
359
+ }): Promise<Manifest>;
360
+
361
+ removeRecipient(options: {
362
+ manifest: Manifest;
363
+ label: string;
364
+ }): Promise<Manifest>;
365
+
366
+ listRecipients(manifest: Manifest): Promise<string[]>;
367
+
368
+ rotateKey(options: {
369
+ manifest: Manifest;
370
+ oldKey: Buffer;
371
+ newKey: Buffer;
372
+ label?: string;
373
+ }): Promise<Manifest>;
374
+
352
375
  // Vault — delegates to VaultService
353
376
 
354
377
  static VAULT_REF: string;
@@ -373,4 +396,14 @@ export default class ContentAddressableStore {
373
396
  resolveVaultEntry(options: { slug: string }): Promise<string>;
374
397
 
375
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
+ }>;
376
409
  }