@git-stunts/git-cas 5.3.2 → 6.0.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 (173) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +998 -214
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +296 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2224 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +208 -65
  60. package/index.js +163 -54
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
@@ -0,0 +1,1868 @@
1
+ # git-cas: The Complete Guide
2
+
3
+ A progressive guide to content-addressed storage backed by Git. Every section
4
+ builds on the same running example -- storing, managing, and restoring a photo
5
+ called `vacation.jpg` under the slug `photos/vacation` -- so you can follow
6
+ along from first principles to full mastery.
7
+
8
+ This is the long-form walkthrough. For the current public API surface and the
9
+ canonical architecture and security guidance, see [README.md](../README.md),
10
+ [API.md](./API.md), [ARCHITECTURE.md](../ARCHITECTURE.md), [SECURITY.md](../SECURITY.md),
11
+ and [THREAT_MODEL.md](./THREAT_MODEL.md).
12
+
13
+ ---
14
+
15
+ ## Table of Contents
16
+
17
+ 1. [What is git-cas?](#1-what-is-git-cas)
18
+ 2. [Quick Start](#2-quick-start)
19
+ 3. [Core Concepts](#3-core-concepts)
20
+ 4. [Storing Files](#4-storing-files)
21
+ 5. [Restoring Files](#5-restoring-files)
22
+ 6. [Encryption](#6-encryption)
23
+ 7. [The CLI](#7-the-cli)
24
+ 8. [Lifecycle Management](#8-lifecycle-management)
25
+ 9. [Observability](#9-observability)
26
+ 10. [Compression](#10-compression)
27
+ 11. [Passphrase Encryption (KDF)](#11-passphrase-encryption-kdf)
28
+ 11b. [Multi-Recipient Encryption & Key Rotation](#11b-multi-recipient-encryption--key-rotation)
29
+ 12. [Merkle Manifests](#12-merkle-manifests)
30
+ 13. [Vault](#13-vault)
31
+ 14. [Architecture](#14-architecture)
32
+ 15. [Codec System](#15-codec-system)
33
+ 16. [Error Handling](#16-error-handling)
34
+ 17. [FAQ / Troubleshooting](#17-faq--troubleshooting)
35
+
36
+ ---
37
+
38
+ ## 1. What is git-cas?
39
+
40
+ Git is, at its core, a content-addressed object database. Every object --
41
+ blob, tree, commit, tag -- is stored by the SHA-1 hash of its content. When
42
+ two files share the same bytes, Git stores them once. `git-cas` takes this
43
+ property seriously: it turns Git's object database into a general-purpose
44
+ content-addressed storage (CAS) system for arbitrary binary files.
45
+
46
+ The problem `git-cas` solves is straightforward. You have large binary assets
47
+ -- images, model weights, data packs, build artifacts, encrypted secret
48
+ bundles -- and you want to store them in a way that is deterministic,
49
+ deduplicated, integrity-verified, and committable. Git LFS solves this by
50
+ moving blobs to an external server, but that introduces a separate
51
+ infrastructure dependency and breaks the self-contained nature of a Git
52
+ repository. `git-cas` keeps everything inside Git's own object database.
53
+
54
+ The approach works as follows. A file is split into fixed-size chunks, each
55
+ chunk is written as a Git blob via `git hash-object -w`, and a manifest
56
+ (a small JSON or CBOR document listing every chunk's hash, size, and blob OID)
57
+ is written alongside them into a Git tree via `git mktree`. That tree OID can
58
+ then be committed, tagged, or referenced like any other Git object. Restoring
59
+ the file means reading the tree, parsing the manifest, fetching each blob,
60
+ verifying SHA-256 digests, and concatenating the bytes back together. Optional
61
+ AES-256-GCM encryption controls what lands in the object database: `whole` and
62
+ `framed` encrypt before chunk storage, while `convergent` encrypts each chunk
63
+ deterministically to preserve CDC deduplication. Plaintext never touches the
64
+ ODB.
65
+
66
+ ---
67
+
68
+ ## 2. Quick Start
69
+
70
+ ### Prerequisites
71
+
72
+ - Node.js >= 22.0.0 (Bun and Deno are also supported)
73
+ - A Git repository (bare or working tree)
74
+
75
+ ### Install
76
+
77
+ ```bash
78
+ npm install @git-stunts/git-cas
79
+ ```
80
+
81
+ ### Minimal Working Example
82
+
83
+ ```js
84
+ import ContentAddressableStore from '@git-stunts/git-cas';
85
+
86
+ // Point at a Git repository
87
+ const cas = await ContentAddressableStore.open({ cwd: './my-repo' });
88
+
89
+ // Store vacation.jpg under the slug "photos/vacation"
90
+ const manifest = await cas.storeFile({
91
+ filePath: './vacation.jpg',
92
+ slug: 'photos/vacation',
93
+ });
94
+
95
+ console.log(manifest.slug); // "photos/vacation"
96
+ console.log(manifest.filename); // "vacation.jpg"
97
+ console.log(manifest.size); // total bytes stored
98
+ console.log(manifest.chunks.length); // number of chunks
99
+
100
+ // Create a Git tree from the manifest
101
+ const treeOid = await cas.createTree({ manifest });
102
+ console.log(treeOid); // e.g. "a1b2c3d4..."
103
+
104
+ // Restore the file later
105
+ await cas.restoreFile({
106
+ manifest,
107
+ outputPath: './restored.jpg',
108
+ baseDirectory: process.cwd(),
109
+ });
110
+ ```
111
+
112
+ That is the full round-trip: store, tree, restore. The rest of this guide
113
+ unpacks what happens at each step.
114
+
115
+ ---
116
+
117
+ ## 3. Core Concepts
118
+
119
+ ### Slugs
120
+
121
+ A slug is a logical identifier for your asset. It is a freeform, non-empty
122
+ string -- typically a path-like name such as `photos/vacation` or
123
+ `models/v3-weights`. The slug is stored inside the manifest and is how you
124
+ refer to the asset in your application logic. It does not affect where
125
+ data lives in Git's object database.
126
+
127
+ ### Chunks
128
+
129
+ Large files are split into fixed-size pieces called chunks. Each chunk is
130
+ stored as a Git blob. A chunk has four properties:
131
+
132
+ | Field | Type | Description |
133
+ | -------- | ------ | --------------------------------------------- |
134
+ | `index` | number | Zero-based position in the file |
135
+ | `size` | number | Byte length of this chunk |
136
+ | `digest` | string | SHA-256 hex digest of the chunk's raw bytes |
137
+ | `blob` | string | Git OID (the SHA-1 hash Git uses to store it) |
138
+
139
+ Because Git is itself content-addressed, if two chunks happen to contain
140
+ identical bytes, Git stores them only once. This gives you deduplication
141
+ for free.
142
+
143
+ ### Manifests
144
+
145
+ A manifest is the index that ties everything together. After storing
146
+ `vacation.jpg`, the manifest looks like this:
147
+
148
+ ```json
149
+ {
150
+ "slug": "photos/vacation",
151
+ "filename": "vacation.jpg",
152
+ "size": 524288,
153
+ "chunks": [
154
+ {
155
+ "index": 0,
156
+ "size": 262144,
157
+ "digest": "e3b0c44298fc1c149afbf4c8996fb924...",
158
+ "blob": "a1b2c3d4e5f6..."
159
+ },
160
+ {
161
+ "index": 1,
162
+ "size": 262144,
163
+ "digest": "d7a8fbb307d7809469ca9abcb0082e4f...",
164
+ "blob": "f6e5d4c3b2a1..."
165
+ }
166
+ ]
167
+ }
168
+ ```
169
+
170
+ Manifests are immutable value objects validated by a Zod schema at
171
+ construction time. If you try to create a `Manifest` with missing or
172
+ malformed fields, an error is thrown immediately.
173
+
174
+ For encrypted manifests, that validation is intentionally strict: only current
175
+ `whole`, `framed`, and `convergent` AES-256-GCM metadata are accepted, and
176
+ malformed nonce/tag or missing `frameBytes` values are rejected before
177
+ restore-time service logic runs. Legacy scheme identifiers (`whole-v1`,
178
+ `framed-v1`, etc.) are no longer accepted and throw `LEGACY_SCHEME`.
179
+
180
+ When encryption is used, the manifest gains an additional `encryption` field.
181
+ For `whole`, it looks like this:
182
+
183
+ ```json
184
+ {
185
+ "slug": "photos/vacation",
186
+ "filename": "vacation.jpg",
187
+ "size": 524288,
188
+ "chunks": [ ... ],
189
+ "encryption": {
190
+ "scheme": "whole",
191
+ "algorithm": "aes-256-gcm",
192
+ "nonce": "base64-encoded-nonce",
193
+ "tag": "base64-encoded-auth-tag",
194
+ "encrypted": true
195
+ }
196
+ }
197
+ ```
198
+
199
+ ### Git Trees
200
+
201
+ When you call `createTree({ manifest })`, `git-cas` serializes the manifest
202
+ using the configured codec (JSON by default), writes it as a blob, then
203
+ builds a Git tree that looks like this:
204
+
205
+ ```
206
+ 100644 blob <oid> manifest.json
207
+ 100644 blob <oid> e3b0c44298fc1c149afbf4c8996fb924...
208
+ 100644 blob <oid> d7a8fbb307d7809469ca9abcb0082e4f...
209
+ ```
210
+
211
+ The tree contains one entry for the manifest file (named `manifest.json` or
212
+ `manifest.cbor` depending on the codec) and one entry per chunk, named by
213
+ its SHA-256 digest. This tree OID is a standard Git object -- you can commit
214
+ it, tag it, push it, or embed it in a larger tree.
215
+
216
+ ### Codecs
217
+
218
+ The codec controls how the manifest is serialized before being written to
219
+ Git. Two codecs ship with `git-cas`:
220
+
221
+ - **JsonCodec** -- human-readable, produces `manifest.json`. Default.
222
+ - **CborCodec** -- compact binary format, produces `manifest.cbor`. Smaller manifests.
223
+
224
+ Both implement the same `CodecPort` interface: `encode(data)`, `decode(buffer)`,
225
+ and `get extension()`.
226
+
227
+ ---
228
+
229
+ ## 4. Storing Files
230
+
231
+ ### The Store Flow
232
+
233
+ When you call `cas.storeFile()`, the following happens:
234
+
235
+ 1. The file at `filePath` is opened as a readable stream.
236
+ 2. The stream is consumed in chunks of `chunkSize` bytes (default: 256 KiB).
237
+ 3. Each chunk is SHA-256 hashed and written to Git as a blob via
238
+ `git hash-object -w --stdin`.
239
+ 4. A manifest is assembled from the chunk metadata.
240
+ 5. The manifest is returned as a frozen `Manifest` value object.
241
+
242
+ ### Configuring Chunk Size
243
+
244
+ The default chunk size is 256 KiB (262,144 bytes). You can change it at
245
+ construction time. The minimum is 1,024 bytes.
246
+
247
+ ```js
248
+ const cas = new ContentAddressableStore({
249
+ plumbing: git,
250
+ chunkSize: 1024 * 1024, // 1 MiB chunks
251
+ });
252
+ ```
253
+
254
+ Larger chunks mean fewer Git objects but coarser deduplication. Smaller chunks
255
+ improve deduplication but increase object count and manifest size. For most
256
+ use cases, the default is a good balance.
257
+
258
+ ### Storing Our Example File
259
+
260
+ ```js
261
+ import GitPlumbing from '@git-stunts/plumbing';
262
+ import ContentAddressableStore from '@git-stunts/git-cas';
263
+
264
+ const git = await GitPlumbing.createDefault({ cwd: './assets-repo' });
265
+ const cas = new ContentAddressableStore({ plumbing: git });
266
+
267
+ const manifest = await cas.storeFile({
268
+ filePath: './vacation.jpg',
269
+ slug: 'photos/vacation',
270
+ });
271
+
272
+ // Inspect the result
273
+ console.log(`Stored ${manifest.filename} (${manifest.size} bytes)`);
274
+ console.log(`Split into ${manifest.chunks.length} chunks`);
275
+
276
+ for (const chunk of manifest.chunks) {
277
+ console.log(` chunk[${chunk.index}]: ${chunk.size} bytes, blob ${chunk.blob}`);
278
+ }
279
+ ```
280
+
281
+ For a 500 KiB file with the default 256 KiB chunk size, you would see two
282
+ chunks: the first at 262,144 bytes and the second at the remaining bytes.
283
+
284
+ ### Storing from an Async Iterable
285
+
286
+ If you already have data in memory or coming from a non-file source, use
287
+ `store()` directly instead of `storeFile()`:
288
+
289
+ ```js
290
+ const encoder = new TextEncoder();
291
+
292
+ async function* generateData() {
293
+ yield encoder.encode('first batch of bytes...');
294
+ yield encoder.encode('second batch of bytes...');
295
+ }
296
+
297
+ const manifest = await cas.store({
298
+ source: generateData(),
299
+ slug: 'photos/vacation',
300
+ filename: 'vacation.jpg',
301
+ });
302
+ ```
303
+
304
+ ### Creating a Git Tree
305
+
306
+ Once you have the manifest, persist it as a Git tree:
307
+
308
+ ```js
309
+ const treeOid = await cas.createTree({ manifest });
310
+ console.log(`Tree OID: ${treeOid}`);
311
+
312
+ // You can now commit this tree:
313
+ // git commit-tree <treeOid> -m "Store vacation.jpg"
314
+ ```
315
+
316
+ ---
317
+
318
+ ## 5. Restoring Files
319
+
320
+ ### Restoring to Disk
321
+
322
+ Given a manifest, `restoreFile()` restores the asset and writes it to the
323
+ specified output path.
324
+
325
+ For plaintext assets, this uses `restoreStream()` and writes chunk-by-chunk with
326
+ bounded memory. When the persistence adapter supports `readBlobStream()`, the
327
+ plaintext chunk path prefers that stream-native read seam before falling back
328
+ to `readBlob()` for compatibility. For `whole` and compression-buffered
329
+ modes, `restoreFile()` now writes through a bounded temp-file path: verified
330
+ bytes flow into whole-object decryption and optional gunzip, then the
331
+ destination is renamed into place only after the pipeline succeeds. For
332
+ generic async byte consumers, `restoreStream()` is still the compatibility
333
+ truth surface: `whole` buffers after chunk verification so it can
334
+ authenticate the full ciphertext as one unit, while `framed` restores
335
+ authenticated plaintext incrementally. If compression is combined with
336
+ `framed`, restore streams through gunzip after frame-by-frame decryption.
337
+ On Web Crypto runtimes, that `whole` decrypt step is still internally
338
+ one-shot. The improvement is bounded behavior, not true whole-object streaming.
339
+
340
+ ```js
341
+ await cas.restoreFile({
342
+ manifest,
343
+ outputPath: './restored-vacation.jpg',
344
+ baseDirectory: process.cwd(),
345
+ });
346
+ // restored-vacation.jpg is now byte-identical to the original
347
+ ```
348
+
349
+ ### Restoring to Memory
350
+
351
+ If you need the bytes in memory rather than on disk, use `restore()`:
352
+
353
+ ```js
354
+ const { buffer, bytesWritten } = await cas.restore({ manifest });
355
+ console.log(`Restored ${bytesWritten} bytes into memory`);
356
+ ```
357
+
358
+ The returned `buffer` is a `Uint8Array`. In Node.js it can be wrapped with
359
+ `Buffer.from(buffer)` when you need Buffer-specific helpers.
360
+
361
+ ### Byte-Level Integrity Verification
362
+
363
+ During restore, each chunk is re-hashed with SHA-256 and compared against the
364
+ digest recorded in the manifest. If any chunk has been corrupted or tampered
365
+ with, an `INTEGRITY_ERROR` is thrown immediately:
366
+
367
+ ```
368
+ CasError: Chunk 0 integrity check failed
369
+ code: 'INTEGRITY_ERROR'
370
+ meta: { chunkIndex: 0, expected: '...', actual: '...' }
371
+ ```
372
+
373
+ You can also verify integrity without restoring:
374
+
375
+ ```js
376
+ const isValid = await cas.verifyIntegrity(manifest);
377
+ if (isValid) {
378
+ console.log('All chunks intact');
379
+ } else {
380
+ console.log('Corruption detected');
381
+ }
382
+ ```
383
+
384
+ ### Restoring from a Tree OID
385
+
386
+ In many workflows you do not have the manifest object in memory -- you have a
387
+ Git tree OID that was committed earlier. Use the public `readManifest()`
388
+ helper, then restore from that manifest:
389
+
390
+ ```js
391
+ const manifest = await cas.readManifest({ treeOid });
392
+ await cas.restoreFile({
393
+ manifest,
394
+ outputPath: './restored-vacation.jpg',
395
+ baseDirectory: process.cwd(),
396
+ });
397
+ ```
398
+
399
+ The CLI (Section 7) handles this entire flow with a single command.
400
+
401
+ ---
402
+
403
+ ## 6. Encryption
404
+
405
+ `git-cas` supports optional AES-256-GCM encryption. When enabled, the file
406
+ content is encrypted via a streaming cipher before chunking, so only
407
+ ciphertext is stored in Git's object database. Plaintext never touches the
408
+ ODB.
409
+
410
+ ### Generating a Key
411
+
412
+ An encryption key must be exactly 32 bytes (256 bits). Generate one with
413
+ OpenSSL:
414
+
415
+ ```bash
416
+ openssl rand -out vacation.key 32
417
+ ```
418
+
419
+ Or in Node.js:
420
+
421
+ ```js
422
+ import { randomBytes } from 'node:crypto';
423
+ import { writeFileSync } from 'node:fs';
424
+
425
+ const key = randomBytes(32);
426
+ writeFileSync('./vacation.key', key);
427
+ ```
428
+
429
+ ### Encrypted Store
430
+
431
+ Pass the `encryptionKey` option when storing:
432
+
433
+ ```js
434
+ import { readFileSync } from 'node:fs';
435
+
436
+ const encryptionKey = readFileSync('./vacation.key');
437
+
438
+ const manifest = await cas.storeFile({
439
+ filePath: './vacation.jpg',
440
+ slug: 'photos/vacation',
441
+ encryptionKey,
442
+ });
443
+
444
+ console.log(manifest.encryption);
445
+ // {
446
+ // scheme: 'framed',
447
+ // algorithm: 'aes-256-gcm',
448
+ // frameBytes: 65536,
449
+ // encrypted: true
450
+ // }
451
+ ```
452
+
453
+ Fixed-chunk encrypted writes default to `framed`, which authenticates each
454
+ stored frame independently. The nonce and tag live inside the serialized
455
+ payload rather than as top-level manifest fields, so the manifest records
456
+ `frameBytes` instead. When using CDC chunking with encryption, the default is
457
+ `convergent`.
458
+
459
+ If you need the whole-object format, opt into `whole` explicitly:
460
+
461
+ ```js
462
+ const manifest = await cas.storeFile({
463
+ filePath: './vacation.jpg',
464
+ slug: 'photos/vacation-whole',
465
+ encryptionKey,
466
+ encryption: { scheme: 'whole' },
467
+ });
468
+
469
+ console.log(manifest.encryption);
470
+ // {
471
+ // scheme: 'whole',
472
+ // algorithm: 'aes-256-gcm',
473
+ // nonce: 'dGhpcyBpcyBhIG5vbmNl',
474
+ // tag: 'YXV0aGVudGljYXRpb24gdGFn',
475
+ // encrypted: true
476
+ // }
477
+ ```
478
+
479
+ Legacy encrypted manifests with version-suffixed scheme names (e.g.,
480
+ `whole-v1`, `framed-v2`) are no longer accepted and throw `LEGACY_SCHEME`.
481
+ Run `npm run upgrade` to migrate.
482
+
483
+ ### Encrypted Restore
484
+
485
+ To restore encrypted content, provide the same key:
486
+
487
+ ```js
488
+ await cas.restoreFile({
489
+ manifest,
490
+ encryptionKey,
491
+ outputPath: './decrypted-vacation.jpg',
492
+ baseDirectory: process.cwd(),
493
+ });
494
+ // decrypted-vacation.jpg is byte-identical to the original vacation.jpg
495
+ ```
496
+
497
+ ### What Happens with the Wrong Key
498
+
499
+ If you attempt to restore with an incorrect key, AES-256-GCM's authenticated
500
+ encryption detects the mismatch and throws:
501
+
502
+ ```
503
+ CasError: Decryption failed: Integrity check error
504
+ code: 'INTEGRITY_ERROR'
505
+ ```
506
+
507
+ If you attempt to restore encrypted content without providing any key at all:
508
+
509
+ ```
510
+ CasError: Encryption key required to restore encrypted content
511
+ code: 'MISSING_KEY'
512
+ ```
513
+
514
+ ### Key Validation
515
+
516
+ Keys must be a `Uint8Array` of exactly 32 bytes. Node `Buffer` values are
517
+ accepted because they extend `Uint8Array`. Violations produce clear errors:
518
+
519
+ - Non-`Uint8Array` key: `INVALID_KEY_TYPE`
520
+ - Wrong length: `INVALID_KEY_LENGTH` (includes expected and actual lengths)
521
+
522
+ ### Encrypted Tree Round-Trip
523
+
524
+ The full encrypted workflow, from store to tree to restore:
525
+
526
+ ```js
527
+ import { readFileSync } from 'node:fs';
528
+ import GitPlumbing from '@git-stunts/plumbing';
529
+ import ContentAddressableStore from '@git-stunts/git-cas';
530
+
531
+ const git = await GitPlumbing.createDefault({ cwd: './assets-repo' });
532
+ const cas = new ContentAddressableStore({ plumbing: git });
533
+ const encryptionKey = readFileSync('./vacation.key');
534
+
535
+ // Store with encryption
536
+ const manifest = await cas.storeFile({
537
+ filePath: './vacation.jpg',
538
+ slug: 'photos/vacation',
539
+ encryptionKey,
540
+ });
541
+
542
+ // Persist as a Git tree
543
+ const treeOid = await cas.createTree({ manifest });
544
+
545
+ // Later: restore from tree OID (see Section 5 for readTree pattern)
546
+ // ...pass encryptionKey to restoreFile()
547
+ ```
548
+
549
+ ---
550
+
551
+ ## 7. The CLI
552
+
553
+ <img src="./cli.gif" alt="git-cas CLI demo" />
554
+
555
+ `git-cas` installs as a Git subcommand. After installation, `git cas` is
556
+ available in any Git repository.
557
+
558
+ ### Store a File
559
+
560
+ ```bash
561
+ # Store vacation.jpg and print the manifest JSON
562
+ git cas store ./vacation.jpg --slug photos/vacation
563
+ ```
564
+
565
+ Output (manifest JSON):
566
+
567
+ ```json
568
+ {
569
+ "slug": "photos/vacation",
570
+ "filename": "vacation.jpg",
571
+ "size": 524288,
572
+ "chunks": [
573
+ {
574
+ "index": 0,
575
+ "size": 262144,
576
+ "digest": "e3b0c44298fc1c149afbf4c8996fb924...",
577
+ "blob": "a1b2c3d4e5f6..."
578
+ },
579
+ {
580
+ "index": 1,
581
+ "size": 262144,
582
+ "digest": "d7a8fbb307d7809469ca9abcb0082e4f...",
583
+ "blob": "f6e5d4c3b2a1..."
584
+ }
585
+ ]
586
+ }
587
+ ```
588
+
589
+ ### Store and Get a Tree OID
590
+
591
+ ```bash
592
+ # The --tree flag creates a tree and prints its OID instead of the manifest
593
+ git cas store ./vacation.jpg --slug photos/vacation --tree
594
+ # Output: a1b2c3d4e5f67890...
595
+ ```
596
+
597
+ ### Create a Tree from an Existing Manifest
598
+
599
+ If you saved the manifest JSON to a file, you can create a tree from it later:
600
+
601
+ ```bash
602
+ git cas store ./vacation.jpg --slug photos/vacation > manifest.json
603
+ git cas tree --manifest manifest.json
604
+ # Output: a1b2c3d4e5f67890...
605
+ ```
606
+
607
+ ### Restore from a Tree OID
608
+
609
+ ```bash
610
+ git cas restore --oid a1b2c3d4e5f67890... --out ./restored-vacation.jpg
611
+ # Output: 524288 (bytes written)
612
+ ```
613
+
614
+ The `restore` command reads the tree, finds the manifest entry, decodes it,
615
+ reads and verifies all chunks, and writes the reassembled file.
616
+
617
+ ### Encrypted CLI Round-Trip
618
+
619
+ ```bash
620
+ # Generate a 32-byte key
621
+ openssl rand -out vacation.key 32
622
+
623
+ # Store with encryption, get a tree OID
624
+ git cas store ./vacation.jpg --slug photos/vacation --key-file ./vacation.key --tree
625
+ # Output: a1b2c3d4e5f67890...
626
+
627
+ # Restore with the same key
628
+ git cas restore --oid a1b2c3d4e5f67890... --out ./decrypted-vacation.jpg --key-file ./vacation.key
629
+ # Output: 524288
630
+ ```
631
+
632
+ ### Compression, Chunking, and Codec Flags
633
+
634
+ ```bash
635
+ # Enable gzip compression
636
+ git cas store ./data.bin --slug my-data --tree --gzip
637
+
638
+ # Use CDC (content-defined chunking) for sub-file deduplication
639
+ git cas store ./data.bin --slug my-data --tree --strategy cdc
640
+
641
+ # Customize chunk size and enable parallel I/O
642
+ git cas store ./data.bin --slug my-data --tree --chunk-size 65536 --concurrency 4
643
+
644
+ # Use CBOR codec for smaller manifests
645
+ git cas store ./data.bin --slug my-data --tree --codec cbor
646
+
647
+ # CDC with custom parameters
648
+ git cas store ./data.bin --slug my-data --tree \
649
+ --strategy cdc --target-chunk-size 32768 \
650
+ --min-chunk-size 8192 --max-chunk-size 131072
651
+
652
+ # Restore with parallel I/O
653
+ git cas restore --slug my-data --out ./data.bin --concurrency 4
654
+ ```
655
+
656
+ ### Project Config File (`.casrc`)
657
+
658
+ Place a `.casrc` JSON file at the repository root to set defaults. CLI flags
659
+ always take precedence.
660
+
661
+ ```json
662
+ {
663
+ "chunkSize": 65536,
664
+ "strategy": "cdc",
665
+ "concurrency": 4,
666
+ "codec": "json",
667
+ "compression": "gzip",
668
+ "merkleThreshold": 500,
669
+ "cdc": {
670
+ "minChunkSize": 8192,
671
+ "targetChunkSize": 32768,
672
+ "maxChunkSize": 131072
673
+ }
674
+ }
675
+ ```
676
+
677
+ ### Working Directory
678
+
679
+ By default the CLI operates in the current directory. Use `--cwd` to point at
680
+ a different repository:
681
+
682
+ ```bash
683
+ git cas store ./vacation.jpg --slug photos/vacation --cwd /path/to/assets-repo --tree
684
+ ```
685
+
686
+ ---
687
+
688
+ ## 8. Lifecycle Management
689
+
690
+ ### Reading a Manifest from a Tree
691
+
692
+ Given a tree OID (from a commit, tag, or ref), you can reconstruct the
693
+ manifest object with a single call:
694
+
695
+ ```js
696
+ const manifest = await cas.readManifest({ treeOid });
697
+
698
+ console.log(manifest.slug); // "photos/vacation"
699
+ console.log(manifest.chunks); // array of Chunk objects
700
+ ```
701
+
702
+ `readManifest` reads the tree, locates the manifest entry (for example
703
+ `manifest.json` or `manifest.cbor`), decodes it using the configured codec, and
704
+ returns a frozen, Zod-validated `Manifest`. If no manifest entry is found, it
705
+ throws `CasError('MANIFEST_NOT_FOUND')`.
706
+
707
+ ### Verifying Integrity Over Time
708
+
709
+ Stored assets can be verified at any time without restoring them. This is
710
+ useful for periodic integrity checks or auditing:
711
+
712
+ ```js
713
+ const ok = await cas.verifyIntegrity(manifest);
714
+ if (!ok) {
715
+ console.error(`Asset ${manifest.slug} has corrupted chunks`);
716
+ }
717
+ ```
718
+
719
+ The `verifyIntegrity` method reads each chunk blob from Git, recomputes its
720
+ SHA-256 digest, and compares it against the manifest. For encrypted content,
721
+ pass the same decryption credentials you would use for `restore()` so
722
+ `verifyIntegrity()` also authenticates the ciphertext instead of only hashing
723
+ the stored blobs:
724
+
725
+ ```js
726
+ const ok = await cas.verifyIntegrity(manifest, {
727
+ encryptionKey: key,
728
+ });
729
+ ```
730
+
731
+ If encrypted content is verified without credentials, `verifyIntegrity()`
732
+ returns `false`. With an observability adapter attached, it also emits
733
+ integrity metrics (see Section 9).
734
+
735
+ ### Inspecting an Asset
736
+
737
+ `inspectAsset` returns logical deletion metadata for an asset without
738
+ performing any destructive Git operations. The caller is responsible for
739
+ removing refs and running `git gc --prune` to reclaim space:
740
+
741
+ ```js
742
+ const { slug, chunksOrphaned } = await cas.inspectAsset({ treeOid });
743
+ console.log(`Asset "${slug}" has ${chunksOrphaned} chunks to clean up`);
744
+
745
+ // Remove the ref pointing to the tree, then:
746
+ // git gc --prune=now
747
+ ```
748
+
749
+ This is intentionally non-destructive: CAS never modifies or deletes Git
750
+ objects. It only tells you what would become unreachable.
751
+
752
+ > **Deprecation note:** `deleteAsset()` is a deprecated alias for
753
+ > `inspectAsset()`. It will be removed in a future major version.
754
+
755
+ ### Collecting Referenced Chunks
756
+
757
+ When you store the same file multiple times with different chunk sizes, or
758
+ store overlapping files, some chunk blobs may no longer be referenced by any
759
+ manifest. `collectReferencedChunks` aggregates all referenced chunk blob OIDs
760
+ across multiple assets:
761
+
762
+ ```js
763
+ const { referenced, total } = await cas.collectReferencedChunks({
764
+ treeOids: [treeOid1, treeOid2, treeOid3],
765
+ });
766
+ console.log(`${referenced.size} unique blobs across ${total} total chunk references`);
767
+ ```
768
+
769
+ If any `treeOid` lacks a manifest, the call throws
770
+ `CasError('MANIFEST_NOT_FOUND')` (fail closed). This is analysis only — no
771
+ objects are deleted or modified.
772
+
773
+ > **Deprecation note:** `findOrphanedChunks()` is a deprecated alias for
774
+ > `collectReferencedChunks()`. It will be removed in a future major version.
775
+
776
+ ### Working with Multiple Assets
777
+
778
+ A common pattern is to store multiple assets and assemble their trees into
779
+ a larger Git tree structure using standard Git plumbing:
780
+
781
+ ```js
782
+ const photoManifest = await cas.storeFile({
783
+ filePath: './vacation.jpg',
784
+ slug: 'photos/vacation',
785
+ });
786
+ const photoTree = await cas.createTree({ manifest: photoManifest });
787
+
788
+ const videoManifest = await cas.storeFile({
789
+ filePath: './clip.mp4',
790
+ slug: 'videos/clip',
791
+ });
792
+ const videoTree = await cas.createTree({ manifest: videoManifest });
793
+
794
+ // Now photoTree and videoTree are standard Git tree OIDs
795
+ // You can compose them into a parent tree, commit them, etc.
796
+ ```
797
+
798
+ ---
799
+
800
+ ## 9. Observability
801
+
802
+ `git-cas` now routes progress, integrity, and error signals through an
803
+ `ObservabilityPort`. If you want the older Node-style event workflow, attach an
804
+ `EventEmitterObserver` and listen on that adapter instead of subscribing
805
+ directly to `CasService`.
806
+
807
+ ### Available Events
808
+
809
+ | Event | Emitted When | Payload |
810
+ | ---------------- | -------------------------------------- | ---------------------------------------- |
811
+ | `chunk:stored` | A chunk is written to Git | `{ index, size, digest, blob }` |
812
+ | `chunk:restored` | A chunk is read back from Git | `{ index, size, digest }` |
813
+ | `file:stored` | All chunks for a file have been stored | `{ slug, size, chunkCount, encrypted }` |
814
+ | `file:restored` | A file has been fully restored | `{ slug, size, chunkCount }` |
815
+ | `integrity:pass` | All chunks pass integrity verification | `{ slug }` |
816
+ | `integrity:fail` | A chunk fails integrity verification | `{ slug, chunkIndex, expected, actual }` |
817
+ | `error` | An error occurs (guarded) | `{ code, message }` |
818
+
819
+ The `error` event is guarded: it is only emitted if there is at least one
820
+ listener attached. This preserves the old behavior that avoided unhandled
821
+ `error` event crashes.
822
+
823
+ ### Building a Progress Bar
824
+
825
+ ```js
826
+ import ContentAddressableStore, { EventEmitterObserver } from '@git-stunts/git-cas';
827
+
828
+ const observability = new EventEmitterObserver();
829
+ const cas = new ContentAddressableStore({ plumbing: git, observability });
830
+
831
+ let chunksStored = 0;
832
+ observability.on('chunk:stored', ({ index, size }) => {
833
+ chunksStored++;
834
+ console.log(` Stored chunk ${index} (${size} bytes)`);
835
+ });
836
+
837
+ observability.on('file:stored', ({ slug, size, chunkCount }) => {
838
+ console.log(`Finished: ${slug} -- ${size} bytes in ${chunkCount} chunks`);
839
+ });
840
+
841
+ // Now store -- events fire as chunks are written
842
+ const manifest = await cas.storeFile({
843
+ filePath: './vacation.jpg',
844
+ slug: 'photos/vacation',
845
+ });
846
+ ```
847
+
848
+ ### Monitoring Restores
849
+
850
+ ```js
851
+ observability.on('chunk:restored', ({ index, size, digest }) => {
852
+ console.log(` Restored chunk ${index} (${size} bytes, digest: ${digest.slice(0, 8)}...)`);
853
+ });
854
+
855
+ observability.on('file:restored', ({ slug, size, chunkCount }) => {
856
+ console.log(`Restored: ${slug} -- ${size} bytes from ${chunkCount} chunks`);
857
+ });
858
+
859
+ await cas.restoreFile({
860
+ manifest,
861
+ outputPath: './restored-vacation.jpg',
862
+ baseDirectory: process.cwd(),
863
+ });
864
+ ```
865
+
866
+ ### Logging Errors
867
+
868
+ ```js
869
+ observability.on('error', ({ code, message }) => {
870
+ console.error(`[CAS ERROR] ${code}: ${message}`);
871
+ });
872
+ ```
873
+
874
+ ### Integrity Monitoring
875
+
876
+ ```js
877
+ observability.on('integrity:pass', ({ slug }) => {
878
+ console.log(`Integrity OK: ${slug}`);
879
+ });
880
+
881
+ observability.on('integrity:fail', ({ slug, chunkIndex, expected, actual }) => {
882
+ console.error(`CORRUPT: ${slug} chunk ${chunkIndex}`);
883
+ console.error(` expected: ${expected}`);
884
+ console.error(` actual: ${actual}`);
885
+ });
886
+
887
+ await cas.verifyIntegrity(manifest);
888
+ ```
889
+
890
+ ---
891
+
892
+ ## 10. Compression
893
+
894
+ _New in v2.0.0._
895
+
896
+ `git-cas` supports optional gzip compression. When enabled, file content is
897
+ compressed before encryption (if any) and before chunking. This reduces storage
898
+ size for compressible data without changing the round-trip contract.
899
+
900
+ ### Storing with Compression
901
+
902
+ Pass the `compression` option when storing:
903
+
904
+ ```js
905
+ const manifest = await cas.storeFile({
906
+ filePath: './vacation.jpg',
907
+ slug: 'photos/vacation',
908
+ compression: { algorithm: 'gzip' },
909
+ });
910
+
911
+ console.log(manifest.compression);
912
+ // { algorithm: 'gzip' }
913
+ ```
914
+
915
+ The manifest gains an optional `compression` field recording the algorithm used.
916
+
917
+ ### Compression + Encryption
918
+
919
+ Compression and encryption compose naturally. Compression runs first (on
920
+ plaintext), then encryption runs on the compressed bytes:
921
+
922
+ ```js
923
+ const manifest = await cas.storeFile({
924
+ filePath: './data.csv',
925
+ slug: 'reports/q4',
926
+ compression: { algorithm: 'gzip' },
927
+ encryptionKey,
928
+ });
929
+ ```
930
+
931
+ ### Restoring Compressed Content
932
+
933
+ Decompression on `restore()` is automatic. If the manifest includes a
934
+ `compression` field, the restored bytes are decompressed after decryption
935
+ (if encrypted) and after chunk reassembly:
936
+
937
+ ```js
938
+ await cas.restoreFile({
939
+ manifest,
940
+ outputPath: './restored.csv',
941
+ baseDirectory: process.cwd(),
942
+ });
943
+ // restored.csv is byte-identical to the original data.csv
944
+ ```
945
+
946
+ ### When to Use Compression
947
+
948
+ Compression is most useful for text, CSV, JSON, XML, and other compressible
949
+ formats. For already-compressed data (JPEG, PNG, MP4, ZIP), compression adds
950
+ CPU cost without meaningful size reduction. Use your judgement.
951
+
952
+ ---
953
+
954
+ ## 11. Passphrase Encryption (KDF)
955
+
956
+ _New in v2.0.0._
957
+
958
+ Instead of managing raw 32-byte encryption keys, you can derive keys from
959
+ passphrases using standard key derivation functions (KDFs). `git-cas` supports
960
+ PBKDF2 (default) and scrypt.
961
+
962
+ ### Storing with a Passphrase
963
+
964
+ Pass `passphrase` instead of `encryptionKey`:
965
+
966
+ ```js
967
+ const manifest = await cas.storeFile({
968
+ filePath: './vacation.jpg',
969
+ slug: 'photos/vacation',
970
+ passphrase: 'my secret passphrase',
971
+ });
972
+
973
+ console.log(manifest.encryption.kdf);
974
+ // {
975
+ // algorithm: 'pbkdf2',
976
+ // salt: 'base64-encoded-salt',
977
+ // iterations: 600000,
978
+ // keyLength: 32
979
+ // }
980
+ ```
981
+
982
+ KDF parameters (salt, iterations, algorithm) are stored in the manifest's
983
+ `encryption.kdf` field. The salt is generated randomly for each store
984
+ operation.
985
+
986
+ ### Restoring with a Passphrase
987
+
988
+ Provide the same passphrase on restore. The KDF parameters in the manifest
989
+ are used to re-derive the key:
990
+
991
+ ```js
992
+ await cas.restoreFile({
993
+ manifest,
994
+ passphrase: 'my secret passphrase',
995
+ outputPath: './restored.jpg',
996
+ baseDirectory: process.cwd(),
997
+ });
998
+ ```
999
+
1000
+ A wrong passphrase produces a wrong key, which fails with `INTEGRITY_ERROR`
1001
+ (AES-256-GCM detects it).
1002
+
1003
+ ### Using scrypt
1004
+
1005
+ Pass `kdfOptions` to select scrypt:
1006
+
1007
+ ```js
1008
+ const manifest = await cas.storeFile({
1009
+ filePath: './secret.bin',
1010
+ slug: 'vault',
1011
+ passphrase: 'strong passphrase',
1012
+ kdfOptions: { algorithm: 'scrypt', cost: 131072 },
1013
+ });
1014
+ ```
1015
+
1016
+ ### Manual Key Derivation
1017
+
1018
+ For advanced workflows, derive the key yourself:
1019
+
1020
+ ```js
1021
+ const { key, salt, params } = await cas.deriveKey({
1022
+ passphrase: 'my secret passphrase',
1023
+ algorithm: 'pbkdf2',
1024
+ iterations: 600000,
1025
+ });
1026
+
1027
+ // Use the derived key directly
1028
+ const manifest = await cas.storeFile({
1029
+ filePath: './vacation.jpg',
1030
+ slug: 'photos/vacation',
1031
+ encryptionKey: key,
1032
+ });
1033
+ ```
1034
+
1035
+ ### Supported KDF Algorithms
1036
+
1037
+ | Algorithm | Default Params | Notes |
1038
+ | ------------------ | --------------------------- | ----------------------------------------- |
1039
+ | `pbkdf2` (default) | 600,000 iterations, SHA-512 | Stronger default, broadly portable |
1040
+ | `scrypt` | N=131072, r=8, p=1 | Memory-hard, stronger against GPU attacks |
1041
+
1042
+ Passphrase-bearing store, restore, vault init, and vault rotation now enforce
1043
+ a bounded KDF policy:
1044
+
1045
+ - new writes default to PBKDF2 `600000` or scrypt `N=131072`
1046
+ - stored manifest and vault metadata are accepted within a bounded
1047
+ compatibility window instead of trusting arbitrary repository-controlled
1048
+ values
1049
+ - out-of-policy values fail with `KDF_POLICY_VIOLATION` before expensive derive
1050
+ work begins
1051
+
1052
+ ---
1053
+
1054
+ ## 11b. Multi-Recipient Encryption & Key Rotation
1055
+
1056
+ _New in v5.1.0 (recipients), v5.2.0 (rotation)._
1057
+
1058
+ ### Envelope Encryption
1059
+
1060
+ Instead of encrypting with a single key, you can encrypt for multiple recipients. A random DEK encrypts the data; each recipient's KEK wraps the DEK:
1061
+
1062
+ ```javascript
1063
+ const manifest = await cas.store({
1064
+ source,
1065
+ slug: 'shared',
1066
+ filename: 'shared.bin',
1067
+ recipients: [
1068
+ { label: 'alice', key: aliceKey },
1069
+ { label: 'bob', key: bobKey },
1070
+ ],
1071
+ });
1072
+ ```
1073
+
1074
+ Any recipient can restore independently:
1075
+
1076
+ ```javascript
1077
+ const { buffer } = await cas.restore({ manifest, encryptionKey: bobKey });
1078
+ ```
1079
+
1080
+ ### Key Rotation
1081
+
1082
+ When a key is compromised, rotate it without re-encrypting data:
1083
+
1084
+ ```javascript
1085
+ const rotated = await cas.rotateKey({
1086
+ manifest,
1087
+ oldKey: aliceOldKey,
1088
+ newKey: aliceNewKey,
1089
+ label: 'alice',
1090
+ });
1091
+ // Persist the updated manifest
1092
+ const treeOid = await cas.createTree({ manifest: rotated });
1093
+ ```
1094
+
1095
+ The `keyVersion` counter increments with each rotation:
1096
+
1097
+ ```javascript
1098
+ console.log(rotated.encryption.keyVersion); // 1
1099
+ console.log(rotated.encryption.recipients[0].keyVersion); // 1
1100
+ ```
1101
+
1102
+ ### Vault Passphrase Rotation
1103
+
1104
+ Rotate the master passphrase for all vault entries at once:
1105
+
1106
+ ```javascript
1107
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase({
1108
+ oldPassphrase: 'old-secret',
1109
+ newPassphrase: 'new-secret',
1110
+ });
1111
+ ```
1112
+
1113
+ Non-envelope entries (direct-key encryption) are skipped — they require manual re-store.
1114
+
1115
+ ### CLI
1116
+
1117
+ ```bash
1118
+ # Rotate a single recipient's key
1119
+ git cas rotate --slug shared --old-key-file old.key --new-key-file new.key --label alice
1120
+
1121
+ # Rotate vault passphrase without exposing secrets in argv
1122
+ printf '%s\n' 'old-secret' > old-passphrase.txt
1123
+ printf '%s\n' 'new-secret' > new-passphrase.txt
1124
+ git cas vault rotate \
1125
+ --old-passphrase-file old-passphrase.txt \
1126
+ --new-passphrase-file new-passphrase.txt
1127
+ ```
1128
+
1129
+ ---
1130
+
1131
+ ## 12. Merkle Manifests
1132
+
1133
+ _New in v2.0.0._
1134
+
1135
+ When storing very large files, the manifest (which lists every chunk) can
1136
+ itself become large. Merkle manifests solve this by splitting the chunk list
1137
+ into sub-manifests, each stored as a separate Git blob. The root manifest
1138
+ references sub-manifests by OID.
1139
+
1140
+ ### How It Works
1141
+
1142
+ When the chunk count exceeds `merkleThreshold` (default: 1000), `git-cas`
1143
+ automatically:
1144
+
1145
+ 1. Groups chunks into sub-manifests (each containing up to `merkleThreshold`
1146
+ chunks).
1147
+ 2. Stores each sub-manifest as a Git blob.
1148
+ 3. Writes a root manifest with `version: 2` and a `subManifests` array
1149
+ referencing the sub-manifest blob OIDs.
1150
+
1151
+ ### Configuring the Threshold
1152
+
1153
+ Set `merkleThreshold` on the store operation that needs a different split
1154
+ point:
1155
+
1156
+ ```js
1157
+ const manifest = await cas.storeFile({
1158
+ filePath: './large-video.mov',
1159
+ slug: 'media/large-video',
1160
+ merkleThreshold: 500, // Per-operation override
1161
+ });
1162
+
1163
+ const treeOid = await cas.createTree({ manifest });
1164
+ ```
1165
+
1166
+ Constructor-level `merkleThreshold` remains the default for operations that do
1167
+ not provide an override:
1168
+
1169
+ ```js
1170
+ const cas = new ContentAddressableStore({
1171
+ plumbing: git,
1172
+ merkleThreshold: 500, // Split at 500 chunks instead of 1000
1173
+ });
1174
+ ```
1175
+
1176
+ ### Transparent Reconstitution
1177
+
1178
+ `readManifest()` transparently handles both v1 (flat) and v2 (Merkle)
1179
+ manifests. When it encounters a v2 manifest, it reads all sub-manifests,
1180
+ concatenates their chunk lists, and returns a flat `Manifest` object:
1181
+
1182
+ ```js
1183
+ const manifest = await cas.readManifest({ treeOid });
1184
+ // Works identically whether the manifest is v1 or v2
1185
+ console.log(manifest.chunks.length); // Full chunk list, regardless of structure
1186
+ ```
1187
+
1188
+ ### Backward Compatibility
1189
+
1190
+ - v2 code reads v1 manifests without any changes.
1191
+ - v1 manifests (chunk count below threshold) continue to use the flat format.
1192
+ - The `version` field defaults to `1` for existing manifests.
1193
+
1194
+ ---
1195
+
1196
+ ## 13. Vault
1197
+
1198
+ <img src="./vault.gif" alt="git-cas vault demo" />
1199
+
1200
+ When you call `createTree({ manifest })`, the resulting tree is a loose Git
1201
+ object. If nothing references it -- no commit, no tag, no ref -- `git gc`
1202
+ will garbage-collect it. This can silently lose stored data.
1203
+
1204
+ The vault solves this by maintaining a single Git ref (`refs/cas/vault`)
1205
+ pointing to a commit chain. The commit's tree indexes all stored assets by
1206
+ slug. One ref protects everything from GC, and `git log refs/cas/vault`
1207
+ gives you free history of every vault operation.
1208
+
1209
+ ### Vault Tree Structure
1210
+
1211
+ ```text
1212
+ refs/cas/vault → commit → tree
1213
+ ├── 100644 blob <oid> .vault.json
1214
+ ├── 040000 tree <oid> photos/vacation
1215
+ ├── 040000 tree <oid> models/v3-weights
1216
+ ```
1217
+
1218
+ The `.vault.json` blob contains versioned metadata. Without encryption:
1219
+ `{ "version": 1 }`. With encryption, it includes KDF configuration.
1220
+
1221
+ ### Initializing a Vault
1222
+
1223
+ ```js
1224
+ // Plain vault (no encryption)
1225
+ await cas.initVault();
1226
+
1227
+ // Vault with passphrase-based encryption
1228
+ await cas.initVault({
1229
+ passphrase: 'my vault passphrase',
1230
+ kdfOptions: { algorithm: 'pbkdf2' },
1231
+ });
1232
+ ```
1233
+
1234
+ When initialized with a passphrase, the vault generates a salt and stores
1235
+ the KDF parameters in `.vault.json`. The passphrase itself is never stored.
1236
+
1237
+ ### Adding Entries
1238
+
1239
+ ```js
1240
+ // Store a file and add it to the vault
1241
+ const manifest = await cas.storeFile({
1242
+ filePath: './vacation.jpg',
1243
+ slug: 'photos/vacation',
1244
+ });
1245
+ const treeOid = await cas.createTree({ manifest });
1246
+ await cas.addToVault({ slug: 'photos/vacation', treeOid });
1247
+ ```
1248
+
1249
+ If the vault does not exist yet, `addToVault` auto-initializes it with
1250
+ `{ version: 1 }` metadata (no encryption). If the slug already exists, it
1251
+ throws `VAULT_ENTRY_EXISTS` unless you pass `force: true`.
1252
+
1253
+ ### Listing and Resolving Entries
1254
+
1255
+ ```js
1256
+ // List all entries (sorted by slug)
1257
+ const entries = await cas.listVault();
1258
+ for (const { slug, treeOid } of entries) {
1259
+ console.log(`${slug}\t${treeOid}`);
1260
+ }
1261
+
1262
+ // Resolve a slug to its tree OID
1263
+ const treeOid = await cas.resolveVaultEntry({ slug: 'photos/vacation' });
1264
+ const manifest = await cas.readManifest({ treeOid });
1265
+ ```
1266
+
1267
+ ### Removing Entries
1268
+
1269
+ ```js
1270
+ const { removedTreeOid } = await cas.removeFromVault({ slug: 'photos/vacation' });
1271
+ ```
1272
+
1273
+ After removing the last entry, the vault remains (with an empty tree +
1274
+ `.vault.json`). The ref stays alive.
1275
+
1276
+ ### Vault-Level Encryption
1277
+
1278
+ When a vault is initialized with a passphrase, the CLI handles key
1279
+ derivation automatically:
1280
+
1281
+ ```bash
1282
+ export GIT_CAS_PASSPHRASE='secret'
1283
+
1284
+ # Initialize an encrypted vault
1285
+ git cas vault init
1286
+
1287
+ # Store with vault-level encryption (key derived from vault config)
1288
+ git cas store ./vacation.jpg --slug photos/vacation --tree
1289
+
1290
+ # Restore using vault slug
1291
+ git cas restore --slug photos/vacation --out ./restored.jpg
1292
+
1293
+ # Or pull the passphrase from stdin or the OS keychain
1294
+ printf '%s\n' 'secret' | git cas restore --slug photos/vacation --out ./restored.jpg --vault-passphrase-file -
1295
+ git cas restore --slug photos/vacation --out ./restored.jpg --os-keychain-target photos/passphrase
1296
+ ```
1297
+
1298
+ The vault stores the KDF policy (algorithm, salt, iterations). The actual
1299
+ encryption is still per-entry AES-256-GCM via the existing `store()`/`restore()`
1300
+ paths -- the vault just provides the key-derivation policy.
1301
+
1302
+ Encrypted v6 vault metadata also stores a small AES-GCM verifier. The verifier
1303
+ lets the CLI and agent reject a wrong vault passphrase before accepting writes
1304
+ to an otherwise empty encrypted vault. Older encrypted vaults that lack this
1305
+ field gain it on the next vault write that supplies the vault encryption key.
1306
+
1307
+ `--os-keychain-target` is a human CLI convenience implemented through
1308
+ `@git-stunts/vault`. It keeps the passphrase in OS-native secure storage while
1309
+ leaving the library API unchanged.
1310
+
1311
+ ### CLI Vault Commands
1312
+
1313
+ ```bash
1314
+ # Initialize vault (optionally with encryption)
1315
+ git cas vault init
1316
+ printf '%s\n' 'secret' | git cas vault init --vault-passphrase-file - --algorithm pbkdf2
1317
+ git cas vault init --os-keychain-target photos/passphrase
1318
+
1319
+ # List all vault entries (tab-separated slug + tree OID)
1320
+ git cas vault list
1321
+
1322
+ # Inspect a single entry
1323
+ git cas vault info photos/vacation
1324
+
1325
+ # Remove an entry
1326
+ git cas vault remove photos/vacation
1327
+
1328
+ # View vault commit history
1329
+ git cas vault history
1330
+ git cas vault history -n 10 # last 10 commits
1331
+
1332
+ # Diagnose vault health
1333
+ git cas doctor
1334
+ printf '%s\n' 'secret' | git cas doctor --vault-passphrase-file -
1335
+ ```
1336
+
1337
+ ### CLI Restore with Vault
1338
+
1339
+ The `restore` command now uses explicit flags instead of a positional argument:
1340
+
1341
+ ```bash
1342
+ # Restore from a vault slug
1343
+ git cas restore --slug photos/vacation --out ./restored.jpg
1344
+
1345
+ # Restore from a direct tree OID (existing behavior)
1346
+ git cas restore --oid a1b2c3d4... --out ./restored.jpg
1347
+ ```
1348
+
1349
+ ### GC Survival
1350
+
1351
+ Because `refs/cas/vault` points to a commit whose tree references all stored
1352
+ asset trees, every blob in the chain is reachable. `git gc --prune=now` will
1353
+ not touch any vault data:
1354
+
1355
+ ```bash
1356
+ git cas vault list # entries exist
1357
+ git gc --prune=now # aggressive garbage collection
1358
+ git cas vault list # entries still intact
1359
+ ```
1360
+
1361
+ ### Concurrent Write Safety
1362
+
1363
+ The vault uses compare-and-swap (CAS) semantics on `git update-ref`. If
1364
+ another process updates the vault between your read and write, the operation
1365
+ retries automatically (up to 3 times with exponential backoff). If all
1366
+ retries fail, a `VAULT_CONFLICT` error is thrown.
1367
+
1368
+ ### Slug Validation
1369
+
1370
+ Slugs are validated strictly:
1371
+
1372
+ - Must be a non-empty string
1373
+ - No leading/trailing `/`
1374
+ - No empty segments (`a//b`), `.`, or `..` segments
1375
+ - No control characters (NUL, tabs, newlines)
1376
+ - Each segment <= 255 bytes, total <= 1024 bytes
1377
+
1378
+ Invalid slugs throw `INVALID_SLUG`.
1379
+
1380
+ ---
1381
+
1382
+ ## 14. Architecture
1383
+
1384
+ `git-cas` follows a hexagonal (ports and adapters) architecture. The domain
1385
+ logic in `CasService` has zero direct dependencies on Node.js, Git, or any
1386
+ specific crypto library. All platform-specific behavior is injected through
1387
+ ports.
1388
+
1389
+ ### Layers
1390
+
1391
+ ```
1392
+ Facade (ContentAddressableStore)
1393
+ |
1394
+ +-- Domain Layer
1395
+ | +-- CasService (core logic)
1396
+ | +-- Manifest (value object, Zod-validated)
1397
+ | +-- Chunk (value object, Zod-validated)
1398
+ | +-- CasError (structured errors)
1399
+ | +-- ManifestSchema (Zod schemas)
1400
+ |
1401
+ +-- Ports (interfaces)
1402
+ | +-- GitPersistencePort (writeBlob, writeTree, readBlobStream, readBlob, readTree)
1403
+ | +-- CodecPort (encode, decode, extension)
1404
+ | +-- CryptoPort (sha256, randomBytes, AES-GCM, HMAC, KDF)
1405
+ | +-- ChunkingPort (chunk, strategy, params)
1406
+ | +-- CompressionPort (buffer + stream compression/decompression)
1407
+ | +-- ObservabilityPort (metric, log, span)
1408
+ |
1409
+ +-- Infrastructure (adapters)
1410
+ +-- GitPersistenceAdapter (Git plumbing commands)
1411
+ +-- JsonCodec (JSON serialization)
1412
+ +-- CborCodec (CBOR serialization)
1413
+ +-- NodeCryptoAdapter (node:crypto)
1414
+ +-- BunCryptoAdapter (Bun.CryptoHasher)
1415
+ +-- WebCryptoAdapter (crypto.subtle)
1416
+ +-- FixedChunker / CdcChunker
1417
+ +-- NodeCompressionAdapter
1418
+ +-- SilentObserver (no-op observability)
1419
+ +-- EventEmitterObserver (Node event bridge)
1420
+ +-- StatsCollector (metric accumulator)
1421
+ ```
1422
+
1423
+ ### Ports
1424
+
1425
+ Each port defines a contract that adapters are expected to satisfy. Some are
1426
+ exported directly from the package, while others are easiest to understand as
1427
+ method shapes rather than stable extension entrypoints.
1428
+
1429
+ **GitPersistencePort** -- the storage interface:
1430
+
1431
+ ```js
1432
+ class GitPersistencePort {
1433
+ async writeBlob(content) {} // Returns Git OID
1434
+ async writeTree(entries) {} // Returns tree OID
1435
+ async readBlobStream(oid) {} // Returns AsyncIterable<Uint8Array>
1436
+ async readBlob(oid) {} // Returns Uint8Array
1437
+ async readTree(treeOid) {} // Returns array of tree entries
1438
+ }
1439
+ ```
1440
+
1441
+ **CodecPort** -- the serialization interface:
1442
+
1443
+ ```js
1444
+ class CodecPort {
1445
+ encode(data) {} // Returns Uint8Array
1446
+ decode(buffer) {} // Returns object
1447
+ get extension() {} // Returns 'json', 'cbor', etc.
1448
+ }
1449
+ ```
1450
+
1451
+ **CryptoPort** -- the cryptographic operations interface:
1452
+
1453
+ ```js
1454
+ class CryptoPort {
1455
+ sha256(buf) {} // Returns hex digest
1456
+ randomBytes(n) {} // Returns Uint8Array
1457
+ encryptBuffer(buffer, key, aad) {} // Returns { buf, meta }
1458
+ decryptBuffer(buffer, key, meta, aad) {} // Returns Uint8Array
1459
+ createEncryptionStream(key) {} // Returns { encrypt, finalize }
1460
+ createDecryptionStream(key, meta) {} // Returns { decrypt }
1461
+ hmacSha256(key, data) {} // Returns Uint8Array
1462
+ encryptBufferWithNonce(buffer, key, nonce) {} // Returns { buf, tag }
1463
+ decryptBufferWithNonceTag(buffer, key, nonce, tag) {} // Returns Uint8Array
1464
+ deriveKey(options) {} // Returns { key, salt, params }
1465
+ }
1466
+ ```
1467
+
1468
+ ### Writing a Custom Persistence Adapter
1469
+
1470
+ To store chunks somewhere other than Git (for example S3, a database, or the
1471
+ local filesystem), implement the same persistence shape used by `CasService`:
1472
+
1473
+ ```js
1474
+ function concatUint8Arrays(chunks) {
1475
+ const size = chunks.reduce((total, chunk) => total + chunk.length, 0);
1476
+ const out = new Uint8Array(size);
1477
+ let offset = 0;
1478
+ for (const chunk of chunks) {
1479
+ out.set(chunk, offset);
1480
+ offset += chunk.length;
1481
+ }
1482
+ return out;
1483
+ }
1484
+
1485
+ class S3PersistenceAdapter {
1486
+ async writeBlob(content) {
1487
+ const hash = computeHash(content);
1488
+ await s3.putObject({ Key: hash, Body: content });
1489
+ return hash;
1490
+ }
1491
+
1492
+ async *readBlobStream(oid) {
1493
+ const response = await s3.getObject({ Key: oid });
1494
+ for await (const chunk of response.Body) {
1495
+ yield chunk instanceof Uint8Array ? chunk : new Uint8Array(chunk);
1496
+ }
1497
+ }
1498
+
1499
+ async readBlob(oid) {
1500
+ const chunks = [];
1501
+ for await (const chunk of await this.readBlobStream(oid)) {
1502
+ chunks.push(chunk);
1503
+ }
1504
+ return concatUint8Arrays(chunks);
1505
+ }
1506
+
1507
+ async writeTree(entries) {
1508
+ // Implement tree assembly for your storage backend
1509
+ }
1510
+
1511
+ async readTree(treeOid) {
1512
+ // Implement tree reading for your storage backend
1513
+ }
1514
+ }
1515
+ ```
1516
+
1517
+ Then inject it:
1518
+
1519
+ ```js
1520
+ import {
1521
+ CasService,
1522
+ FixedChunker,
1523
+ JsonCodec,
1524
+ NodeCompressionAdapter,
1525
+ NodeCryptoAdapter,
1526
+ SilentObserver,
1527
+ } from '@git-stunts/git-cas';
1528
+
1529
+ const service = new CasService({
1530
+ persistence: new S3PersistenceAdapter(),
1531
+ codec: new JsonCodec(),
1532
+ crypto: new NodeCryptoAdapter(),
1533
+ observability: new SilentObserver(),
1534
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
1535
+ compressionAdapter: new NodeCompressionAdapter(),
1536
+ });
1537
+ ```
1538
+
1539
+ ### Resilience Policy
1540
+
1541
+ The `GitPersistenceAdapter` wraps every Git command in a resilience policy
1542
+ (provided by `@git-stunts/alfred`). The default policy is a 30-second timeout
1543
+ wrapping an exponential-backoff retry (2 retries, 100ms initial delay, 2s max
1544
+ delay). You can override this:
1545
+
1546
+ ```js
1547
+ import { Policy } from '@git-stunts/alfred';
1548
+
1549
+ const cas = new ContentAddressableStore({
1550
+ plumbing: git,
1551
+ policy: Policy.timeout(60_000).wrap(
1552
+ Policy.retry({ retries: 5, backoff: 'exponential', delay: 200 })
1553
+ ),
1554
+ });
1555
+ ```
1556
+
1557
+ ---
1558
+
1559
+ ## 15. Codec System
1560
+
1561
+ ### JSON Codec
1562
+
1563
+ The default codec. Produces human-readable manifest files with pretty-printed
1564
+ indentation.
1565
+
1566
+ ```js
1567
+ import { JsonCodec } from '@git-stunts/git-cas';
1568
+
1569
+ const codec = new JsonCodec();
1570
+ const encoded = codec.encode({ slug: 'photos/vacation', chunks: [] });
1571
+ // '{\n "slug": "photos/vacation",\n "chunks": []\n}'
1572
+
1573
+ codec.extension; // 'json'
1574
+ ```
1575
+
1576
+ Manifests are stored in the tree as `manifest.json`.
1577
+
1578
+ ### CBOR Codec
1579
+
1580
+ A binary codec that produces smaller manifests. Useful when you are storing
1581
+ many assets and want to minimize overhead, or when the manifest does not
1582
+ need to be human-readable.
1583
+
1584
+ ```js
1585
+ import { CborCodec } from '@git-stunts/git-cas';
1586
+
1587
+ const cas = new ContentAddressableStore({
1588
+ plumbing: git,
1589
+ codec: new CborCodec(),
1590
+ });
1591
+
1592
+ // Or use the factory method:
1593
+ const cas2 = ContentAddressableStore.createCbor({ plumbing: git });
1594
+ ```
1595
+
1596
+ Manifests are stored in the tree as `manifest.cbor`.
1597
+
1598
+ ### When to Use Which
1599
+
1600
+ | Consideration | JSON | CBOR |
1601
+ | ----------------- | --------------- | ---------------- |
1602
+ | Human-readable | Yes | No |
1603
+ | Manifest size | Larger | Smaller |
1604
+ | Debugging ease | Easy to inspect | Requires tooling |
1605
+ | Parse performance | Good | Slightly better |
1606
+ | Default | Yes | No |
1607
+
1608
+ For most use cases, JSON is the right choice. Switch to CBOR if you are
1609
+ storing thousands of assets and the manifest size difference matters, or if
1610
+ you are in a pipeline where human readability is irrelevant.
1611
+
1612
+ ### Implementing a Custom Codec
1613
+
1614
+ To implement your own codec (for example MessagePack or Protobuf), provide the
1615
+ same method shape that the built-in codecs use:
1616
+
1617
+ ```js
1618
+ import msgpack from 'msgpack-lite';
1619
+
1620
+ class MsgPackCodec {
1621
+ encode(data) {
1622
+ return msgpack.encode(data);
1623
+ }
1624
+
1625
+ decode(buffer) {
1626
+ return msgpack.decode(buffer);
1627
+ }
1628
+
1629
+ get extension() {
1630
+ return 'msgpack';
1631
+ }
1632
+ }
1633
+ ```
1634
+
1635
+ Then pass it to the constructor:
1636
+
1637
+ ```js
1638
+ const cas = new ContentAddressableStore({
1639
+ plumbing: git,
1640
+ codec: new MsgPackCodec(),
1641
+ });
1642
+ ```
1643
+
1644
+ The manifest will be stored in the tree as `manifest.msgpack`.
1645
+
1646
+ ---
1647
+
1648
+ ## 16. Error Handling
1649
+
1650
+ All errors thrown by `git-cas` are instances of `CasError`, which extends
1651
+ `Error` with two additional properties:
1652
+
1653
+ - `code` -- a machine-readable string identifier
1654
+ - `meta` -- an object with additional context
1655
+
1656
+ ### Error Codes Reference
1657
+
1658
+ | Code | Meaning | Typical `meta` |
1659
+ | -------------------- | ------------------------------------------------ | --------------------------------------------------------- |
1660
+ | `INVALID_KEY_TYPE` | Encryption key is not a Uint8Array-compatible value | -- |
1661
+ | `INVALID_KEY_LENGTH` | Encryption key is not 32 bytes | `{ expected: 32, actual: N }` |
1662
+ | `MISSING_KEY` | Encrypted content restored without a key | -- |
1663
+ | `INTEGRITY_ERROR` | Chunk digest mismatch or decryption auth failure | `{ chunkIndex, expected, actual }` or `{ originalError }` |
1664
+ | `PERSISTENCE_CAPABILITY_REQUIRED` | Buffered restore requires `readBlobStream()` so `maxRestoreBufferSize` can be enforced with memory-safe reads | `{ capability, mode, oid, docs }` |
1665
+ | `KDF_POLICY_VIOLATION` | KDF parameters fell outside the accepted policy | `{ source, field, value, min?, max?, expected? }` |
1666
+ | `STREAM_ERROR` | Error reading from source stream during store | `{ chunksDispatched, orphanedBlobs, originalError }` |
1667
+ | `STORE_ERROR` | Error writing a dispatched chunk during store | `{ chunksDispatched, orphanedBlobs, failedIndex, originalError }` |
1668
+ | `TREE_PARSE_ERROR` | Malformed `ls-tree` output from Git | `{ rawEntry }` |
1669
+
1670
+ ### Catching and Handling Errors
1671
+
1672
+ ```js
1673
+ try {
1674
+ await cas.restoreFile({
1675
+ manifest,
1676
+ outputPath: './restored.jpg',
1677
+ baseDirectory: process.cwd(),
1678
+ // Oops, forgot the encryption key
1679
+ });
1680
+ } catch (err) {
1681
+ if (err.code === 'MISSING_KEY') {
1682
+ console.error('This asset is encrypted. Please provide the encryption key.');
1683
+ } else if (err.code === 'INTEGRITY_ERROR') {
1684
+ console.error('Data corruption detected:', err.meta);
1685
+ } else {
1686
+ throw err; // unexpected error, re-throw
1687
+ }
1688
+ }
1689
+ ```
1690
+
1691
+ ### Structured Error Pattern
1692
+
1693
+ Because every `CasError` has a `code`, you can build exhaustive error
1694
+ handlers:
1695
+
1696
+ ```js
1697
+ function handleCasError(err) {
1698
+ switch (err.code) {
1699
+ case 'INVALID_KEY_TYPE':
1700
+ case 'INVALID_KEY_LENGTH':
1701
+ return { status: 400, message: 'Invalid encryption key' };
1702
+ case 'MISSING_KEY':
1703
+ return { status: 401, message: 'Encryption key required' };
1704
+ case 'INTEGRITY_ERROR':
1705
+ return { status: 500, message: 'Data integrity check failed' };
1706
+ case 'STREAM_ERROR':
1707
+ return { status: 502, message: `Stream failed after ${err.meta.chunksDispatched} dispatched chunks` };
1708
+ case 'STORE_ERROR':
1709
+ return { status: 502, message: `Chunk write failed after ${err.meta.chunksDispatched} dispatched chunks` };
1710
+ case 'TREE_PARSE_ERROR':
1711
+ return { status: 500, message: 'Corrupted Git tree' };
1712
+ default:
1713
+ return { status: 500, message: err.message };
1714
+ }
1715
+ }
1716
+ ```
1717
+
1718
+ ### Manifest Validation Errors
1719
+
1720
+ Constructing a `Manifest` or `Chunk` with invalid data throws a plain `Error`
1721
+ (not a `CasError`) with a descriptive message from Zod validation:
1722
+
1723
+ ```js
1724
+ import { Manifest } from '@git-stunts/git-cas';
1725
+
1726
+ try {
1727
+ new Manifest({ slug: '', filename: 'test.jpg', size: 0, chunks: [] });
1728
+ } catch (err) {
1729
+ // Error: Invalid manifest data: String must contain at least 1 character(s)
1730
+ }
1731
+ ```
1732
+
1733
+ ---
1734
+
1735
+ ## 17. FAQ / Troubleshooting
1736
+
1737
+ ### Q: Does this work with bare repositories?
1738
+
1739
+ Yes. `git-cas` uses Git plumbing commands (`hash-object`, `mktree`, `cat-file`,
1740
+ `ls-tree`) that work identically in bare and non-bare repositories. Point
1741
+ `GitPlumbing` at the bare repo path.
1742
+
1743
+ ### Q: What happens if I store the same file twice?
1744
+
1745
+ You get two manifests, but Git deduplicates the underlying blobs. If the file
1746
+ content has not changed, the blob OIDs will be identical. You are not wasting
1747
+ storage.
1748
+
1749
+ ### Q: Can I change the chunk size after storing?
1750
+
1751
+ Yes, but the new store will produce different chunks and different blob OIDs.
1752
+ The old manifest remains valid -- its chunks are still in Git. You will have
1753
+ two sets of blobs: one for each chunk size.
1754
+
1755
+ ### Q: Is the encryption key stored anywhere?
1756
+
1757
+ No. The manifest stores only the algorithm, nonce, and authentication tag.
1758
+ The key is never stored in Git. If you lose the key, you cannot decrypt the
1759
+ content. Treat your key files like any other secret.
1760
+
1761
+ ### Q: What encryption algorithm is used?
1762
+
1763
+ AES-256-GCM (Galois/Counter Mode). This is an authenticated encryption
1764
+ algorithm -- it provides both confidentiality and integrity. The authentication
1765
+ tag in the manifest ensures that any tampering with the ciphertext is detected
1766
+ during decryption.
1767
+
1768
+ ### Q: Can I use this with Bun or Deno?
1769
+
1770
+ Yes. `git-cas` includes runtime detection that automatically selects the
1771
+ appropriate crypto adapter:
1772
+
1773
+ - **Node.js**: `NodeCryptoAdapter` (uses `node:crypto`)
1774
+ - **Bun**: `BunCryptoAdapter` (uses `Bun.CryptoHasher`)
1775
+ - **Deno**: `WebCryptoAdapter` (uses `crypto.subtle`)
1776
+
1777
+ Runtime truth: `framed` is the streaming-encrypted mode across all of these.
1778
+ For `whole`, Node and Bun provide the stronger low-memory file-restore path,
1779
+ while Deno/Web Crypto remains bounded-buffer because AES-GCM decrypt is still a
1780
+ one-shot operation there.
1781
+
1782
+ ### Q: How do I commit a tree OID?
1783
+
1784
+ Use standard Git plumbing:
1785
+
1786
+ ```bash
1787
+ TREE_OID=$(git cas store ./vacation.jpg --slug photos/vacation --tree)
1788
+ COMMIT_OID=$(git commit-tree "$TREE_OID" -m "Store vacation.jpg")
1789
+ git update-ref refs/heads/assets "$COMMIT_OID"
1790
+ ```
1791
+
1792
+ ### Q: What is the maximum file size?
1793
+
1794
+ There is no hard limit imposed by `git-cas`. The practical limit is determined
1795
+ by your Git repository's object database and available memory.
1796
+
1797
+ Plaintext restore can stream chunk-by-chunk, so memory usage is close to
1798
+ `chunkSize` plus normal I/O overhead. On modern persistence adapters that means
1799
+ chunk blobs can be read through `readBlobStream()` instead of forcing an early
1800
+ adapter-level materialization. `framed`, `convergent`, and gzip restore paths
1801
+ stream through their authentication/decompression stages; `whole` preserves its
1802
+ whole-object authentication boundary and is bounded by `maxRestoreBufferSize`
1803
+ (default 512 MiB). Custom persistence adapters must implement
1804
+ `readBlobStream()` to get the hard-limited streaming and bounded restore
1805
+ guarantees.
1806
+
1807
+ ### Q: I get "Chunk size must be an integer >= 1024 bytes"
1808
+
1809
+ The minimum chunk size is 1 KiB. This prevents pathologically small chunks
1810
+ that would create excessive Git objects. Increase your `chunkSize` parameter.
1811
+
1812
+ There is also a hard cap at 100 MiB — values above this are rejected outright.
1813
+ Setting `chunkSize` above 10 MiB will trigger a warning, since very large
1814
+ chunks reduce deduplication benefit and increase memory pressure.
1815
+
1816
+ ### Q: I get "Encryption key must be 32 bytes, got N"
1817
+
1818
+ AES-256 requires exactly a 256-bit (32-byte) key. Ensure your key file
1819
+ contains exactly 32 raw bytes. A common mistake is to store the key as a
1820
+ hex string (64 characters) rather than raw bytes.
1821
+
1822
+ ```bash
1823
+ # Correct: 32 raw bytes
1824
+ openssl rand -out my.key 32
1825
+
1826
+ # Wrong: this creates a hex-encoded file (64 bytes of ASCII)
1827
+ openssl rand -hex 32 > my.key
1828
+ ```
1829
+
1830
+ ### Q: The manifest JSON contains "blob" OIDs -- what are those?
1831
+
1832
+ The `blob` field in each chunk is the Git SHA-1 OID returned by
1833
+ `git hash-object -w`. It is the address of that chunk in Git's object
1834
+ database. You can inspect any chunk directly:
1835
+
1836
+ ```bash
1837
+ git cat-file blob <blob-oid> | sha256sum
1838
+ ```
1839
+
1840
+ The output should match the `digest` field in the manifest.
1841
+
1842
+ ### Q: Can I use git-cas in a CI/CD pipeline?
1843
+
1844
+ Yes. A typical pattern:
1845
+
1846
+ ```bash
1847
+ # In your build step:
1848
+ TREE=$(git cas store ./dist/artifact.tar.gz --slug builds/latest --tree)
1849
+ git commit-tree "$TREE" -p HEAD -m "Build $(date +%s)" | xargs git update-ref refs/builds/latest
1850
+ git push origin refs/builds/latest
1851
+
1852
+ # In your deploy step:
1853
+ git fetch origin refs/builds/latest
1854
+ TREE=$(git log -1 --format='%T' FETCH_HEAD)
1855
+ git cas restore --oid "$TREE" --out ./artifact.tar.gz
1856
+ ```
1857
+
1858
+ ### Q: How does the resilience policy work?
1859
+
1860
+ Every Git plumbing command is wrapped in a policy from `@git-stunts/alfred`.
1861
+ The default policy applies a 30-second timeout and retries up to 2 times with
1862
+ exponential backoff (100ms, then up to 2s). This handles transient filesystem
1863
+ errors and lock contention gracefully. You can override the policy at
1864
+ construction time (see Section 14).
1865
+
1866
+ ---
1867
+
1868
+ _Copyright 2026 James Ross. Licensed under Apache-2.0._