@git-stunts/git-cas 5.2.1 → 5.3.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +67 -5
  3. package/bin/actions.js +38 -8
  4. package/bin/config.js +203 -0
  5. package/bin/git-cas.js +200 -54
  6. package/bin/ui/context.js +13 -0
  7. package/bin/ui/dashboard-cmds.js +14 -6
  8. package/bin/ui/dashboard-view.js +55 -6
  9. package/bin/ui/dashboard.js +109 -7
  10. package/bin/ui/encryption-card.js +2 -2
  11. package/bin/ui/heatmap.js +20 -2
  12. package/bin/ui/history-timeline.js +8 -6
  13. package/bin/ui/manifest-view.js +37 -8
  14. package/bin/ui/passphrase-prompt.js +100 -0
  15. package/bin/ui/progress.js +60 -38
  16. package/index.d.ts +20 -1
  17. package/index.js +74 -218
  18. package/package.json +2 -1
  19. package/src/domain/errors/CasError.js +3 -1
  20. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  21. package/src/domain/services/CasService.d.ts +21 -1
  22. package/src/domain/services/CasService.js +134 -228
  23. package/src/domain/services/KeyResolver.js +220 -0
  24. package/src/domain/services/Semaphore.js +2 -2
  25. package/src/domain/services/VaultService.js +72 -29
  26. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  27. package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
  28. package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
  29. package/src/infrastructure/adapters/FileIOHelper.js +64 -0
  30. package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
  31. package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
  32. package/src/infrastructure/adapters/NodeCryptoAdapter.js +49 -8
  33. package/src/infrastructure/adapters/SilentObserver.js +15 -0
  34. package/src/infrastructure/adapters/StatsCollector.js +15 -1
  35. package/src/infrastructure/adapters/WebCryptoAdapter.js +120 -42
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/CdcChunker.js +5 -0
  38. package/src/infrastructure/chunkers/FixedChunker.js +28 -8
  39. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  40. package/src/infrastructure/codecs/CborCodec.js +11 -3
  41. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  42. package/src/ports/CodecPort.js +3 -3
  43. package/src/ports/CryptoPort.js +56 -23
  44. package/src/ports/GitPersistencePort.js +4 -4
  45. package/src/ports/GitRefPort.js +10 -10
  46. package/src/types/ambient.d.ts +37 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,106 @@ 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.3.0] — 2026-03-08
9
+
10
+ ### Added
11
+ - **Vault rotate passphrase-file support** — `vault rotate` now accepts `--old-passphrase-file` and `--new-passphrase-file` flags, bringing it to parity with the store/restore passphrase-file support.
12
+ - **CLI store flags** — `--gzip`, `--strategy <fixed|cdc>`, `--chunk-size <n>`, `--concurrency <n>`, `--codec <json|cbor>`, `--merkle-threshold <n>`, `--target-chunk-size <n>`, `--min-chunk-size <n>`, `--max-chunk-size <n>`. All library-level chunking, compression, codec, and concurrency options are now accessible from the CLI.
13
+ - **CLI restore flags** — `--concurrency <n>`, `--max-restore-buffer <n>`. Parallel I/O and restore buffer limit now configurable from CLI.
14
+ - **`.casrc` config file** — JSON config file at the repository root provides default values for CLI flags. CLI flags always take precedence. Supports: `chunkSize`, `strategy`, `concurrency`, `codec`, `compression`, `merkleThreshold`, `maxRestoreBufferSize`, and `cdc.*` sub-keys.
15
+ - **CODE-EVAL.md** — Forensic architectural audit (zero-knowledge code extraction, critical assessment, roadmap reconciliation, prescriptive blueprint).
16
+ - **M16 Capstone** — New milestone in ROADMAP.md addressing all 9 audit flaws and 10 concerns (C1–C10). 13 task cards, ~698 LoC, ~21h estimated.
17
+ - **Concerns C8–C10** — Three architectural concerns from the CODE-EVAL.md audit now documented: crypto adapter LSP violation (C8), FixedChunker quadratic allocation (C9), encrypt-then-chunk dedup loss (C10).
18
+ - **CasError codes** — `RESTORE_TOO_LARGE` and `ENCRYPTION_BUFFER_EXCEEDED` registered in canonical error code table.
19
+ - **16.2 — Memory restore guard** — `CasService` accepts `maxRestoreBufferSize` (default 512 MiB). `_restoreBuffered` throws `RESTORE_TOO_LARGE` with `{ size, limit }` meta when encrypted/compressed restore would exceed the limit. Unencrypted streaming restore is unaffected.
20
+ - **16.3 — Web Crypto encryption buffer guard** — `WebCryptoAdapter` accepts `maxEncryptionBufferSize` (default 512 MiB). Throws `ENCRYPTION_BUFFER_EXCEEDED` when streaming encryption exceeds the limit, since Web Crypto AES-GCM is a one-shot API. NodeCryptoAdapter uses true streaming and is unaffected.
21
+ - **16.5 — Encrypt-then-chunk dedup warning** — `CasService.store()` now logs a warning when encryption is combined with CDC chunking, since ciphertext is pseudorandom and content-defined boundaries provide no dedup benefit.
22
+ - **16.10 — Orphaned blob tracking** — `STREAM_ERROR` now includes `meta.orphanedBlobs` — an array of OIDs for blobs successfully written before the stream failure. Error metric includes `orphanedBlobs` count for observability.
23
+ - **16.11 — Passphrase input security** — New `--vault-passphrase-file <path>` CLI option reads passphrase from file (use `-` for stdin). Interactive TTY prompt added as fallback when no other passphrase source is available. `resolvePassphrase` is now async with priority: file → flag → env → TTY → undefined. Empty passphrases rejected. File permission warning on group/world-readable files.
24
+ - **16.12 — KDF brute-force awareness** — `CasService` now emits `decryption_failed` metric with slug context when decryption fails with `INTEGRITY_ERROR` during encrypted restore. CLI adds a 1-second delay after `INTEGRITY_ERROR` to slow brute-force attempts. Library API imposes no delay — callers manage their own rate-limiting policy.
25
+ - **16.13 — GCM nonce collision docs + encryption counter** — `SECURITY.md` moved to project root with new sections: GCM nonce bound (2^32 NIST limit), key rotation frequency, KDF parameter guidance, and passphrase entropy recommendations. Vault metadata now tracks `encryptionCount`, incremented per encrypted `addToVault()`. Observability warning emitted when count exceeds 2^31. `VaultService` accepts optional `observability` port.
26
+ - **16.7 — Lifecycle method naming** — Added `inspectAsset()` (replaces `deleteAsset()`) and `collectReferencedChunks()` (replaces `findOrphanedChunks()`) as canonical names on both `CasService` and the facade. Old names are preserved as deprecated aliases that emit observability warnings. Type definitions updated with `@deprecated` JSDoc.
27
+
28
+ ### Changed
29
+ - **`runAction` injectable delay** — `runAction()` now accepts an optional `{ delay }` dependency, replacing the hardcoded `setTimeout` call. Tests inject a spy instead of using `vi.useFakeTimers()`, making INTEGRITY_ERROR rate-limit tests deterministic across Node, Bun, and Deno.
30
+ - **Test conventions** — Added `test/CONVENTIONS.md` documenting rules for deterministic, cross-runtime tests: inject time dependencies, use `chmod()` instead of `writeFile({ mode })`, avoid global state patching.
31
+ - **VaultService test observability wiring** — `VaultService.test.js` now passes a `mockObservability()` port to all tests instead of relying on the silent no-op default. `rotateVaultPassphrase.test.js` now passes `SilentObserver` explicitly. If observability wiring breaks, the test suite will catch it.
32
+ - **`NodeCryptoAdapter.encryptBuffer` JSDoc** — `@returns` annotation corrected to `Promise<...>`, matching the async implementation.
33
+ - **`maxRestoreBufferSize` documented** — constructor JSDoc and `#config` type in `ContentAddressableStore` now include the parameter.
34
+ - **ROADMAP.md heading level** — added `## Task Cards` heading between `# M16` and `### 16.1` to satisfy MD001 heading-increment rule.
35
+ - **16.1 — Crypto adapter behavioral normalization** — `NodeCryptoAdapter.encryptBuffer` now returns a Promise (was sync), matching Bun/Web. `decryptBuffer` validates key on all adapters. `NodeCryptoAdapter.createEncryptionStream` guards `finalize()` with `STREAM_NOT_CONSUMED`. New conformance test suite asserts identical contracts across all adapters.
36
+ - **16.4 — FixedChunker pre-allocated buffer** — Replaced `Buffer.concat()` loop with a pre-allocated `Buffer.allocUnsafe(chunkSize)` working buffer, eliminating O(n²) copies for many small input buffers. Matches the allocation strategy used by `CdcChunker`.
37
+
38
+ ### Fixed
39
+ - **Post-decompression size guard** — `_restoreBuffered` now enforces `maxRestoreBufferSize` after decompression, not just before. Compressed payloads that inflate beyond the configured limit now throw `RESTORE_TOO_LARGE` instead of silently allocating unbounded memory.
40
+ - **CLI passphrase prompt deferral** — `resolveEncryptionKey` now checks vault metadata before calling `resolvePassphrase`, avoiding unnecessary TTY prompts for unencrypted vaults. Store action recipient-conflict check inspects flags/env without consuming stdin.
41
+ - **CRLF passphrase normalization** — `readPassphraseFile` now strips trailing `\r\n` (Windows line endings) in addition to `\n`, preventing passphrase mismatches from Windows-edited files.
42
+ - **Constructor validation** — `CasService.maxRestoreBufferSize` (integer >= 1024), `CasService.chunkSize` (integer >= 1024), `WebCryptoAdapter.maxEncryptionBufferSize` (finite, positive), and `FixedChunker.chunkSize` (positive integer) are now validated at construction time, preventing silent misconfiguration.
43
+ - **Error-path test hardening** — `orphanedBlobs`, `restoreGuard`, `kdfBruteForce`, and `conformance` tests now fail explicitly when expected errors are not thrown (previously silent pass-through).
44
+ - **Orphaned blob enrichment on CasError re-throw** — `_chunkAndStore` now attaches `orphanedBlobs` metadata to existing `CasError` instances before re-throwing, instead of discarding the information.
45
+ - **VaultService metadata mutation on retry** — `addToVault` now shallow-copies `state.metadata` before mutation, preventing `encryptionCount` from being incremented multiple times across CAS retries.
46
+ - **16.8 — CasError portability guard** — `Error.captureStackTrace` now guarded with a runtime check. CasError constructs correctly on runtimes where `captureStackTrace` is unavailable (e.g. Firefox, older Deno).
47
+ - **16.9 — Pre-commit hook + hooks directory** — `scripts/git-hooks/` renamed to `scripts/hooks/` per CLAUDE.md convention. New `pre-commit` hook runs lint gate. `install-hooks.sh` updated accordingly.
48
+ - **16.6 — Chunk size upper bound** — CasService, FixedChunker, and CdcChunker now reject chunk sizes exceeding 100 MiB. CasService logs a warning when chunk size exceeds 10 MiB.
49
+ - **ROADMAP.md M16 summary** — Corrected LoC/hours from `~430/~28h` to `~698/~21h` to match the detailed task breakdown.
50
+ - **VaultService constructor type** — Added missing `observability?: ObservabilityPort` parameter to `index.d.ts` declaration.
51
+ - **Nullish coalescing for config merging** — `strategy` and `codec` in `mergeConfig()` now use `??` instead of `||`, so empty-string CLI values don't fall through to `.casrc` defaults.
52
+ - **Empty passphrase rejection** — `readPassphraseFile` rejects files that yield an empty string after newline stripping. `resolvePassphrase` validates `--vault-passphrase` flag and `GIT_CAS_PASSPHRASE` env var.
53
+ - **KDF algorithm validation** — `vault init` and `vault rotate` now validate `--algorithm` against the supported set (`pbkdf2`, `scrypt`) before passing to the KDF.
54
+ - **`.casrc` config validation** — `loadConfig()` now validates all config values (types, ranges, enum membership) after JSON parsing.
55
+ - **Deprecated method names in docs** — Updated `deleteAsset` → `inspectAsset` and `findOrphanedChunks` → `collectReferencedChunks` in README and GUIDE.
56
+ - **Missing error codes in SECURITY.md** — Added `RESTORE_TOO_LARGE` and `ENCRYPTION_BUFFER_EXCEEDED` sections.
57
+
58
+ ## [5.2.4] — Prism polish (2026-03-03)
59
+
60
+ ### Fixed
61
+ - **`CryptoPortBase.sha256()` type** — `index.d.ts` declaration corrected from `string | Promise<string>` to `Promise<string>`, matching the async implementation since v5.2.3.
62
+ - **`keyLength` passthrough** — `KeyResolver.#resolveKeyFromPassphrase` and `deriveKekFromKdf` now forward `kdf.keyLength` to `deriveKey()`, fixing a latent bug for vaults configured with non-default key lengths.
63
+ - **Deno test compatibility** — `createCryptoAdapter.test.js` no longer crashes on Deno by guarding immutable `globalThis.Deno` restoration with try/catch and skipping Node-only tests on non-Node runtimes.
64
+ - **README wording** — "no public API changes" corrected to "no breaking API changes" in the v5.2.3 summary.
65
+ - **Barrel re-export description** — README and CHANGELOG now show the correct `export { default as X } from '...'` syntax.
66
+ - **Vestigial `lastchat.txt`** removed from `jsr.json` exclude list.
67
+
68
+ ### Changed
69
+ - **`keyResolver` is now private** — `CasService.keyResolver` changed to `#keyResolver`, preventing external access to an internal implementation detail.
70
+ - **`VaultPassphraseRotator.js` → `rotateVaultPassphrase.js`** — renamed to follow camelCase convention for files that export a function (PascalCase is reserved for classes).
71
+ - **`resolveChunker` validation** — `chunkSize` now validated as a finite positive number before constructing `FixedChunker`; invalid values fall through to CasService default.
72
+ - **`@fileoverview` JSDoc** added to `FileIOHelper.js`, `createCryptoAdapter.js`, and `resolveChunker.js`.
73
+ - **`KeyResolver` design note** — class JSDoc now documents the direct `CryptoPort.deriveKey()` call (bypasses `CasService.deriveKey()`).
74
+ - **Long function signature wrapped** — `rotateVaultPassphrase()` export signature broken across multiple lines.
75
+ - **Test hardening** — salt assertion in `KeyResolver.resolveForStore`, `keyLength` round-trip test, `resolveChunker` edge-case tests, guarded `rmSync` teardown in `FileIOHelper.test.js`.
76
+
77
+ ## [5.2.3] — Prism refactor (2026-03-03)
78
+
79
+ ### Changed
80
+ - **Async `sha256()` across all adapters** — `NodeCryptoAdapter.sha256()` now returns `Promise<string>` (was sync `string`), matching Bun and Web adapters. Fixes Liskov Substitution violation; all callers already `await`. `CryptoPort` JSDoc and `CasService.d.ts` updated to `Promise<string>`.
81
+ - **Extract `KeyResolver`** — ~170 lines of key resolution logic (`wrapDek`, `unwrapDek`, `resolveForDecryption`, `resolveForStore`, `resolveRecipients`, `resolveKeyForRecipients`, passphrase derivation, mutual-exclusion validation) extracted from `CasService` into `src/domain/services/KeyResolver.js`. CasService delegates via `this.keyResolver`. No public API changes. 24 new unit tests.
82
+ - **Move `createCryptoAdapter`** — runtime crypto detection moved from `index.js` to `src/infrastructure/adapters/createCryptoAdapter.js`; test helper now delegates instead of duplicating.
83
+ - **Factor out `resolveChunker`** — chunker factory resolution moved from `index.js` private method to `src/infrastructure/chunkers/resolveChunker.js`.
84
+ - **Move file I/O helpers** — `storeFile()` and `restoreFile()` moved from `index.js` to `src/infrastructure/adapters/FileIOHelper.js`; all `node:*` imports removed from facade.
85
+ - **Factor out `rotateVaultPassphrase`** — passphrase rotation orchestration (~100 lines with retry/backoff) moved from `index.js` to `src/domain/services/rotateVaultPassphrase.js`; `CasError` and `buildKdfMetadata` imports removed from facade.
86
+ - **Private `#config` field** — facade constructor stores options in a single private `#config` field instead of 10 public `this.fooConfig` properties.
87
+ - **Barrel re-exports** — 10 re-export-only modules (`NodeCryptoAdapter`, `Manifest`, `Chunk`, ports, observers, chunkers) converted to `export { default as X } from '...'` form, eliminating unnecessary local bindings.
88
+ - **Configurable retry** — `rotateVaultPassphrase()` now accepts optional `maxRetries` (default 3) and `retryBaseMs` (default 50) options for tuning optimistic-concurrency backoff.
89
+ - **Deterministic fuzz test** — envelope fuzz round-trip test now uses a seeded xorshift32 PRNG instead of `Math.random()`, making failures reproducible across runs.
90
+ - **DRY chunk verification** — extracted `_readAndVerifyChunk()` in `CasService`; both the buffered and streaming restore paths now delegate to the same single-chunk verification method.
91
+ - **DRY KDF metadata** — extracted `buildKdfMetadata()` helper (`src/domain/helpers/buildKdfMetadata.js`); `VaultService` and `ContentAddressableStore` both call it instead of duplicating the KDF object construction.
92
+
93
+ ## [5.2.2] — JSDoc total coverage (2026-02-28)
94
+
95
+ ### Added
96
+ - `tsconfig.checkjs.json` — strict `checkJs` configuration; `tsc --noEmit` passes with zero errors.
97
+ - `src/types/ambient.d.ts` — ambient type declarations for `@git-stunts/plumbing` and `bun` modules.
98
+ - `@types/node` dev dependency for typecheck support.
99
+ - JSDoc `@typedef` types: `EncryptionMeta`, `KdfParamSet`, `DeriveKeyParams` (CryptoPort); `VaultMetadata`, `VaultState`, `VaultEncryptionMeta` (VaultService).
100
+
101
+ ### Changed
102
+ - Every exported and internal function, class method, and callback across all 32 source files now has complete JSDoc `@param`/`@returns` annotations.
103
+ - CryptoPort return types widened to `string | Promise<string>` (sha256), `Buffer | Uint8Array` (randomBytes), sync-or-async for encrypt/decrypt — accurately reflecting adapter implementations.
104
+ - Port `@param` names corrected to match underscore-prefixed abstract parameters (fixes TS8024).
105
+ - Observer adapter methods (`SilentObserver`, `EventEmitterObserver`, `StatsCollector`) fully typed.
106
+ - CLI files (`bin/`) comprehensively annotated with JSDoc types for all Commander callbacks and TUI render functions.
107
+
8
108
  ## [5.2.1] — Carousel polish (2026-02-28)
9
109
 
10
110
  ### Added
package/README.md CHANGED
@@ -29,7 +29,7 @@ We use the object database.
29
29
  - **Manifests** a tiny explicit index of chunks + metadata (JSON/CBOR).
30
30
  - **Tree output** generates standard Git trees so assets snap into commits cleanly.
31
31
  - **Full round-trip** store, tree, and restore — get your bytes back, verified.
32
- - **Lifecycle management** `readManifest`, `deleteAsset`, `findOrphanedChunks` — inspect trees, plan deletions, audit storage.
32
+ - **Lifecycle management** `readManifest`, `inspectAsset`, `collectReferencedChunks` — inspect trees, plan deletions, audit storage.
33
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
34
  - **Interactive dashboard** `git cas inspect` with chunk heatmap, animated progress bars, and rich manifest views.
35
35
  - **Verify & JSON output** `git cas verify` checks integrity; `--json` on all commands for CI/scripting.
@@ -38,6 +38,37 @@ We use the object database.
38
38
 
39
39
  <img src="./docs/demo.gif" alt="git-cas demo" />
40
40
 
41
+ ## What's new in v5.3.0
42
+
43
+ **M16 Capstone — audit remediation, CLI configuration, and security hardening.**
44
+
45
+ - **`.casrc` config file** — JSON config at repo root sets defaults for all CLI flags (chunk size, strategy, concurrency, codec, compression, CDC params).
46
+ - **CLI store/restore flags** — all library-level options now accessible from the command line: `--gzip`, `--strategy`, `--chunk-size`, `--concurrency`, `--codec`, `--merkle-threshold`, and CDC-specific flags.
47
+ - **Passphrase-file support** — `--vault-passphrase-file <path>` on store, restore, and vault rotate (use `-` for stdin).
48
+ - **Memory restore guard** — `maxRestoreBufferSize` (default 512 MiB) prevents unbounded memory allocation on encrypted/compressed restore.
49
+ - **Web Crypto encryption buffer guard** — `maxEncryptionBufferSize` (default 512 MiB) for the one-shot AES-GCM API.
50
+ - **Orphaned blob tracking** — `STREAM_ERROR` now includes `meta.orphanedBlobs` for cleanup after partial store failures.
51
+ - **KDF brute-force awareness** — `decryption_failed` metric + CLI rate-limiting delay on `INTEGRITY_ERROR`.
52
+ - **Encryption counter** — vault metadata tracks `encryptionCount` with observability warning near GCM nonce bound.
53
+ - **Lifecycle method rename** — `inspectAsset()` / `collectReferencedChunks()` replace `deleteAsset()` / `findOrphanedChunks()` (old names preserved as deprecated aliases).
54
+ - **FixedChunker O(n²) fix** — pre-allocated buffer replaces `Buffer.concat()` loop.
55
+ - **Chunk size upper bound** — 100 MiB max enforced across all chunkers.
56
+ - **Constructor validation** — `chunkSize`, `maxRestoreBufferSize`, `maxEncryptionBufferSize` validated at construction time.
57
+ - **Cross-runtime portability** — `Error.captureStackTrace` guarded, crypto adapter contracts normalized.
58
+
59
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
60
+
61
+ ## What's new in v5.2.3
62
+
63
+ **Internal refactoring — no breaking API changes.** The facade, CasService, and crypto adapters were restructured for better separation of concerns:
64
+
65
+ - **Consistent async `sha256()`** — `NodeCryptoAdapter.sha256()` now returns `Promise<string>` like Bun and Web adapters, fixing a Liskov Substitution violation.
66
+ - **`KeyResolver` extracted** — ~170 lines of key resolution logic (DEK wrap/unwrap, passphrase derivation, envelope recipients) moved from CasService (1085 → 909 lines) into a dedicated `KeyResolver` service.
67
+ - **Facade decomposed** — `createCryptoAdapter`, `resolveChunker`, `FileIOHelper`, `rotateVaultPassphrase`, and `buildKdfMetadata` extracted from the monolithic `index.js` into focused modules.
68
+ - **Barrel re-exports** — 10 re-export-only modules converted to `export { default as X } from '...'` form.
69
+
70
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
71
+
41
72
  ## What's new in v5.2.1
42
73
 
43
74
  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.
@@ -205,9 +236,9 @@ await cas.restoreFile({ manifest, outputPath: './restored.png' });
205
236
  // Read the manifest back from a tree OID
206
237
  const m = await cas.readManifest({ treeOid });
207
238
 
208
- // Lifecycle: inspect deletion impact, find orphaned chunks
209
- const { slug, chunksOrphaned } = await cas.deleteAsset({ treeOid });
210
- const { referenced, total } = await cas.findOrphanedChunks({ treeOids: [treeOid] });
239
+ // Lifecycle: inspect deletion impact, collect referenced chunks
240
+ const { slug, chunksOrphaned } = await cas.inspectAsset({ treeOid });
241
+ const { referenced, total } = await cas.collectReferencedChunks({ treeOids: [treeOid] });
211
242
 
212
243
  // v2.0.0: Compressed + passphrase-encrypted store
213
244
  const manifest2 = await cas.storeFile({
@@ -271,16 +302,47 @@ git cas vault init
271
302
  git cas store ./secret.bin --slug vault-entry --tree
272
303
  git cas restore --slug vault-entry --out ./decrypted.bin
273
304
 
305
+ # Compression, chunking, codec, concurrency
306
+ git cas store ./data.bin --slug my-data --tree --gzip
307
+ git cas store ./data.bin --slug my-data --tree --strategy cdc
308
+ git cas store ./data.bin --slug my-data --tree --chunk-size 65536 --concurrency 4
309
+ git cas store ./data.bin --slug my-data --tree --codec cbor
310
+
311
+ # Restore with concurrency
312
+ git cas restore --slug my-data --out ./data.bin --concurrency 4
313
+
274
314
  # JSON output on any command (for CI/scripting)
275
315
  git cas store ./data.bin --slug my-data --tree --json
276
316
  ```
277
317
 
318
+ ### `.casrc` — Project Config File
319
+
320
+ Place a `.casrc` JSON file at the repository root to set defaults for CLI flags.
321
+ CLI flags always take precedence over `.casrc` values.
322
+
323
+ ```json
324
+ {
325
+ "chunkSize": 65536,
326
+ "strategy": "cdc",
327
+ "concurrency": 4,
328
+ "codec": "json",
329
+ "compression": "gzip",
330
+ "merkleThreshold": 500,
331
+ "maxRestoreBufferSize": 1073741824,
332
+ "cdc": {
333
+ "minChunkSize": 8192,
334
+ "targetChunkSize": 32768,
335
+ "maxChunkSize": 131072
336
+ }
337
+ }
338
+ ```
339
+
278
340
  ## Documentation
279
341
 
280
342
  - [Guide](./GUIDE.md) — progressive walkthrough
281
343
  - [API Reference](./docs/API.md) — full method documentation
282
344
  - [Architecture](./ARCHITECTURE.md) — hexagonal design overview
283
- - [Security](./docs/SECURITY.md) — crypto design and threat model
345
+ - [Security](./SECURITY.md) — crypto design and threat model
284
346
 
285
347
  ## When to use git-cas (and when not to)
286
348
 
package/bin/actions.js CHANGED
@@ -2,6 +2,9 @@
2
2
  * CLI error handler — wraps command actions with structured error output.
3
3
  */
4
4
 
5
+ /** @typedef {{ code?: string, message?: string }} ErrorLike */
6
+
7
+ /** @type {Readonly<Record<string, string>>} */
5
8
  const HINTS = {
6
9
  MISSING_KEY: 'Provide --key-file or --vault-passphrase',
7
10
  MANIFEST_NOT_FOUND: 'Verify the tree OID contains a manifest',
@@ -19,38 +22,65 @@ const HINTS = {
19
22
  /**
20
23
  * Format and write an error to stderr.
21
24
  *
22
- * @param {Error} err
25
+ * @param {ErrorLike} err
23
26
  * @param {boolean} json - Whether to output JSON.
24
27
  */
25
28
  function writeError(err, json) {
26
29
  const message = err?.message ?? String(err);
27
30
  const code = typeof err?.code === 'string' ? err.code : undefined;
28
31
  if (json) {
32
+ /** @type {{ error: string, code?: string }} */
29
33
  const obj = { error: message };
30
34
  if (code) { obj.code = code; }
31
35
  process.stderr.write(`${JSON.stringify(obj)}\n`);
32
36
  } else {
33
37
  const prefix = code ? `error [${code}]: ` : 'error: ';
34
38
  process.stderr.write(`${prefix}${message}\n`);
35
- const hint = code ? HINTS[code] : undefined;
39
+ const hint = getHint(code);
36
40
  if (hint) {
37
41
  process.stderr.write(`hint: ${hint}\n`);
38
42
  }
39
43
  }
40
44
  }
41
45
 
46
+ /**
47
+ * Look up a hint for the given error code, guarding against prototype keys.
48
+ *
49
+ * @param {string | undefined} code
50
+ * @returns {string | undefined}
51
+ */
52
+ function getHint(code) {
53
+ if (code && Object.prototype.hasOwnProperty.call(HINTS, code)) {
54
+ return HINTS[code];
55
+ }
56
+ return undefined;
57
+ }
58
+
59
+ /**
60
+ * Default delay — real setTimeout for production use.
61
+ * @param {number} ms
62
+ * @returns {Promise<void>}
63
+ */
64
+ function defaultDelay(ms) {
65
+ return new Promise((resolve) => { setTimeout(resolve, ms); });
66
+ }
67
+
42
68
  /**
43
69
  * Wrap a command action with structured error handling.
44
70
  *
45
- * @param {Function} fn - The async action function.
46
- * @param {Function} getJson - Lazy getter for --json flag value.
47
- * @returns {Function} Wrapped action.
71
+ * @param {(...args: any[]) => Promise<void>} fn - The async action function.
72
+ * @param {() => boolean} getJson - Lazy getter for --json flag value.
73
+ * @param {{ delay?: (ms: number) => Promise<void> }} [options] - Injectable dependencies.
74
+ * @returns {(...args: any[]) => Promise<void>} Wrapped action.
48
75
  */
49
- export function runAction(fn, getJson) {
50
- return async (...args) => {
76
+ export function runAction(fn, getJson, { delay = defaultDelay } = {}) {
77
+ return async (/** @type {any[]} */ ...args) => {
51
78
  try {
52
79
  await fn(...args);
53
- } catch (err) {
80
+ } catch (/** @type {any} */ err) {
81
+ if (err?.code === 'INTEGRITY_ERROR') {
82
+ await delay(1000);
83
+ }
54
84
  writeError(err, getJson());
55
85
  process.exitCode = 1;
56
86
  }
package/bin/config.js ADDED
@@ -0,0 +1,203 @@
1
+ /**
2
+ * @fileoverview Loads `.casrc` project config from the Git working directory.
3
+ *
4
+ * `.casrc` is a JSON file placed at the repository root that provides default
5
+ * values for CLI flags. CLI flags always take precedence over `.casrc` values.
6
+ *
7
+ * Supported keys:
8
+ * chunkSize — Chunk size in bytes (integer >= 1024, default 262144)
9
+ * strategy — Chunking strategy: "fixed" or "cdc" (default "fixed")
10
+ * concurrency — Parallel chunk I/O operations (positive integer, default 1)
11
+ * codec — Manifest codec: "json" or "cbor" (default "json")
12
+ * compression — Compression algorithm: "gzip" or false (default false)
13
+ * merkleThreshold — Chunk count threshold for Merkle sub-manifests (default 1000)
14
+ * maxRestoreBufferSize — Max bytes for buffered restore (default 536870912)
15
+ * cdc.minChunkSize — CDC minimum chunk size
16
+ * cdc.targetChunkSize — CDC target chunk size
17
+ * cdc.maxChunkSize — CDC maximum chunk size
18
+ */
19
+
20
+ import { readFileSync } from 'node:fs';
21
+ import { resolve } from 'node:path';
22
+
23
+ const FILENAME = '.casrc';
24
+ const MAX_CHUNK_SIZE = 100 * 1024 * 1024;
25
+
26
+ /**
27
+ * @typedef {Object} CasConfig
28
+ * @property {number} [chunkSize]
29
+ * @property {string} [strategy]
30
+ * @property {number} [concurrency]
31
+ * @property {string} [codec]
32
+ * @property {string|false} [compression]
33
+ * @property {number} [merkleThreshold]
34
+ * @property {number} [maxRestoreBufferSize]
35
+ * @property {{ minChunkSize?: number, targetChunkSize?: number, maxChunkSize?: number }} [cdc]
36
+ */
37
+
38
+ /**
39
+ * @param {any} value
40
+ * @param {string} name
41
+ * @param {{ min: number, max?: number }} range
42
+ */
43
+ function assertInt(value, name, { min, max }) {
44
+ if (value === undefined) { return; }
45
+ if (!Number.isInteger(value) || value < min) {
46
+ throw new Error(`${FILENAME}: ${name} must be an integer >= ${min}`);
47
+ }
48
+ if (max !== undefined && value > max) {
49
+ throw new Error(`${FILENAME}: ${name} must not exceed ${max}`);
50
+ }
51
+ }
52
+
53
+ /**
54
+ * @param {any} value
55
+ * @param {string} name
56
+ * @param {string[]} allowed
57
+ */
58
+ function assertEnum(value, name, allowed) {
59
+ if (value === undefined) { return; }
60
+ if (!allowed.includes(value)) {
61
+ throw new Error(`${FILENAME}: ${name} must be ${allowed.map((v) => `"${v}"`).join(' or ')}`);
62
+ }
63
+ }
64
+
65
+ /**
66
+ * @param {Record<string, any>} config
67
+ */
68
+ /**
69
+ * @param {{ minChunkSize?: number, targetChunkSize?: number, maxChunkSize?: number }} cdc
70
+ */
71
+ function assertCdcOrdering(cdc) {
72
+ const { minChunkSize, targetChunkSize, maxChunkSize } = cdc;
73
+ if (minChunkSize !== undefined && maxChunkSize !== undefined && minChunkSize > maxChunkSize) {
74
+ throw new Error(`${FILENAME}: cdc.minChunkSize must not exceed cdc.maxChunkSize`);
75
+ }
76
+ if (targetChunkSize !== undefined && minChunkSize !== undefined && targetChunkSize < minChunkSize) {
77
+ throw new Error(`${FILENAME}: cdc.targetChunkSize must be >= cdc.minChunkSize`);
78
+ }
79
+ if (targetChunkSize !== undefined && maxChunkSize !== undefined && targetChunkSize > maxChunkSize) {
80
+ throw new Error(`${FILENAME}: cdc.targetChunkSize must be <= cdc.maxChunkSize`);
81
+ }
82
+ }
83
+
84
+ /**
85
+ * @param {Record<string, any>} config
86
+ */
87
+ function validateCdc(config) {
88
+ if (config.cdc === undefined) { return; }
89
+ if (typeof config.cdc !== 'object' || config.cdc === null || Array.isArray(config.cdc)) {
90
+ throw new Error(`${FILENAME}: cdc must be an object`);
91
+ }
92
+ for (const key of ['minChunkSize', 'targetChunkSize', 'maxChunkSize']) {
93
+ assertInt(config.cdc[key], `cdc.${key}`, { min: 1, max: MAX_CHUNK_SIZE });
94
+ }
95
+ assertCdcOrdering(config.cdc);
96
+ }
97
+
98
+ /**
99
+ * Validates `.casrc` config values after parsing.
100
+ *
101
+ * @param {Record<string, any>} config
102
+ */
103
+ function validateConfig(config) {
104
+ assertInt(config.chunkSize, 'chunkSize', { min: 1024, max: MAX_CHUNK_SIZE });
105
+ assertEnum(config.strategy, 'strategy', ['fixed', 'cdc']);
106
+ assertInt(config.concurrency, 'concurrency', { min: 1 });
107
+ assertEnum(config.codec, 'codec', ['json', 'cbor']);
108
+ if (config.compression !== undefined && config.compression !== false) {
109
+ assertEnum(config.compression, 'compression', ['gzip']);
110
+ }
111
+ assertInt(config.merkleThreshold, 'merkleThreshold', { min: 1 });
112
+ assertInt(config.maxRestoreBufferSize, 'maxRestoreBufferSize', { min: 1024 });
113
+ validateCdc(config);
114
+ }
115
+
116
+ /**
117
+ * Loads `.casrc` from the given directory, returning an empty object if not found.
118
+ *
119
+ * @param {string} cwd - Directory to search for `.casrc`.
120
+ * @returns {CasConfig}
121
+ */
122
+ export function loadConfig(cwd) {
123
+ const filePath = resolve(cwd, FILENAME);
124
+ try {
125
+ const raw = readFileSync(filePath, 'utf8');
126
+ const config = JSON.parse(raw);
127
+ if (typeof config !== 'object' || config === null || Array.isArray(config)) {
128
+ throw new Error(`${FILENAME}: expected a JSON object`);
129
+ }
130
+ validateConfig(config);
131
+ return config;
132
+ } catch (err) {
133
+ if (err.code === 'ENOENT') {
134
+ return {};
135
+ }
136
+ if (err instanceof SyntaxError) {
137
+ throw new Error(`${FILENAME}: invalid JSON — ${err.message}`);
138
+ }
139
+ throw err;
140
+ }
141
+ }
142
+
143
+ /**
144
+ * Sets key on target if value is not undefined.
145
+ * @param {Record<string, any>} target
146
+ * @param {string} key
147
+ * @param {any} value
148
+ */
149
+ function setIfDefined(target, key, value) {
150
+ if (value !== undefined) { target[key] = value; }
151
+ }
152
+
153
+ /**
154
+ * Resolves chunking config from merged CLI + config values.
155
+ * @param {{ strategy?: string, chunkSize?: number, cliOpts: Record<string, any>, config: CasConfig }} opts
156
+ * @returns {Record<string, any>|undefined}
157
+ */
158
+ function resolveChunking({ strategy, chunkSize, cliOpts, config }) {
159
+ if (strategy === 'cdc') {
160
+ const cdcConf = config.cdc || {};
161
+ return {
162
+ strategy: 'cdc',
163
+ targetChunkSize: cliOpts.targetChunkSize ?? cdcConf.targetChunkSize,
164
+ minChunkSize: cliOpts.minChunkSize ?? cdcConf.minChunkSize,
165
+ maxChunkSize: cliOpts.maxChunkSize ?? cdcConf.maxChunkSize,
166
+ };
167
+ }
168
+ if (strategy === 'fixed' && chunkSize !== undefined) {
169
+ return { strategy: 'fixed', chunkSize };
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ /**
175
+ * Merges CLI options over `.casrc` defaults. CLI flags take precedence.
176
+ *
177
+ * @param {Record<string, any>} cliOpts - Parsed CLI options.
178
+ * @param {CasConfig} config - Loaded `.casrc` config.
179
+ * @returns {{ casConfig: Record<string, any>, storeExtras: Record<string, any> }}
180
+ */
181
+ export function mergeConfig(cliOpts, config) {
182
+ const strategy = cliOpts.strategy ?? config.strategy;
183
+ const chunkSize = cliOpts.chunkSize ?? config.chunkSize;
184
+
185
+ /** @type {Record<string, any>} */
186
+ const casConfig = {};
187
+ setIfDefined(casConfig, 'concurrency', cliOpts.concurrency ?? config.concurrency);
188
+ setIfDefined(casConfig, 'chunkSize', chunkSize);
189
+ setIfDefined(casConfig, 'merkleThreshold', cliOpts.merkleThreshold ?? config.merkleThreshold);
190
+ setIfDefined(casConfig, 'maxRestoreBufferSize', cliOpts.maxRestoreBufferSize ?? config.maxRestoreBufferSize);
191
+ setIfDefined(casConfig, 'chunking', resolveChunking({ strategy, chunkSize, cliOpts, config }));
192
+
193
+ const codec = cliOpts.codec ?? config.codec;
194
+ if (codec === 'cbor') { casConfig.codec = 'cbor'; }
195
+
196
+ /** @type {Record<string, any>} */
197
+ const storeExtras = {};
198
+ if (cliOpts.gzip || config.compression === 'gzip') {
199
+ storeExtras.compression = { algorithm: 'gzip' };
200
+ }
201
+
202
+ return { casConfig, storeExtras };
203
+ }