@git-stunts/git-cas 4.0.1 → 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,53 @@ 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
+
33
+ ## [5.0.0] — Hydra (2026-02-28)
34
+
35
+ ### Breaking Changes
36
+ - **`CasService` constructor accepts `chunker` port** — a new optional `ChunkingPort` parameter controls chunking strategy. Existing code that does not pass `chunker` is unaffected (defaults to `FixedChunker`).
37
+ - **Major version bump** — new hexagonal port (`ChunkingPort`) and manifest schema extension warrant a semver-major release for downstream tooling awareness.
38
+
39
+ ### Added
40
+ - **Content-defined chunking (CDC)** — Buzhash rolling-hash engine with configurable `minChunkSize` (64 KiB), `maxChunkSize` (1 MiB), and `targetChunkSize` (256 KiB). CDC limits the dedup blast radius to 1–2 chunks on incremental edits vs. total invalidation with fixed-size chunking. Benchmarked at 265 MB/s and 98.4% chunk reuse on small edits.
41
+ - **`ChunkingPort`** — new hexagonal port (`src/ports/ChunkingPort.js`) with `async *chunk(source)`, `strategy`, and `params`. Abstracts chunking behind a pluggable interface.
42
+ - **`FixedChunker`** — adapter wrapping existing fixed-size buffer slicing behind `ChunkingPort`.
43
+ - **`CdcChunker`** — adapter wrapping the buzhash CDC engine behind `ChunkingPort`.
44
+ - **`chunking` manifest field** — optional `{ strategy: 'fixed' | 'cdc', params: {...} }` metadata in manifests. Fixed-strategy manifests omit the field for full backward compatibility.
45
+ - **`ChunkingSchema`** — Zod discriminated union (`FixedChunkingSchema` + `CdcChunkingSchema`) for manifest validation.
46
+ - **`INVALID_CHUNKING_STRATEGY` error code** — thrown when an unrecognized chunking strategy is encountered in a manifest.
47
+ - **Facade `chunking` config** — `ContentAddressableStore` constructor accepts `chunking: { strategy, ... }` declarative config or a raw `chunker` port instance.
48
+ - **CDC benchmarks** (`test/benchmark/chunking.bench.js`) — throughput and dedup efficiency comparison.
49
+ - 90 new unit tests (709 total).
50
+
51
+ ### Changed
52
+ - `CasService._chunkAndStore()` refactored to delegate to `ChunkingPort` instead of inline buffer slicing.
53
+ - `ChunkingPort`, `FixedChunker`, `CdcChunker` exported from the main entry point.
54
+
8
55
  ## [4.0.1] — M8 Spit Shine + M9 Cockpit (2026-02-28)
9
56
 
10
57
  ### Added
package/README.md CHANGED
@@ -44,6 +44,21 @@ We use the object database.
44
44
 
45
45
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
46
46
 
47
+ ## What's new in v5.0.0
48
+
49
+ **Content-defined chunking (CDC)** — Fixed-size chunking invalidates every chunk after an edit. CDC uses a buzhash rolling hash to find natural boundaries, limiting the blast radius to 1–2 chunks. Benchmarked at 98.4% chunk reuse on small edits vs 32% for fixed.
50
+
51
+ ```js
52
+ const cas = new ContentAddressableStore({
53
+ plumbing,
54
+ chunking: { strategy: 'cdc', targetChunkSize: 262144, minChunkSize: 65536, maxChunkSize: 1048576 },
55
+ });
56
+ ```
57
+
58
+ **`ChunkingPort`** — new hexagonal port abstracts chunking strategy. `FixedChunker` and `CdcChunker` adapters ship out of the box. Bring your own chunker by extending `ChunkingPort`.
59
+
60
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
61
+
47
62
  ## What's new in v4.0.1
48
63
 
49
64
  **`git cas verify`** — verify stored asset integrity from the CLI without restoring (`git cas verify --slug my-asset`).
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)));
@@ -32,12 +32,12 @@ function formatBytes(bytes) {
32
32
  * @param {boolean} [options.quiet] - Suppress all progress output.
33
33
  * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
34
34
  */
35
- export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize }) {
35
+ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: providedSize, ctx: providedCtx }) {
36
36
  if (quiet) {
37
37
  return { attach() {}, detach() {} };
38
38
  }
39
39
 
40
- const ctx = getCliContext();
40
+ const ctx = providedCtx || getCliContext();
41
41
  if (ctx.mode === 'pipe') {
42
42
  return { attach() {}, detach() {} };
43
43
  }
@@ -60,12 +60,12 @@ export function createStoreProgress({ filePath, chunkSize, quiet, fileSize: prov
60
60
  * @param {boolean} [options.quiet] - Suppress all progress output.
61
61
  * @returns {{ attach(observer: { on(event: string, fn: Function): void, removeListener(event: string, fn: Function): void }): void, detach(): void }}
62
62
  */
63
- export function createRestoreProgress({ totalChunks, quiet }) {
63
+ export function createRestoreProgress({ totalChunks, quiet, ctx: providedCtx }) {
64
64
  if (quiet || totalChunks === 0) {
65
65
  return { attach() {}, detach() {} };
66
66
  }
67
67
 
68
- const ctx = getCliContext();
68
+ const ctx = providedCtx || getCliContext();
69
69
  if (ctx.mode === 'pipe') {
70
70
  return { attach() {}, detach() {} };
71
71
  }
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,32 @@ 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
+
23
+ /** Abstract port for splitting a byte stream into chunks. */
24
+ export declare class ChunkingPort {
25
+ get strategy(): string;
26
+ get params(): Record<string, unknown>;
27
+ chunk(source: AsyncIterable<Buffer>): AsyncIterable<Buffer>;
28
+ }
29
+
30
+ /** Fixed-size chunking adapter. */
31
+ export declare class FixedChunker extends ChunkingPort {
32
+ constructor(options?: { chunkSize?: number });
33
+ get strategy(): "fixed";
34
+ get params(): { chunkSize: number };
35
+ }
36
+
37
+ /** Content-defined chunking adapter using buzhash rolling hash. */
38
+ export declare class CdcChunker extends ChunkingPort {
39
+ constructor(options?: {
40
+ minChunkSize?: number;
41
+ maxChunkSize?: number;
42
+ targetChunkSize?: number;
43
+ });
44
+ get strategy(): "cdc";
45
+ get params(): { target: number; min: number; max: number };
46
+ }
22
47
 
23
48
  /** Abstract port for cryptographic operations. */
24
49
  export declare class CryptoPortBase {
@@ -125,6 +150,15 @@ export declare class StatsCollector {
125
150
  };
126
151
  }
127
152
 
153
+ /** Declarative chunking strategy configuration. */
154
+ export interface ChunkingConfig {
155
+ strategy: "fixed" | "cdc";
156
+ chunkSize?: number;
157
+ targetChunkSize?: number;
158
+ minChunkSize?: number;
159
+ maxChunkSize?: number;
160
+ }
161
+
128
162
  /** Constructor options for {@link ContentAddressableStore}. */
129
163
  export interface ContentAddressableStoreOptions {
130
164
  plumbing: unknown;
@@ -135,6 +169,8 @@ export interface ContentAddressableStoreOptions {
135
169
  policy?: unknown;
136
170
  merkleThreshold?: number;
137
171
  concurrency?: number;
172
+ chunking?: ChunkingConfig;
173
+ chunker?: ChunkingPort;
138
174
  }
139
175
 
140
176
  /** A single vault entry. */
@@ -266,6 +302,7 @@ export default class ContentAddressableStore {
266
302
  passphrase?: string;
267
303
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
268
304
  compression?: { algorithm: "gzip" };
305
+ recipients?: Array<{ label: string; key: Buffer }>;
269
306
  }): Promise<Manifest>;
270
307
 
271
308
  store(options: {
@@ -276,6 +313,7 @@ export default class ContentAddressableStore {
276
313
  passphrase?: string;
277
314
  kdfOptions?: Omit<DeriveKeyOptions, "passphrase">;
278
315
  compression?: { algorithm: "gzip" };
316
+ recipients?: Array<{ label: string; key: Buffer }>;
279
317
  }): Promise<Manifest>;
280
318
 
281
319
  restoreFile(options: {
@@ -313,6 +351,20 @@ export default class ContentAddressableStore {
313
351
 
314
352
  deriveKey(options: DeriveKeyOptions): Promise<DeriveKeyResult>;
315
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
+
316
368
  // Vault — delegates to VaultService
317
369
 
318
370
  static VAULT_REF: string;
package/index.js CHANGED
@@ -15,12 +15,15 @@ import NodeCryptoAdapter from './src/infrastructure/adapters/NodeCryptoAdapter.j
15
15
  import Manifest from './src/domain/value-objects/Manifest.js';
16
16
  import Chunk from './src/domain/value-objects/Chunk.js';
17
17
  import CryptoPort from './src/ports/CryptoPort.js';
18
+ import ChunkingPort from './src/ports/ChunkingPort.js';
18
19
  import ObservabilityPort from './src/ports/ObservabilityPort.js';
19
20
  import JsonCodec from './src/infrastructure/codecs/JsonCodec.js';
20
21
  import CborCodec from './src/infrastructure/codecs/CborCodec.js';
21
22
  import SilentObserver from './src/infrastructure/adapters/SilentObserver.js';
22
23
  import EventEmitterObserver from './src/infrastructure/adapters/EventEmitterObserver.js';
23
24
  import StatsCollector from './src/infrastructure/adapters/StatsCollector.js';
25
+ import FixedChunker from './src/infrastructure/chunkers/FixedChunker.js';
26
+ import CdcChunker from './src/infrastructure/chunkers/CdcChunker.js';
24
27
 
25
28
  export {
26
29
  CasService,
@@ -29,6 +32,7 @@ export {
29
32
  GitRefAdapter,
30
33
  NodeCryptoAdapter,
31
34
  CryptoPort,
35
+ ChunkingPort,
32
36
  ObservabilityPort,
33
37
  Manifest,
34
38
  Chunk,
@@ -37,6 +41,8 @@ export {
37
41
  SilentObserver,
38
42
  EventEmitterObserver,
39
43
  StatsCollector,
44
+ FixedChunker,
45
+ CdcChunker,
40
46
  };
41
47
 
42
48
  /**
@@ -72,8 +78,10 @@ export default class ContentAddressableStore {
72
78
  * @param {import('@git-stunts/alfred').Policy} [options.policy] - Resilience policy for Git I/O.
73
79
  * @param {number} [options.merkleThreshold=1000] - Chunk count threshold for Merkle manifests.
74
80
  * @param {number} [options.concurrency=1] - Maximum parallel chunk I/O operations.
81
+ * @param {{ strategy: string, chunkSize?: number, targetChunkSize?: number, minChunkSize?: number, maxChunkSize?: number }} [options.chunking] - Chunking strategy config.
82
+ * @param {import('./src/ports/ChunkingPort.js').default} [options.chunker] - Pre-built ChunkingPort instance (advanced).
75
83
  */
76
- constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency }) {
84
+ constructor({ plumbing, chunkSize, codec, policy, crypto, observability, merkleThreshold, concurrency, chunking, chunker }) {
77
85
  this.plumbing = plumbing;
78
86
  this.chunkSizeConfig = chunkSize;
79
87
  this.codecConfig = codec;
@@ -82,6 +90,8 @@ export default class ContentAddressableStore {
82
90
  this.observabilityConfig = observability;
83
91
  this.merkleThresholdConfig = merkleThreshold;
84
92
  this.concurrencyConfig = concurrency;
93
+ this.chunkingConfig = chunking;
94
+ this.chunkerConfig = chunker;
85
95
  this.service = null;
86
96
  this.#servicePromise = null;
87
97
  }
@@ -102,6 +112,34 @@ export default class ContentAddressableStore {
102
112
  return await this.#servicePromise;
103
113
  }
104
114
 
115
+ /**
116
+ * Resolves the chunker from config options.
117
+ * @private
118
+ * @returns {import('./src/ports/ChunkingPort.js').default|undefined}
119
+ */
120
+ #resolveChunker() {
121
+ // Direct ChunkingPort instance takes precedence
122
+ if (this.chunkerConfig) {
123
+ return this.chunkerConfig;
124
+ }
125
+ // Build from declarative chunking config
126
+ if (this.chunkingConfig) {
127
+ if (this.chunkingConfig.strategy === 'cdc') {
128
+ return new CdcChunker({
129
+ targetChunkSize: this.chunkingConfig.targetChunkSize,
130
+ minChunkSize: this.chunkingConfig.minChunkSize,
131
+ maxChunkSize: this.chunkingConfig.maxChunkSize,
132
+ });
133
+ }
134
+ // 'fixed' or unrecognized — fall through to default (FixedChunker via CasService)
135
+ if (this.chunkingConfig.strategy === 'fixed' && this.chunkingConfig.chunkSize) {
136
+ return new FixedChunker({ chunkSize: this.chunkingConfig.chunkSize });
137
+ }
138
+ }
139
+ // undefined → CasService will default to FixedChunker
140
+ return undefined;
141
+ }
142
+
105
143
  /**
106
144
  * Constructs adapters, resolves crypto, and creates CasService + VaultService.
107
145
  * @private
@@ -113,6 +151,7 @@ export default class ContentAddressableStore {
113
151
  policy: this.policyConfig
114
152
  });
115
153
  const crypto = this.cryptoConfig || await getDefaultCryptoAdapter();
154
+ const chunker = this.#resolveChunker();
116
155
  this.service = new CasService({
117
156
  persistence,
118
157
  chunkSize: this.chunkSizeConfig,
@@ -121,6 +160,7 @@ export default class ContentAddressableStore {
121
160
  observability: this.observabilityConfig || new SilentObserver(),
122
161
  merkleThreshold: this.merkleThresholdConfig,
123
162
  concurrency: this.concurrencyConfig,
163
+ chunker,
124
164
  });
125
165
 
126
166
  const ref = new GitRefAdapter({
@@ -225,9 +265,10 @@ export default class ContentAddressableStore {
225
265
  * @param {string} [options.passphrase] - Derive encryption key from passphrase.
226
266
  * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
227
267
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
268
+ * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
228
269
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
229
270
  */
230
- async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression }) {
271
+ async storeFile({ filePath, slug, filename, encryptionKey, passphrase, kdfOptions, compression, recipients }) {
231
272
  const source = createReadStream(filePath);
232
273
  const service = await this.#getService();
233
274
  return await service.store({
@@ -238,6 +279,7 @@ export default class ContentAddressableStore {
238
279
  passphrase,
239
280
  kdfOptions,
240
281
  compression,
282
+ recipients,
241
283
  });
242
284
  }
243
285
 
@@ -251,6 +293,7 @@ export default class ContentAddressableStore {
251
293
  * @param {string} [options.passphrase] - Derive encryption key from passphrase.
252
294
  * @param {Object} [options.kdfOptions] - KDF options when using passphrase.
253
295
  * @param {{ algorithm: 'gzip' }} [options.compression] - Enable compression.
296
+ * @param {Array<{label: string, key: Buffer}>} [options.recipients] - Envelope recipients (mutually exclusive with encryptionKey/passphrase).
254
297
  * @returns {Promise<import('./src/domain/value-objects/Manifest.js').default>} The resulting manifest.
255
298
  */
256
299
  async store(options) {
@@ -381,6 +424,46 @@ export default class ContentAddressableStore {
381
424
  return await service.deriveKey(options);
382
425
  }
383
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
+
384
467
  // ---------------------------------------------------------------------------
385
468
  // Vault — delegates to VaultService
386
469
  // ---------------------------------------------------------------------------
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@git-stunts/git-cas",
3
- "version": "4.0.1",
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. */
@@ -38,6 +48,30 @@ export declare const CompressionSchema: z.ZodObject<{
38
48
  algorithm: z.ZodEnum<["gzip"]>;
39
49
  }>;
40
50
 
51
+ /** Validates fixed-size chunking parameters. */
52
+ export declare const FixedChunkingSchema: z.ZodObject<{
53
+ strategy: z.ZodLiteral<"fixed">;
54
+ params: z.ZodObject<{
55
+ chunkSize: z.ZodNumber;
56
+ }>;
57
+ }>;
58
+
59
+ /** Validates content-defined chunking (CDC) parameters. */
60
+ export declare const CdcChunkingSchema: z.ZodObject<{
61
+ strategy: z.ZodLiteral<"cdc">;
62
+ params: z.ZodObject<{
63
+ target: z.ZodNumber;
64
+ min: z.ZodNumber;
65
+ max: z.ZodNumber;
66
+ }>;
67
+ }>;
68
+
69
+ /** Validates chunking metadata (fixed or CDC). */
70
+ export declare const ChunkingSchema: z.ZodDiscriminatedUnion<
71
+ "strategy",
72
+ [typeof FixedChunkingSchema, typeof CdcChunkingSchema]
73
+ >;
74
+
41
75
  /** Validates a sub-manifest reference in a v2 Merkle manifest. */
42
76
  export declare const SubManifestRefSchema: z.ZodObject<{
43
77
  oid: z.ZodString;
@@ -54,5 +88,6 @@ export declare const ManifestSchema: z.ZodObject<{
54
88
  chunks: z.ZodArray<typeof ChunkSchema>;
55
89
  encryption: z.ZodOptional<typeof EncryptionSchema>;
56
90
  compression: z.ZodOptional<typeof CompressionSchema>;
91
+ chunking: z.ZodOptional<typeof ChunkingSchema>;
57
92
  subManifests: z.ZodOptional<z.ZodArray<typeof SubManifestRefSchema>>;
58
93
  }>;