@git-stunts/git-cas 5.0.0 → 5.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,31 @@ 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.1.0] — Locksmith (2026-02-28)
9
+
10
+ ### Added
11
+ - **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.
12
+ - **`RecipientSchema`** — Zod schema for validating recipient entries in manifests.
13
+ - **`recipients` field on `EncryptionSchema`** — optional array of `{ label, wrappedDek, nonce, tag }` entries.
14
+ - **`CasService.addRecipient()` / `removeRecipient()` / `listRecipients()`** — manage envelope recipients on existing manifests.
15
+ - **`--recipient <label:keyfile>` CLI flag** — repeatable flag on `git cas store` for envelope encryption.
16
+ - **`git cas recipient add/remove/list`** subcommands — CLI management of envelope recipients.
17
+ - **`RecipientEntry` type re-exported** from `index.d.ts`.
18
+ - 48 new unit tests covering envelope store/restore, recipient management, edge cases, and fuzz round-trips.
19
+
20
+ ### Fixed
21
+ - **`_wrapDek` / `_unwrapDek` missing `await`** — these called async `encryptBuffer()` / `decryptBuffer()` without `await`, silently producing garbage on Bun/Deno runtimes where crypto is async.
22
+ - **`--recipient` + `--vault-passphrase` not guarded** — CLI now rejects combining `--recipient` with `--key-file` or `--vault-passphrase`.
23
+ - **Dead `_resolveEncryptionKey` method removed** — superseded by `_resolveDecryptionKey` but left behind.
24
+ - **Redundant `RECIPIENT_NOT_FOUND` guards** in `removeRecipient` collapsed into one.
25
+ - **`addRecipient` duplicated unwrap loop** replaced with `_resolveKeyForRecipients` reuse.
26
+ - **`removeRecipient` post-filter guard** — defense-in-depth check prevents zero recipients when duplicate labels exist in corrupted/crafted manifests.
27
+ - **`EncryptionSchema` empty recipients** — `recipients` array now enforces `min(1)` to reject undecryptable envelope manifests.
28
+ - **`parseRecipient` empty keyfile** — CLI now rejects `--recipient alice:` (missing keyfile path) with a clear error.
29
+ - **CLI 30s hang in Docker** — `process.exit()` with I/O flushing prevents `setTimeout` leak in containerized runtimes.
30
+ - **Deno Dockerfile** — multi-stage Node 22 copy replaces `apt install nodejs`, improving layer caching and image size.
31
+ - **Runtime-neutral Docker hint** in integration tests; `afterAll` guards `rmSync` against partial `beforeAll` failures.
32
+
8
33
  ## [5.0.0] — Hydra (2026-02-28)
9
34
 
10
35
  ### Breaking Changes
package/bin/actions.js CHANGED
@@ -8,6 +8,11 @@ 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',
11
16
  };
12
17
 
13
18
  /**
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.0.0')
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
 
@@ -419,4 +442,92 @@ vault
419
442
  await launchDashboard(cas);
420
443
  }, getJson));
421
444
 
422
- await program.parseAsync();
445
+ // ---------------------------------------------------------------------------
446
+ // recipient add / remove / list
447
+ // ---------------------------------------------------------------------------
448
+ const recipient = program
449
+ .command('recipient')
450
+ .description('Manage envelope encryption recipients');
451
+
452
+ recipient
453
+ .command('add <slug>')
454
+ .description('Add a recipient to an envelope-encrypted asset')
455
+ .requiredOption('--label <label>', 'Label for the new recipient')
456
+ .requiredOption('--key-file <path>', 'Path to 32-byte key file for the new recipient')
457
+ .requiredOption('--existing-key-file <path>', 'Path to key file of an existing recipient')
458
+ .option('--cwd <dir>', 'Git working directory', '.')
459
+ .action(runAction(async (slug, opts) => {
460
+ const cas = createCas(opts.cwd);
461
+ const treeOid = await cas.resolveVaultEntry({ slug });
462
+ const manifest = await cas.readManifest({ treeOid });
463
+
464
+ const existingKey = readKeyFile(opts.existingKeyFile);
465
+ const newRecipientKey = readKeyFile(opts.keyFile);
466
+
467
+ const updated = await cas.addRecipient({
468
+ manifest,
469
+ existingKey,
470
+ newRecipientKey,
471
+ label: opts.label,
472
+ });
473
+
474
+ const newTreeOid = await cas.createTree({ manifest: updated });
475
+ await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
476
+
477
+ const json = program.opts().json;
478
+ if (json) {
479
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
480
+ } else {
481
+ process.stdout.write(`${newTreeOid}\n`);
482
+ }
483
+ }, getJson));
484
+
485
+ recipient
486
+ .command('remove <slug>')
487
+ .description('Remove a recipient from an envelope-encrypted asset')
488
+ .requiredOption('--label <label>', 'Label of the recipient to remove')
489
+ .option('--cwd <dir>', 'Git working directory', '.')
490
+ .action(runAction(async (slug, opts) => {
491
+ const cas = createCas(opts.cwd);
492
+ const treeOid = await cas.resolveVaultEntry({ slug });
493
+ const manifest = await cas.readManifest({ treeOid });
494
+
495
+ const updated = await cas.removeRecipient({ manifest, label: opts.label });
496
+
497
+ const newTreeOid = await cas.createTree({ manifest: updated });
498
+ await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
499
+
500
+ const json = program.opts().json;
501
+ if (json) {
502
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
503
+ } else {
504
+ process.stdout.write(`${newTreeOid}\n`);
505
+ }
506
+ }, getJson));
507
+
508
+ recipient
509
+ .command('list <slug>')
510
+ .description('List recipients of an envelope-encrypted asset')
511
+ .option('--cwd <dir>', 'Git working directory', '.')
512
+ .action(runAction(async (slug, opts) => {
513
+ const cas = createCas(opts.cwd);
514
+ const treeOid = await cas.resolveVaultEntry({ slug });
515
+ const manifest = await cas.readManifest({ treeOid });
516
+
517
+ const labels = await cas.listRecipients(manifest);
518
+ const json = program.opts().json;
519
+ if (json) {
520
+ process.stdout.write(`${JSON.stringify(labels)}\n`);
521
+ } else {
522
+ for (const label of labels) {
523
+ process.stdout.write(`${label}\n`);
524
+ }
525
+ }
526
+ }, getJson));
527
+
528
+ await program.parseAsync();
529
+
530
+ // Flush stdout/stderr before exiting — spawned git child processes leave
531
+ // libuv handles that prevent natural exit in containerized environments.
532
+ const code = process.exitCode || 0;
533
+ 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,20 @@ 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
+
352
368
  // Vault — delegates to VaultService
353
369
 
354
370
  static VAULT_REF: string;
package/index.js CHANGED
@@ -265,9 +265,10 @@ export default class ContentAddressableStore {
265
265
  * @param {string} [options.passphrase] - Derive encryption key from passphrase.
266
266
  * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
267
267
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
268
+ * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
268
269
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
269
270
  */
270
- async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
271
+ async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
271
272
  const source = createReadStream(filePath);
272
273
  const service = await this.#getService();
273
274
  return await service.store({
@@ -278,6 +279,7 @@ export default class ContentAddressableStore {
278
279
  passphrase,
279
280
  kdfOptions,
280
281
  compression,
282
+ recipients,
281
283
  });
282
284
  }
283
285
 
@@ -291,6 +293,7 @@ export default class ContentAddressableStore {
291
293
  * @param {string} [options.passphrase] - Derive encryption key from passphrase.
292
294
  * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
293
295
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
296
+ * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
294
297
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
295
298
  */
296
299
  async store(options) {
@@ -421,6 +424,46 @@ export default class ContentAddressableStore {
421
424
  return await service.deriveKey(options);
422
425
  }
423
426
 
427
+ // ---------------------------------------------------------------------------
428
+ // Recipient management — delegates to CasService
429
+ // ---------------------------------------------------------------------------
430
+
431
+ /**
432
+ * Adds a recipient to an envelope-encrypted manifest.
433
+ * @param {Object} options
434
+ * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest
435
+ * @param {Buffer} options.existingKey - KEK of an existing recipient.
436
+ * @param {Buffer} options.newRecipientKey - KEK for the new recipient.
437
+ * @param {string} options.label - Label for the new recipient.
438
+ * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>}
439
+ */
440
+ async addRecipient(options) {
441
+ const service = await this.#getService();
442
+ return await service.addRecipient(options);
443
+ }
444
+
445
+ /**
446
+ * Removes a recipient from an envelope-encrypted manifest.
447
+ * @param {Object} options
448
+ * @param {import('./src/domain/value-objects/Manifest.js').default} options.manifest
449
+ * @param {string} options.label - Label to remove.
450
+ * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>}
451
+ */
452
+ async removeRecipient(options) {
453
+ const service = await this.#getService();
454
+ return await service.removeRecipient(options);
455
+ }
456
+
457
+ /**
458
+ * Lists recipient labels from an envelope-encrypted manifest.
459
+ * @param {import('./src/domain/value-objects/Manifest.js').default} manifest
460
+ * @returns {Promise<string[]>}
461
+ */
462
+ async listRecipients(manifest) {
463
+ const service = await this.#getService();
464
+ return service.listRecipients(manifest);
465
+ }
466
+
424
467
  // ---------------------------------------------------------------------------
425
468
  // Vault — delegates to VaultService
426
469
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "5.0.0",
3
+ "version": "5.1.0",
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",
@@ -24,6 +24,15 @@ export declare const KdfSchema: z.ZodObject<{
24
24
  keyLength: z.ZodDefault<z.ZodNumber>;
25
25
  }>;
26
26
 
27
+ /** Validates a single recipient entry in an envelope-encrypted manifest. */
28
+ export declare const RecipientSchema: z.ZodObject<{
29
+ label: z.ZodString;
30
+ wrappedDek: z.ZodString;
31
+ nonce: z.ZodString;
32
+ tag: z.ZodString;
33
+ kekType: z.ZodOptional<z.ZodString>;
34
+ }>;
35
+
27
36
  /** Validates the encryption metadata attached to an encrypted manifest. */
28
37
  export declare const EncryptionSchema: z.ZodObject<{
29
38
  algorithm: z.ZodString;
@@ -31,6 +40,7 @@ export declare const EncryptionSchema: z.ZodObject<{
31
40
  tag: z.ZodString;
32
41
  encrypted: z.ZodDefault<z.ZodBoolean>;
33
42
  kdf: z.ZodOptional<typeof KdfSchema>;
43
+ recipients: z.ZodOptional<z.ZodArray<typeof RecipientSchema>>;
34
44
  }>;
35
45
 
36
46
  /** Validates compression metadata. */
@@ -24,6 +24,15 @@ export const KdfSchema = z.object({
24
24
  keyLength: z.number().int().positive().default(32),
25
25
  });
26
26
 
27
+ /** Validates a single recipient entry in an envelope-encrypted manifest. */
28
+ export const RecipientSchema = z.object({
29
+ label: z.string().min(1),
30
+ wrappedDek: z.string().min(1),
31
+ nonce: z.string().min(1),
32
+ tag: z.string().min(1),
33
+ kekType: z.string().optional(),
34
+ });
35
+
27
36
  /** Validates the encryption metadata attached to an encrypted manifest. */
28
37
  export const EncryptionSchema = z.object({
29
38
  algorithm: z.string(),
@@ -31,6 +40,7 @@ export const EncryptionSchema = z.object({
31
40
  tag: z.string(),
32
41
  encrypted: z.boolean().default(true),
33
42
  kdf: KdfSchema.optional(),
43
+ recipients: z.array(RecipientSchema).min(1).optional(),
34
44
  });
35
45
 
36
46
  /** Validates compression metadata. */
@@ -112,6 +112,7 @@ export default class CasService {
112
112
  passphrase?: string;
113
113
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
114
114
  compression?: { algorithm: "gzip" };
115
+ recipients?: Array<{ label: string; key: Buffer }>;
115
116
  }): Promise<Manifest>;
116
117
 
117
118
  createTree(options: { manifest: Manifest }): Promise<string>;
@@ -138,6 +139,20 @@ export default class CasService {
138
139
  treeOids: string[];
139
140
  }): Promise<{ referenced: Set<string>; total: number }>;
140
141
 
142
+ addRecipient(options: {
143
+ manifest: Manifest;
144
+ existingKey: Buffer;
145
+ newRecipientKey: Buffer;
146
+ label: string;
147
+ }): Promise<Manifest>;
148
+
149
+ removeRecipient(options: {
150
+ manifest: Manifest;
151
+ label: string;
152
+ }): Promise<Manifest>;
153
+
154
+ listRecipients(manifest: Manifest): string[];
155
+
141
156
  verifyIntegrity(manifest: Manifest): Promise<boolean>;
142
157
 
143
158
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
@@ -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
- }
263
-
264
- if (encryptionKey) {
265
- this.crypto._validateKey(encryptionKey);
266
- }
267
-
268
- const manifestData = { slug, filename, size: 0, chunks: [] };
371
+ const keyInfo = recipients
372
+ ? await this._resolveRecipientsForStore(recipients)
373
+ : await this._resolveKeyForStore(encryptionKey, passphrase, kdfOptions);
269
374
 
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,124 @@ 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
+
746
979
  /**
747
980
  * Verifies the integrity of a stored file by re-hashing its chunks.
748
981
  * @param {import('../value-objects/Manifest.js').default} manifest
@@ -11,6 +11,15 @@ 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
+ }
22
+
14
23
  /** AES-256-GCM encryption metadata attached to an encrypted manifest. */
15
24
  export interface EncryptionMeta {
16
25
  algorithm: string;
@@ -18,6 +27,7 @@ export interface EncryptionMeta {
18
27
  tag: string;
19
28
  encrypted: boolean;
20
29
  kdf?: KdfParams;
30
+ recipients?: RecipientEntry[];
21
31
  }
22
32
 
23
33
  /** 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 } }