@git-stunts/git-cas 5.3.1 → 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 (174) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +401 -4
  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 +72 -20
  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 +604 -450
  20. package/bin/io.js +86 -0
  21. package/bin/passphrase-source.js +266 -0
  22. package/bin/restore-output-target.js +28 -0
  23. package/bin/ui/blocks/asset-card.js +109 -0
  24. package/bin/ui/blocks/health-dashboard.js +149 -0
  25. package/bin/ui/blocks/heatmap-block.js +67 -0
  26. package/bin/ui/blocks/merkle-explorer.js +163 -0
  27. package/bin/ui/blocks/operation-feed.js +176 -0
  28. package/bin/ui/blocks/wizard-block.js +168 -0
  29. package/bin/ui/components/short-sha.js +36 -0
  30. package/bin/ui/context.js +56 -1
  31. package/bin/ui/dashboard-cmds.js +1578 -13
  32. package/bin/ui/dashboard-view.js +612 -145
  33. package/bin/ui/dashboard.js +998 -214
  34. package/bin/ui/encryption-card.js +69 -26
  35. package/bin/ui/heatmap.js +26 -54
  36. package/bin/ui/history-timeline.js +51 -19
  37. package/bin/ui/manifest-view.js +115 -60
  38. package/bin/ui/merkle-dag.js +83 -0
  39. package/bin/ui/progress.js +15 -9
  40. package/bin/ui/repo-treemap.js +328 -0
  41. package/bin/ui/shaders/bak-sneppen.js +180 -0
  42. package/bin/ui/shaders/fractal-zoom.js +99 -0
  43. package/bin/ui/shaders/merkle-tree.js +142 -0
  44. package/bin/ui/shaders/organic-flow.js +96 -0
  45. package/bin/ui/shaders/phase-portrait.js +93 -0
  46. package/bin/ui/store-wizard.js +296 -0
  47. package/bin/ui/theme.js +155 -0
  48. package/bin/ui/vault-report.js +495 -0
  49. package/build-info.json +4 -0
  50. package/docs/API.md +2224 -0
  51. package/docs/ENCRYPTION_MODES.md +33 -0
  52. package/docs/EXTENDING.md +174 -0
  53. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  54. package/docs/THREAT_MODEL.md +269 -0
  55. package/docs/VAULT_INTERNALS.md +251 -0
  56. package/docs/WALKTHROUGH.md +1868 -0
  57. package/docs/demo.gif +0 -0
  58. package/docs/releases/v6.0.0.md +104 -0
  59. package/examples/README.md +260 -0
  60. package/index.d.ts +208 -65
  61. package/index.js +163 -54
  62. package/package.json +35 -6
  63. package/scripts/migrate-encryption.js +680 -0
  64. package/src/domain/bytes/ByteLayout.js +96 -0
  65. package/src/domain/encoding/base64.js +91 -0
  66. package/src/domain/encoding/hex.js +14 -0
  67. package/src/domain/encoding/utf8.js +123 -0
  68. package/src/domain/encryption/schemes.js +132 -0
  69. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  70. package/src/domain/errors/CasError.d.ts +28 -0
  71. package/src/domain/errors/CasError.js +43 -6
  72. package/src/domain/errors/Codes.js +54 -0
  73. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  74. package/src/domain/errors/GitError.js +10 -0
  75. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  76. package/src/domain/errors/IntegrityError.js +10 -0
  77. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  78. package/src/domain/errors/InvalidOidError.js +10 -0
  79. package/src/domain/errors/InvalidOptionsError.js +10 -0
  80. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  81. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  82. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  83. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  84. package/src/domain/errors/PortNotImplementedError.js +10 -0
  85. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  86. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  87. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  88. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  89. package/src/domain/errors/createCasError.js +68 -0
  90. package/src/domain/errors/index.js +20 -0
  91. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  92. package/src/domain/helpers/codecBytes.js +34 -0
  93. package/src/domain/helpers/gitRefErrors.js +84 -0
  94. package/src/domain/helpers/scryptMaxmem.js +22 -0
  95. package/src/domain/outcomes/RestoreFailure.js +15 -0
  96. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  97. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  98. package/src/domain/outcomes/StoreFailure.js +15 -0
  99. package/src/domain/outcomes/StoreOutcome.js +11 -0
  100. package/src/domain/outcomes/StoreSuccess.js +17 -0
  101. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  102. package/src/domain/schemas/ManifestSchema.js +67 -13
  103. package/src/domain/services/CasService.d.ts +123 -38
  104. package/src/domain/services/CasService.js +298 -834
  105. package/src/domain/services/ChunkRepository.js +230 -0
  106. package/src/domain/services/CompressionStreams.js +72 -0
  107. package/src/domain/services/ConvergentEncryption.js +128 -0
  108. package/src/domain/services/GitTreeBuilder.js +86 -0
  109. package/src/domain/services/IntegrityVerifier.js +199 -0
  110. package/src/domain/services/KeyResolver.js +49 -42
  111. package/src/domain/services/ManifestDiff.js +56 -0
  112. package/src/domain/services/ManifestRepository.js +286 -0
  113. package/src/domain/services/PrefetchWindow.js +48 -0
  114. package/src/domain/services/RecipientService.js +157 -0
  115. package/src/domain/services/RedactingObservability.js +169 -0
  116. package/src/domain/services/RestorePipeline.js +68 -0
  117. package/src/domain/services/StorePipeline.js +201 -0
  118. package/src/domain/services/VaultKeyVerifier.js +101 -0
  119. package/src/domain/services/VaultMetadataCodec.js +206 -0
  120. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  121. package/src/domain/services/VaultPersistence.js +410 -0
  122. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  123. package/src/domain/services/VaultService.js +749 -251
  124. package/src/domain/services/VaultStateCache.js +225 -0
  125. package/src/domain/services/VaultTreeCodec.js +121 -0
  126. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  127. package/src/domain/strategies/Aad.js +39 -0
  128. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  129. package/src/domain/strategies/RestoreCompressed.js +40 -0
  130. package/src/domain/strategies/RestoreConvergent.js +44 -0
  131. package/src/domain/strategies/RestoreFramed.js +55 -0
  132. package/src/domain/strategies/RestorePlain.js +37 -0
  133. package/src/domain/strategies/RestoreStrategy.js +35 -0
  134. package/src/domain/strategies/RestoreWhole.js +135 -0
  135. package/src/domain/strategies/StoreConvergent.js +28 -0
  136. package/src/domain/strategies/StoreFramed.js +39 -0
  137. package/src/domain/strategies/StorePlain.js +20 -0
  138. package/src/domain/strategies/StoreStrategy.js +61 -0
  139. package/src/domain/strategies/StoreWhole.js +34 -0
  140. package/src/domain/value-objects/Chunk.js +1 -2
  141. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  142. package/src/domain/value-objects/Manifest.d.ts +40 -4
  143. package/src/domain/value-objects/Manifest.js +61 -20
  144. package/src/domain/value-objects/Oid.js +45 -0
  145. package/src/domain/value-objects/Slug.js +124 -0
  146. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  147. package/src/helpers/aesGcmMeta.js +55 -0
  148. package/src/helpers/canonicalBase64.js +1 -0
  149. package/src/helpers/kdfPolicy.js +194 -0
  150. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  151. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  152. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  153. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  154. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  155. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  156. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  157. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  158. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  159. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  160. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  161. package/src/infrastructure/codecs/CborCodec.js +3 -3
  162. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  163. package/src/infrastructure/createGitPlumbing.js +22 -0
  164. package/src/package-version.js +1 -0
  165. package/src/ports/ChunkingPort.js +3 -3
  166. package/src/ports/CodecPort.js +4 -4
  167. package/src/ports/CompressionPort.js +57 -0
  168. package/src/ports/CryptoPort.js +138 -50
  169. package/src/ports/GitPersistencePort.js +32 -2
  170. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  171. package/src/ports/GitRefPort.js +1 -1
  172. package/src/types/ambient.d.ts +10 -5
  173. package/test/CONVENTIONS.md +94 -0
  174. package/test/cycles/README.md +13 -0
package/SECURITY.md ADDED
@@ -0,0 +1,993 @@
1
+ # Security Model
2
+
3
+ This document describes the security architecture, cryptographic design, and limitations of git-cas's content-addressable storage system with optional encryption.
4
+
5
+ For explicit attacker models, trust boundaries, protected assets, exposed
6
+ metadata, and non-goals, see [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md).
7
+
8
+ ## Table of Contents
9
+
10
+ 1. [Reporting Vulnerabilities](#reporting-vulnerabilities)
11
+ 2. [Operational Limits](#operational-limits)
12
+ 3. [Threat Model](#threat-model)
13
+ 4. [Cryptographic Design](#cryptographic-design)
14
+ 5. [Key Handling](#key-handling)
15
+ 6. [Encryption Flow](#encryption-flow)
16
+ 7. [Decryption Flow](#decryption-flow)
17
+ 8. [Chunk Digest Verification](#chunk-digest-verification)
18
+ 9. [Limitations](#limitations)
19
+ 10. [Git Object Immutability](#git-object-immutability)
20
+ 11. [Error Codes for Security Operations](#error-codes-for-security-operations)
21
+
22
+ ---
23
+
24
+ ## Reporting Vulnerabilities
25
+
26
+ Do not open public issues for suspected vulnerabilities. Email
27
+ [James Ross](mailto:james@flyingrobots.dev) with:
28
+
29
+ - affected `git-cas` version or commit
30
+ - runtime and operating system
31
+ - minimal reproduction or exploit sketch
32
+ - expected impact and affected workflows
33
+ - known mitigations or workarounds, if any
34
+
35
+ The maintainer will acknowledge valid private reports as capacity allows and
36
+ will coordinate disclosure timing before public issue or release-note details
37
+ are posted.
38
+
39
+ ---
40
+
41
+ ## Operational Limits
42
+
43
+ ### GCM Nonce Bound
44
+
45
+ AES-256-GCM uses a 96-bit random nonce per encryption. NIST SP 800-38D recommends limiting to **2^32 invocations per key** to keep the nonce collision probability below an acceptable threshold. The birthday bound is approximately 2^48 for random 96-bit nonces, but the conservative NIST guidance of 2^32 accounts for the catastrophic consequences of a collision (full plaintext and authentication key recovery).
46
+
47
+ git-cas tracks encryption operations via `encryptionCount` in vault metadata. When the count exceeds **2^31** (2,147,483,648), an observability warning is emitted, providing a safety margin before the 2^32 NIST limit.
48
+
49
+ **Recommended key rotation frequency**: Rotate the vault passphrase (or encryption key) before `encryptionCount` reaches 2^31, or every 90 days, whichever comes first.
50
+
51
+ ### Vault Passphrase Verification
52
+
53
+ Encrypted vaults store an AES-GCM verifier in `.vault.json`. When a caller
54
+ derives a vault key from a passphrase and provides it to `readState()`,
55
+ `verifyVaultKey()`, CLI store/restore flows, agent store/restore flows, or vault
56
+ passphrase rotation, git-cas authenticates that key before accepting it.
57
+
58
+ This closes the empty-vault ambiguity: a wrong passphrase now fails with
59
+ `INTEGRITY_ERROR` before a new encrypted vault entry can be added. Existing
60
+ encrypted vaults that predate the verifier remain readable; the next vault write
61
+ that supplies a vault encryption key writes verifier metadata for future checks.
62
+
63
+ ### Restore Path Boundary
64
+
65
+ `restoreFile()` requires `baseDirectory` and treats it as the caller-approved
66
+ write boundary. The requested `outputPath` is resolved against that boundary and
67
+ then checked with canonical `realpath` containment over existing path
68
+ components. Symlinked directories therefore cannot redirect stream or
69
+ bounded-file restores outside the boundary. If the resolved path escapes the
70
+ boundary, restore fails with `SECURITY_BOUNDARY_VIOLATION` before publishing
71
+ any output.
72
+
73
+ For local trusted scripts and CLIs, `baseDirectory: process.cwd()` is often the
74
+ right boundary. Services and automation should pass an application-owned
75
+ workspace, job directory, or tenant-scoped restore root instead of trusting
76
+ ambient process state.
77
+
78
+ ### Metadata Blob Size Boundary
79
+
80
+ Manifest and sub-manifest reads use `readBlob()` and are capped by
81
+ `maxBlobSize`, which defaults to 10 MiB. This bounds repository-controlled
82
+ metadata before the codec or manifest schema processes it. Normal content
83
+ restore still reads chunk blobs through streaming paths where available, and
84
+ buffered restore modes remain separately bounded by `maxRestoreBufferSize`.
85
+
86
+ ### KDF Parameter Guidance
87
+
88
+ When using passphrase-based encryption, git-cas derives keys using PBKDF2 or scrypt.
89
+
90
+ | Algorithm | Default Parameters | Notes |
91
+ | --------- | ---------------------------- | ------------------------------------- |
92
+ | PBKDF2 | 600,000 iterations (SHA-512) | Stronger default, broadly portable |
93
+ | scrypt | N=2^17, r=8, p=1 | ~128 MiB memory, stronger GPU posture |
94
+
95
+ Higher iteration counts / cost parameters increase resistance to brute-force attacks but also increase the time to derive a key. Choose parameters based on your threat model and latency tolerance.
96
+
97
+ PBKDF2 works across the shipped Node, Bun, and Web Crypto adapters. scrypt
98
+ requires a Node/Bun-compatible crypto adapter; Web Crypto runtimes, including
99
+ the Deno adapter, report an explicit capability error for scrypt.
100
+
101
+ git-cas now also applies a bounded KDF policy to passphrase-bearing store,
102
+ restore, vault init, and vault rotation flows:
103
+
104
+ - new writes default to PBKDF2 `600000` or scrypt `N=131072`
105
+ - supported KDF algorithms are explicitly limited to `pbkdf2` and `scrypt`
106
+ - stored manifest and vault metadata are accepted only within a bounded
107
+ compatibility window
108
+ - out-of-policy KDF metadata fails with `KDF_POLICY_VIOLATION` before derive
109
+ work begins
110
+
111
+ Current acceptance window:
112
+
113
+ | Field | Accepted Range |
114
+ | ----- | -------------- |
115
+ | PBKDF2 `iterations` | `100000` to `2000000` |
116
+ | scrypt `cost` (`N`) | `16384` to `1048576`, power of two |
117
+ | scrypt `blockSize` (`r`) | `8` to `32` |
118
+ | scrypt `parallelization` (`p`) | `1` to `16` |
119
+ | `keyLength` | exactly `32` |
120
+
121
+ ### Passphrase Entropy Recommendations
122
+
123
+ | Entropy (bits) | Example | Brute-Force Resistance |
124
+ | -------------- | -------------------------------------------------- | ------------------------ |
125
+ | < 40 | `password123` | Trivially crackable |
126
+ | 40–60 | 4–5 random dictionary words | Weak against GPU attacks |
127
+ | 60–80 | 6+ random dictionary words or 12+ mixed characters | Moderate |
128
+ | > 80 | 8+ random dictionary words or 16+ mixed characters | Strong |
129
+
130
+ **Minimum recommendation**: 80+ bits of entropy for vault passphrases. Use a random passphrase generator (e.g., Diceware) rather than human-chosen passwords.
131
+
132
+ ---
133
+
134
+ ## Threat Model
135
+
136
+ For the canonical threat model, see
137
+ [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md).
138
+
139
+ Short-form summary:
140
+
141
+ - encrypted content can remain confidential against repository readers who do
142
+ not have the relevant key material
143
+ - integrity verification and authenticated decryption detect corruption or
144
+ ciphertext tampering
145
+ - repository exposure still reveals meaningful metadata, including slugs,
146
+ manifest structure, object IDs, and vault metadata
147
+ - `git-cas` does not provide access control, key custody, host-compromise
148
+ protection, or secure deletion
149
+
150
+ Use [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md) when making or reviewing
151
+ security claims. This document focuses on the cryptographic and implementation
152
+ details behind that boundary.
153
+
154
+ ---
155
+
156
+ ## Cryptographic Design
157
+
158
+ ### AES-256-GCM
159
+
160
+ git-cas uses **AES-256-GCM** (Galois/Counter Mode) for authenticated encryption:
161
+
162
+ - **Algorithm**: `aes-256-gcm` via runtime-specific adapters (Node.js `node:crypto`, Bun `CryptoHasher` + `node:crypto`, Deno/Web `crypto.subtle`)
163
+ - **Payload schemes**: `whole` (whole-object authenticated ciphertext), `framed` (independently authenticated records), and `convergent` (per-chunk deterministic encryption)
164
+ - **Key size**: 256 bits (32 bytes)
165
+ - **Nonce size**: 96 bits (12 bytes), cryptographically random (or deterministically derived for `convergent`)
166
+ - **Authentication tag**: 128 bits (16 bytes)
167
+
168
+ ### Why AES-256-GCM?
169
+
170
+ AES-256-GCM was chosen because:
171
+
172
+ 1. **Authenticated Encryption with Associated Data (AEAD)**: Provides both confidentiality and integrity/authenticity in a single operation.
173
+ 2. **Nonce-based**: Does not require unique per-message keys, only unique nonces.
174
+ 3. **Industry standard**: Widely deployed, well-studied, and supported by hardware acceleration on modern CPUs.
175
+ 4. **Streaming-friendly**: GCM mode allows incremental encryption without padding requirements.
176
+
177
+ ### Nonce Generation
178
+
179
+ Each encryption operation generates a fresh 96-bit (12-byte) nonce using `crypto.randomBytes(12)`:
180
+
181
+ - **Uniqueness requirement**: The same key must NEVER be used with the same nonce twice.
182
+ - **Random generation**: git-cas uses cryptographically secure random number generation from Node.js's `crypto.randomBytes()`, which sources from the OS entropy pool.
183
+ - **Collision probability**: With 96-bit random nonces, the probability of collision is negligible for practical use cases (< 2^48 encryptions with the same key).
184
+
185
+ **Exception**: The `convergent` scheme derives nonces deterministically from the
186
+ content hash (see [Convergent Scheme](#convergent-scheme) below). Identical
187
+ plaintext always produces the same nonce, which is the mechanism that preserves
188
+ deduplication.
189
+
190
+ **CRITICAL**: Callers must NOT reuse encryption keys across a large number of operations (approaching 2^32 encryptions with a single key). While collision is unlikely, best practice is to rotate keys periodically.
191
+
192
+ ### Authentication Tag
193
+
194
+ After encryption completes, AES-256-GCM produces a 128-bit authentication tag:
195
+
196
+ - For `whole`, the tag is stored in the manifest's `encryption.tag` field with one nonce for the full payload.
197
+ - For `framed`, each stored record carries its own nonce and tag inside the serialized ciphertext stream.
198
+ - For `convergent`, the GCM tag is appended directly to each chunk blob (see [Convergent Scheme](#convergent-scheme)).
199
+ - During decryption, the tag is verified by `createDecipheriv()` via `setAuthTag()`.
200
+ - If the ciphertext or tag has been modified, `decipher.final()` will throw an error.
201
+
202
+ ### Encryption Wraps Around Chunked Storage
203
+
204
+ For `whole`, the encryption layer wraps the chunking layer:
205
+
206
+ ```
207
+ [Plain source stream] → [Encrypt stream] → [Chunk into 256KB blocks] → [Store as Git blobs]
208
+ ```
209
+
210
+ This means:
211
+
212
+ - **Encrypted chunks are not individually authenticated**: The entire ciphertext is authenticated as a single unit by the GCM tag.
213
+ - **Chunk digests are computed on ciphertext**: The SHA-256 digest stored in each chunk entry is the hash of the encrypted data, not the plaintext.
214
+ - **Chunking is deterministic**: Given the same plaintext and key/nonce, the encrypted chunks will be identical (because nonce is fixed at encryption time).
215
+
216
+ In manifest metadata, this current format is named explicitly as
217
+ `encryption.scheme = 'whole'`. Older encrypted manifests using the legacy scheme
218
+ strings `whole-v1` or `whole-v2` are rejected at read time with guidance to run
219
+ the migration script.
220
+
221
+ Manifest validation accepts three encrypted payload shapes:
222
+
223
+ - `whole` (whole-object authenticated ciphertext)
224
+ - `framed` (independently authenticated records)
225
+ - `convergent` (per-chunk deterministic encryption)
226
+
227
+ For `whole`, manifest-level nonce and tag fields must be canonical base64
228
+ and decode to the expected AES-GCM sizes. For `framed`, the manifest must
229
+ carry `frameBytes` and must not carry top-level nonce/tag fields.
230
+
231
+ For `framed`, git-cas first splits plaintext into fixed-size frames, then
232
+ encrypts each frame independently and serializes records as:
233
+
234
+ ```text
235
+ [4-byte ciphertext length][12-byte nonce][16-byte tag][ciphertext]
236
+ ```
237
+
238
+ Chunk digests still cover the serialized encrypted bytes stored in Git, but
239
+ restore can now authenticate and yield plaintext one frame at a time.
240
+
241
+ ### Convergent Scheme
242
+
243
+ The `convergent` scheme provides per-chunk deterministic encryption that
244
+ preserves content deduplication across encrypted stores. Identical plaintext
245
+ chunks always produce identical ciphertext, even across different store
246
+ operations with the same master key.
247
+
248
+ **Key and nonce derivation**:
249
+
250
+ For each plaintext chunk with SHA-256 digest `D` and master key `K`:
251
+
252
+ - `chunkKey = HMAC-SHA256(K, "git-cas-convergent-key:<D>")[0..31]` — 32-byte AES-256 key
253
+ - `chunkNonce = HMAC-SHA256(K, "git-cas-convergent-nonce:<D>")[0..11]` — 12-byte GCM nonce
254
+
255
+ **Blob format**:
256
+
257
+ Each chunk blob stores `ciphertext || 16-byte GCM auth tag`. The tag is
258
+ appended directly to the ciphertext within the Git blob, rather than being
259
+ carried in the manifest.
260
+
261
+ **Properties**:
262
+
263
+ - **Deterministic**: Same plaintext + same master key = same ciphertext. This
264
+ enables Git's content-addressed deduplication to work even with encryption.
265
+ - **Per-chunk authentication**: Each chunk is independently authenticated by its
266
+ GCM tag. Restore verifies each chunk individually.
267
+ - **Streaming restore**: Like `framed`, `convergent` supports true streaming
268
+ restore — each chunk is decrypted and verified independently without buffering
269
+ the entire ciphertext.
270
+ - **Digest binding**: The plaintext digest is verified after decryption. If the
271
+ decrypted content does not match the expected digest, restore fails with
272
+ `INTEGRITY_ERROR`.
273
+
274
+ **Trade-off**: Because encryption is deterministic, an attacker who can guess the
275
+ plaintext of a chunk and knows the master key can confirm the guess by deriving
276
+ the expected ciphertext. This is inherent to all convergent encryption schemes.
277
+ The `whole` and `framed` schemes use random nonces and do not have this property.
278
+
279
+ ---
280
+
281
+ ## Key Handling
282
+
283
+ ### Caller Responsibility
284
+
285
+ git-cas **does not store encryption keys**. All key management responsibilities fall on the caller:
286
+
287
+ 1. **Key generation**: The caller must generate cryptographically secure 256-bit (32-byte) keys.
288
+ 2. **Key storage**: The caller must securely store keys (e.g., in environment variables, key management systems, hardware security modules).
289
+ 3. **Key distribution**: If keys need to be shared across systems, the caller must implement secure key distribution.
290
+ 4. **Key rotation**: For envelope-encrypted content (v5.2.0+), use `rotateKey()` to re-wrap the DEK with a new KEK without touching data blobs. For vault-wide rotation, use `rotateVaultPassphrase()`. Legacy (non-envelope) content requires manual re-store with a new key.
291
+
292
+ ### Key Validation
293
+
294
+ git-cas validates keys before use:
295
+
296
+ ```javascript
297
+ _validateKey(key) {
298
+ if (!(key instanceof Uint8Array)) {
299
+ throw new CasError(
300
+ 'Encryption key must be a Uint8Array',
301
+ 'INVALID_KEY_TYPE',
302
+ );
303
+ }
304
+ if (key.length !== 32) {
305
+ throw new CasError(
306
+ `Encryption key must be 32 bytes, got ${key.length}`,
307
+ 'INVALID_KEY_LENGTH',
308
+ { expected: 32, actual: key.length },
309
+ );
310
+ }
311
+ }
312
+ ```
313
+
314
+ **Accepted type**: `Uint8Array`
315
+ **Required length**: Exactly 32 bytes (256 bits)
316
+
317
+ Node `Buffer` values are accepted at the Node boundary because `Buffer` extends
318
+ `Uint8Array`; the core contract is the platform-neutral parent type.
319
+
320
+ If validation fails:
321
+
322
+ - **INVALID_KEY_TYPE**: Key is not a Uint8Array
323
+ - **INVALID_KEY_LENGTH**: Key is not 32 bytes
324
+
325
+ ### Key Best Practices
326
+
327
+ 1. **Generate keys using a CSPRNG**: Use `crypto.randomBytes(32)` or equivalent.
328
+ 2. **Never hardcode keys**: Store keys in secure configuration, not in source code.
329
+ 3. **Use unique keys per project/environment**: Do not reuse the same key across different repositories or environments.
330
+ 4. **Rotate keys periodically**: Establish a key rotation policy (e.g., every 90 days).
331
+ 5. **Secure key backups**: If keys are backed up, encrypt the backup with a separate master key.
332
+
333
+ ---
334
+
335
+ ## Encryption Flow
336
+
337
+ ### High-Level Overview
338
+
339
+ When storing content with encryption enabled:
340
+
341
+ 1. Caller provides `source` (async iterable of `Uint8Array` chunks), `slug`, `filename`, and `encryptionKey`.
342
+ 2. git-cas validates the key.
343
+ 3. git-cas creates a streaming encryption context with a random nonce.
344
+ 4. The source stream is encrypted incrementally.
345
+ 5. Encrypted chunks are buffered to 256KB boundaries.
346
+ 6. Each 256KB encrypted chunk is hashed (SHA-256) and written as a Git blob.
347
+ 7. After encryption completes, the GCM authentication tag is retrieved.
348
+ 8. Encryption metadata (algorithm, nonce, tag) is stored in the manifest.
349
+
350
+ > **Note**: The above describes the `whole` encryption path. `framed` encrypts
351
+ > each frame independently (each with its own nonce and tag) before chunking.
352
+ > `convergent` skips stream-level encryption entirely and instead encrypts each
353
+ > chunk individually after chunking, deriving key and nonce from the chunk's
354
+ > plaintext digest (see [Convergent Scheme](#convergent-scheme)).
355
+
356
+ ### Step-by-Step: `store({ source, slug, filename, encryptionKey })` — `whole` path
357
+
358
+ **Step 1: Key Validation**
359
+
360
+ ```javascript
361
+ if (encryptionKey) {
362
+ this._validateKey(encryptionKey);
363
+ }
364
+ ```
365
+
366
+ - If `encryptionKey` is provided, validate it is a 32-byte `Uint8Array`.
367
+ - If validation fails, throw `CasError` with code `INVALID_KEY_TYPE` or `INVALID_KEY_LENGTH`.
368
+
369
+ **Step 2: Initialize Manifest Data**
370
+
371
+ ```javascript
372
+ const manifestData = {
373
+ slug,
374
+ filename,
375
+ size: 0,
376
+ chunks: [],
377
+ };
378
+ ```
379
+
380
+ **Step 3: Create Encryption Stream**
381
+
382
+ ```javascript
383
+ const { encrypt, finalize } = this.crypto.createEncryptionStream(key, aad);
384
+ ```
385
+
386
+ - `createEncryptionStream(key, aad)` generates a 12-byte random nonce.
387
+ - Creates an `aes-256-gcm` cipher with the key and nonce.
388
+ - If `aad` (Additional Authenticated Data) is provided, it is bound to the
389
+ cipher via `setAAD()`. AAD is authenticated but not encrypted — it ensures
390
+ the ciphertext cannot be re-associated with a different manifest context
391
+ (e.g., a different slug or filename) without failing tag verification.
392
+ - Returns:
393
+ - `encrypt`: an async generator function that yields encrypted chunks
394
+ - `finalize`: a function that returns encryption metadata after encryption completes
395
+
396
+ **Step 4: Chunk and Store Encrypted Stream**
397
+
398
+ ```javascript
399
+ await this._chunkAndStore(encrypt(source), manifestData);
400
+ ```
401
+
402
+ - The `encrypt(source)` async generator reads from the source, encrypts data incrementally, and yields encrypted buffers.
403
+ - `_chunkAndStore()` buffers encrypted data to 256KB boundaries.
404
+ - Each 256KB chunk is SHA-256 hashed and written as a Git blob.
405
+ - Chunk metadata (index, size, digest, blob OID) is appended to `manifestData.chunks`.
406
+
407
+ **Step 5: Finalize Encryption Metadata**
408
+
409
+ ```javascript
410
+ manifestData.encryption = finalize();
411
+ ```
412
+
413
+ - `finalize()` retrieves the GCM authentication tag.
414
+ - Returns an object:
415
+ ```javascript
416
+ {
417
+ algorithm: 'aes-256-gcm',
418
+ nonce: '<base64-encoded-nonce>',
419
+ tag: '<base64-encoded-tag>',
420
+ encrypted: true,
421
+ }
422
+ ```
423
+ - This metadata is stored in the manifest's `encryption` field.
424
+
425
+ **Step 6: Create Manifest**
426
+
427
+ ```javascript
428
+ const manifest = new Manifest(manifestData);
429
+ ```
430
+
431
+ ### Important Properties
432
+
433
+ - **Streaming encryption**: Data is encrypted incrementally. The entire plaintext does NOT need to fit in memory during encryption.
434
+ - **Deterministic chunking**: For the same plaintext and key/nonce, the chunk boundaries and digests are deterministic.
435
+ - **No plaintext leakage**: The plaintext source is never written to disk. Only encrypted chunks are persisted.
436
+
437
+ ---
438
+
439
+ ## Decryption Flow
440
+
441
+ ### High-Level Overview
442
+
443
+ When restoring content with encryption:
444
+
445
+ 1. Caller provides `manifest` and `encryptionKey`.
446
+ 2. git-cas validates the key.
447
+ 3. git-cas reads all chunk blobs from Git.
448
+ 4. Each chunk's SHA-256 digest is verified against the stored digest in the manifest.
449
+ 5. All encrypted chunks are concatenated into a single ciphertext buffer.
450
+ 6. The ciphertext is decrypted using AES-256-GCM with the stored nonce and tag.
451
+ 7. If the tag verification fails, decryption throws an integrity error.
452
+ 8. The plaintext buffer is returned to the caller.
453
+
454
+ > **Note**: The above describes the `whole` decryption path, which buffers the
455
+ > full ciphertext. `framed` and `convergent` provide true streaming restore:
456
+ > `framed` decrypts and authenticates each frame independently, and `convergent`
457
+ > decrypts each chunk independently using its derived key and nonce. Both can
458
+ > yield verified plaintext incrementally without loading the entire ciphertext
459
+ > into memory.
460
+
461
+ ### Step-by-Step: `restore({ manifest, encryptionKey })` — `whole` path
462
+
463
+ **Step 1: Key Validation**
464
+
465
+ ```javascript
466
+ if (encryptionKey) {
467
+ this._validateKey(encryptionKey);
468
+ }
469
+ ```
470
+
471
+ **Step 2: Check if Key is Required**
472
+
473
+ ```javascript
474
+ if (manifest.encryption?.encrypted && !encryptionKey) {
475
+ throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
476
+ }
477
+ ```
478
+
479
+ - If the manifest indicates content is encrypted but no key is provided, throw `MISSING_KEY`.
480
+
481
+ **Step 3: Read and Verify Chunks**
482
+
483
+ ```javascript
484
+ const chunks = await this._readAndVerifyChunks(manifest.chunks);
485
+ ```
486
+
487
+ - For each chunk in the manifest:
488
+ 1. Read the Git blob by OID.
489
+ 2. Compute SHA-256 digest of the blob.
490
+ 3. Compare computed digest with stored digest in manifest.
491
+ 4. If mismatch, throw `CasError` with code `INTEGRITY_ERROR`.
492
+ 5. If match, append blob to `buffers` array.
493
+
494
+ **Step 4: Concatenate Encrypted Chunks**
495
+
496
+ ```javascript
497
+ let buffer = concatBytes(chunks);
498
+ ```
499
+
500
+ - All encrypted chunk buffers are concatenated into a single ciphertext buffer.
501
+
502
+ **CRITICAL**: This operation loads the entire ciphertext into memory. For large files, this may cause memory exhaustion. See [Limitations](#limitations).
503
+
504
+ **Step 5: Decrypt Bytes**
505
+
506
+ ```javascript
507
+ if (manifest.encryption?.encrypted) {
508
+ buffer = await this.decrypt({
509
+ buffer,
510
+ key: encryptionKey,
511
+ meta: manifest.encryption,
512
+ });
513
+ }
514
+ ```
515
+
516
+ - Extract nonce and tag from `manifest.encryption`.
517
+ - Create `aes-256-gcm` decipher with key and nonce.
518
+ - Set authentication tag via `setAuthTag()`.
519
+ - Decrypt the ciphertext:
520
+ ```javascript
521
+ const nonce = decodeBase64(meta.nonce);
522
+ const tag = decodeBase64(meta.tag);
523
+ const decipher = createDecipheriv('aes-256-gcm', key, nonce);
524
+ decipher.setAuthTag(tag);
525
+ return concatBytes([decipher.update(buffer), decipher.final()]);
526
+ ```
527
+ - If `decipher.final()` throws (due to tag mismatch or corrupted ciphertext), catch and re-throw as `CasError` with code `INTEGRITY_ERROR`.
528
+
529
+ **Step 6: Return Plaintext**
530
+
531
+ ```javascript
532
+ return { buffer, bytesWritten: buffer.length };
533
+ ```
534
+
535
+ ### Important Properties
536
+
537
+ - **No streaming decryption for `whole`**: The entire ciphertext must be loaded into memory before decryption. This is a limitation of the `whole` scheme specifically. The `framed` and `convergent` schemes support true streaming decryption.
538
+ - **Authentication before decryption**: GCM mode ensures that ciphertext integrity is verified before any plaintext is returned. If the tag check fails, no plaintext is leaked.
539
+ - **Chunk integrity before decryption**: SHA-256 verification of encrypted chunks occurs before decryption. This detects corruption at the chunk level.
540
+
541
+ ---
542
+
543
+ ## Chunk Digest Verification
544
+
545
+ ### SHA-256 Per Chunk
546
+
547
+ Every chunk (encrypted or unencrypted) is protected by a SHA-256 digest:
548
+
549
+ - **Digest computation**: When a chunk is stored, its SHA-256 digest is computed and stored in the manifest. (The actual implementation uses the async `CryptoPort.sha256()` abstraction for runtime portability, not a direct `node:crypto` call.)
550
+ - **Digest verification**: When a chunk is read during `restore()` or `verifyIntegrity()`, the digest is recomputed and compared.
551
+
552
+ ### When Digests Are Verified
553
+
554
+ 1. **During restore** (`restore()` method):
555
+ - Every chunk is read from Git and its SHA-256 digest is verified.
556
+ - If any digest mismatch is detected, `restore()` throws `CasError` with code `INTEGRITY_ERROR`.
557
+
558
+ 2. **During integrity verification** (`verifyIntegrity()` method):
559
+ - All chunks are read and their SHA-256 digests are verified.
560
+ - For encrypted manifests, authenticated decryption is also required for a
561
+ passing result.
562
+ - If any digest mismatch or encrypted-auth failure is detected,
563
+ `verifyIntegrity()` returns `false` and emits an `integrity:fail` event.
564
+ - If encrypted content is verified without decryption credentials,
565
+ `verifyIntegrity()` returns `false`.
566
+
567
+ ### What Digests Protect Against
568
+
569
+ - **Bit-rot**: Silent corruption of Git objects on disk.
570
+ - **Storage errors**: Corruption during disk writes or reads.
571
+ - **Tampering**: Intentional modification of chunk blobs.
572
+ - **Incomplete writes**: Partial writes during storage failures.
573
+
574
+ ### What Digests Do NOT Protect Against
575
+
576
+ - **Manifest tampering**: If an attacker modifies the manifest to point to different blobs with matching digests, the chunk verification will pass. However:
577
+ - For unencrypted content, this results in incorrect data being restored.
578
+ - For encrypted content, restore rejects downgraded encryption metadata and
579
+ GCM tag verification fails unless the attacker also forges the
580
+ authentication tag (which is computationally infeasible).
581
+
582
+ - **Rollback attacks**: If an attacker replaces a newer manifest with an older one, chunk digests will still verify. Application-level versioning or commit signing is required to prevent rollback.
583
+
584
+ ---
585
+
586
+ ## Limitations
587
+
588
+ ### 1. `whole` Encrypted Restore Loads Full Ciphertext into Memory
589
+
590
+ **Issue**: The `whole` scheme concatenates all encrypted chunks into a single buffer before decryption:
591
+
592
+ ```javascript
593
+ let buffer = concatBytes(chunks);
594
+ ```
595
+
596
+ **Impact**:
597
+
598
+ - For large encrypted files (e.g., 1GB+), this can cause memory exhaustion.
599
+ - JavaScript runtimes have finite typed-array allocation limits, so this path is
600
+ bounded by `maxRestoreBufferSize`.
601
+
602
+ **Workaround**:
603
+
604
+ - Prefer `framed` or `convergent` for large encrypted assets that need authenticated streaming restore.
605
+ - If the consumer is restoring to disk, prefer `restoreFile()`. `whole`
606
+ file restores now use a bounded temp-file path instead of buffering the full
607
+ decrypted payload before publication.
608
+ - On Web Crypto runtimes, the whole-object decrypt step is still one-shot.
609
+ The parity improvement is bounded buffering via `maxDecryptionBufferSize`,
610
+ not true whole-object streaming.
611
+ - `restoreStream()` / `restore()` now enforce `maxRestoreBufferSize` against
612
+ streamed gunzip output and, on stream-native persistence adapters, against
613
+ actual blob reads in the buffered path. They still fundamentally require a
614
+ bounded in-memory buffer for `whole`.
615
+ - If large encrypted files are required, implement application-level chunking (e.g., split a 10GB file into 10 separate 1GB files before storing).
616
+
617
+ ### 2. `whole` Has No Streaming Decryption
618
+
619
+ **Issue**: AES-256-GCM decryption under the `whole` scheme is performed on the entire ciphertext as a single operation. The authentication tag is verified only at the end of decryption.
620
+
621
+ **Impact**:
622
+
623
+ - Cannot stream decrypted plaintext to the caller incrementally for `whole`.
624
+ - Cannot detect tampering until the entire ciphertext is processed for `whole`.
625
+
626
+ `framed` and `convergent` are the streaming alternatives: `framed` authenticates
627
+ each frame independently, and `convergent` authenticates each chunk
628
+ independently, so restore can emit verified plaintext incrementally in both
629
+ cases.
630
+
631
+ `restoreFile()` now provides the bounded operational path for `whole`: it
632
+ streams tentative plaintext into a temp file and only renames into place after
633
+ final authentication succeeds. The generic `restoreStream()` API remains
634
+ compatibility-only for `whole` because yielding plaintext to arbitrary
635
+ callers before final auth would weaken the contract.
636
+
637
+ ### 3. Key Rotation (v5.2.0+)
638
+
639
+ **Envelope-encrypted content** supports key rotation without re-encrypting data blobs:
640
+
641
+ - `rotateKey({ manifest, oldKey, newKey, label? })` — unwraps the DEK with `oldKey`, re-wraps with `newKey`, increments `keyVersion`. Data blobs are never read.
642
+ - `rotateVaultPassphrase({ oldPassphrase, newPassphrase })` — rotates all envelope-encrypted vault entries atomically.
643
+
644
+ **Limitations**:
645
+
646
+ - **Legacy (non-envelope) encrypted content** does not support rotation. You must restore with the old key and re-store with envelope encryption.
647
+ - **Rotation does not invalidate old ciphertext**: The encrypted data blobs remain unchanged in the Git object database. An attacker who has both the old wrapped DEK (from a prior manifest commit) and the old KEK can still decrypt. To fully revoke access, the old manifest commits must be unreachable (e.g., via vault history squash + `git gc`).
648
+
649
+ **Best practice**: Track `keyVersion` in manifests to audit rotation compliance. Rotate keys after suspected compromise, on personnel changes, or on a regular schedule (e.g., every 90 days).
650
+
651
+ ### 4. Nonce Collision Risk After 2^32 Operations
652
+
653
+ **Issue**: While 96-bit nonces have negligible collision probability for practical use cases, the GCM security proof degrades after ~2^32 encryptions with the same key.
654
+
655
+ **Impact**:
656
+
657
+ - If the same key is used to encrypt more than 2^32 files, nonce reuse becomes more likely.
658
+ - Nonce reuse with AES-GCM is catastrophic: it allows attackers to recover the plaintext and authentication key.
659
+
660
+ **Mitigation**:
661
+
662
+ - Rotate encryption keys after a reasonable number of operations (e.g., every 1 million encryptions, or every 90 days, whichever comes first).
663
+
664
+ ### 5. Metadata Not Encrypted
665
+
666
+ **Issue**: The following metadata is stored in plaintext in the manifest:
667
+
668
+ - `slug` (file identifier)
669
+ - `filename`
670
+ - `size` (total size of encrypted content)
671
+ - `chunks` array (chunk indices, sizes, digests, blob OIDs)
672
+
673
+ **Impact**:
674
+
675
+ - An attacker with access to the repository can infer file structure, sizes, and access patterns.
676
+ - Chunk digests may leak information about plaintext content if chunks are small or predictable.
677
+
678
+ **Mitigation**:
679
+
680
+ - If metadata privacy is required, implement application-level encryption of the entire manifest before storing it as a Git blob.
681
+
682
+ ### 6. No Protection Against Replay or Rollback Attacks
683
+
684
+ **Issue**: git-cas does not include versioning or timestamps in the encryption metadata.
685
+
686
+ **Impact**:
687
+
688
+ - An attacker can replace a newer manifest tree with an older one (rollback attack).
689
+ - An attacker can duplicate encrypted content across different slugs (replay attack).
690
+
691
+ **Mitigation**:
692
+
693
+ - Use Git commit signing to authenticate manifest trees.
694
+ - Implement application-level versioning or monotonic counters.
695
+
696
+ ---
697
+
698
+ ## Git Object Immutability
699
+
700
+ ### Objects Are Immutable in Git's Object Database
701
+
702
+ Git's object database (ODB) is **append-only** and **content-addressed**:
703
+
704
+ - Once a blob, tree, or commit is written, its content is immutable.
705
+ - Objects are stored in `.git/objects/` and referenced by their SHA-1 (or SHA-256) hash.
706
+
707
+ ### Logical vs. Physical Deletion
708
+
709
+ git-cas does NOT provide a `delete()` method because:
710
+
711
+ 1. **Logical deletion** is trivial: Remove the reference to a manifest tree from your application's index.
712
+ 2. **Physical deletion** is a Git-level operation: Unreferenced objects remain in `.git/objects/` until garbage collection.
713
+
714
+ ### Garbage Collection via `git gc`
715
+
716
+ To physically remove unreferenced objects:
717
+
718
+ ```bash
719
+ git gc --aggressive --prune=now
720
+ ```
721
+
722
+ **Important**:
723
+
724
+ - `git gc` only removes objects that are not reachable from any ref (branch, tag, commit).
725
+ - If a manifest tree is still referenced (e.g., in a commit or reflog), its chunks will NOT be pruned.
726
+
727
+ ### Security Implications
728
+
729
+ 1. **Deleted content may persist**: If you "delete" a file by removing its manifest reference, the encrypted chunks remain in `.git/objects/` until `git gc` prunes them.
730
+
731
+ 2. **Reflog prevents immediate pruning**: Git's reflog keeps references to old commits for 90 days by default. To prune immediately:
732
+
733
+ ```bash
734
+ git reflog expire --expire=now --all
735
+ git gc --prune=now
736
+ ```
737
+
738
+ 3. **Shallow clones do not remove history**: Even if you force-push to remove a commit, the objects remain in the local repository until pruned.
739
+
740
+ ### Best Practices
741
+
742
+ - **Do not rely on logical deletion for security**: If sensitive content was encrypted and stored, assume the ciphertext remains in the repository until `git gc` prunes it.
743
+ - **Prune after sensitive operations**: After removing sensitive content, run:
744
+ ```bash
745
+ git reflog expire --expire=now --all
746
+ git gc --aggressive --prune=now
747
+ ```
748
+ - **Consider repository rotation**: For highly sensitive data, periodically create a new repository and migrate only non-sensitive content.
749
+
750
+ ---
751
+
752
+ ## Error Codes for Security Operations
753
+
754
+ git-cas defines the following error codes for security-related operations:
755
+
756
+ ### `INTEGRITY_ERROR`
757
+
758
+ **Thrown when**:
759
+
760
+ - A chunk's SHA-256 digest does not match the stored digest in the manifest.
761
+ - AES-256-GCM authentication tag verification fails during decryption.
762
+
763
+ **Example**:
764
+
765
+ ```javascript
766
+ throw new CasError('Chunk 2 integrity check failed', 'INTEGRITY_ERROR', {
767
+ chunkIndex: 2,
768
+ expected: 'abc123...',
769
+ actual: 'def456...',
770
+ });
771
+ ```
772
+
773
+ **Possible causes**:
774
+
775
+ - Corruption of Git objects on disk.
776
+ - Tampering with chunk blobs.
777
+ - Wrong encryption key used for decryption (GCM tag mismatch).
778
+ - Incomplete or interrupted writes.
779
+
780
+ **Recommended action**:
781
+
782
+ - If this occurs during `restore()`, the file is corrupted and cannot be recovered without a backup.
783
+ - If this occurs during `verifyIntegrity()`, investigate storage hardware or Git repository health.
784
+
785
+ ### `KDF_POLICY_VIOLATION`
786
+
787
+ **Thrown when**:
788
+
789
+ - Requested KDF parameters for a new passphrase-encrypted write are outside the accepted policy.
790
+ - Stored manifest or vault KDF metadata requests parameters outside the accepted policy window.
791
+
792
+ **Example**:
793
+
794
+ ```javascript
795
+ throw new CasError('manifest KDF field "iterations" must be between 100000 and 2000000', 'KDF_POLICY_VIOLATION', {
796
+ source: 'manifest',
797
+ field: 'iterations',
798
+ value: 20000000,
799
+ min: 100000,
800
+ max: 2000000,
801
+ });
802
+ ```
803
+
804
+ **Recommended action**:
805
+
806
+ - If this occurs on new writes, choose a supported KDF parameter set.
807
+ - If this occurs on restore or vault operations, treat the stored metadata as
808
+ invalid or hostile and inspect repository provenance before proceeding.
809
+
810
+ ### `INVALID_KEY_LENGTH`
811
+
812
+ **Thrown when**:
813
+
814
+ - An encryption key is provided but is not exactly 32 bytes (256 bits).
815
+
816
+ **Example**:
817
+
818
+ ```javascript
819
+ throw new CasError('Encryption key must be 32 bytes, got 16', 'INVALID_KEY_LENGTH', {
820
+ expected: 32,
821
+ actual: 16,
822
+ });
823
+ ```
824
+
825
+ **Possible causes**:
826
+
827
+ - Incorrect key generation (e.g., using 128-bit AES key instead of 256-bit).
828
+ - Key truncation during storage or transmission.
829
+ - Encoding issues (e.g., base64 decoding resulting in wrong length).
830
+
831
+ **Recommended action**:
832
+
833
+ - Verify key generation logic uses `crypto.randomBytes(32)` or equivalent.
834
+ - Check key storage/retrieval does not corrupt or truncate the key.
835
+
836
+ ### `INVALID_KEY_TYPE`
837
+
838
+ **Thrown when**:
839
+
840
+ - An encryption key is provided but is not a `Uint8Array`.
841
+
842
+ **Example**:
843
+
844
+ ```javascript
845
+ throw new CasError('Encryption key must be a Uint8Array', 'INVALID_KEY_TYPE');
846
+ ```
847
+
848
+ **Possible causes**:
849
+
850
+ - Passing a string instead of decoded bytes.
851
+ - Passing a base64-encoded string without decoding it first.
852
+
853
+ **Recommended action**:
854
+
855
+ - Ensure keys are stored as `Uint8Array`.
856
+ - If keys are stored as hex/base64 strings, decode them before passing to git-cas:
857
+ ```javascript
858
+ const key = decodeBase64(keyBase64);
859
+ ```
860
+
861
+ ### `MISSING_KEY`
862
+
863
+ **Thrown when**:
864
+
865
+ - A manifest indicates content is encrypted (`manifest.encryption.encrypted === true`) but no `encryptionKey` is provided to `restore()`.
866
+
867
+ **Example**:
868
+
869
+ ```javascript
870
+ throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
871
+ ```
872
+
873
+ **Possible causes**:
874
+
875
+ - Application logic error: Forgot to pass key to `restore()`.
876
+ - Key was lost or not available in the current environment.
877
+
878
+ **Recommended action**:
879
+
880
+ - Verify the encryption key is available and passed to `restore()`.
881
+ - If the key is lost, the content is permanently inaccessible.
882
+
883
+ ### `RESTORE_TOO_LARGE`
884
+
885
+ **Thrown when**:
886
+
887
+ - An encrypted or compressed restore would exceed the configured `maxRestoreBufferSize` limit.
888
+ - An actual blob read in the buffered restore path exceeds its allowed bound.
889
+ - Streamed gunzip output in the buffered restore path exceeds the limit.
890
+
891
+ **Example**:
892
+
893
+ ```javascript
894
+ throw new CasError('Restore buffer exceeds limit', 'RESTORE_TOO_LARGE', {
895
+ size: 1073741824,
896
+ limit: 536870912,
897
+ });
898
+ ```
899
+
900
+ **Possible causes**:
901
+
902
+ - The asset is larger than the configured buffer limit (default 512 MiB).
903
+ - A referenced blob is larger than the manifest-declared chunk size or the
904
+ remaining buffered restore budget.
905
+ - A compressed asset inflates beyond the limit during decompression.
906
+
907
+ **Recommended action**:
908
+
909
+ - Increase `maxRestoreBufferSize` in the `CasService` constructor or `.casrc`.
910
+ - For very large assets, consider `framed` or `convergent` so encrypted restore can stay streaming.
911
+
912
+ ---
913
+
914
+ ### `ENCRYPTION_BUFFER_EXCEEDED`
915
+
916
+ **Thrown when**:
917
+
918
+ - Web Crypto AES-GCM encryption is attempted on data exceeding the configured `maxEncryptionBufferSize`.
919
+ - Web Crypto is a one-shot API — it cannot stream, so the entire plaintext must fit in memory.
920
+
921
+ **Example**:
922
+
923
+ ```javascript
924
+ throw new CasError(
925
+ 'Streaming encryption buffered 1073741824 bytes (limit: 536870912)...',
926
+ 'ENCRYPTION_BUFFER_EXCEEDED',
927
+ { accumulated: 1073741824, limit: 536870912 }
928
+ );
929
+ ```
930
+
931
+ **Possible causes**:
932
+
933
+ - Large plaintext inputs combined with `WebCryptoAdapter` (used by Deno and
934
+ browser-class runtimes).
935
+ - `NodeCryptoAdapter` and `BunCryptoAdapter` use true streaming encryption and
936
+ are not affected by this limit.
937
+
938
+ **Recommended action**:
939
+
940
+ - Increase `maxEncryptionBufferSize` in the `WebCryptoAdapter` constructor.
941
+ - Switch to `NodeCryptoAdapter` if streaming encryption is needed.
942
+ - Split the asset before storing, or store without encryption on the Web Crypto path for very large files.
943
+
944
+ ---
945
+
946
+ ### `DECRYPTION_BUFFER_EXCEEDED`
947
+
948
+ **Thrown when**:
949
+
950
+ - Web Crypto AES-GCM whole-object decryption is attempted on ciphertext
951
+ exceeding the configured `maxDecryptionBufferSize`.
952
+ - Web Crypto decrypt is still one-shot, so `whole` ciphertext must fit
953
+ within the configured bounded buffer on that runtime path.
954
+
955
+ **Example**:
956
+
957
+ ```javascript
958
+ throw new CasError(
959
+ 'Streaming decryption buffered 1073741824 bytes (limit: 536870912)...',
960
+ 'DECRYPTION_BUFFER_EXCEEDED',
961
+ { accumulated: 1073741824, limit: 536870912 }
962
+ );
963
+ ```
964
+
965
+ **Possible causes**:
966
+
967
+ - Large `whole` encrypted restores on Deno or browser-class runtimes using
968
+ `WebCryptoAdapter`.
969
+ - Assuming `restoreFile()` implies identical whole-object decrypt mechanics on
970
+ Node/Bun and Web Crypto.
971
+
972
+ **Recommended action**:
973
+
974
+ - Prefer `framed` or `convergent` for large encrypted restores that need bounded,
975
+ authenticated streaming across runtimes.
976
+ - Increase `maxDecryptionBufferSize` in the `WebCryptoAdapter` constructor if
977
+ the runtime has enough headroom.
978
+ - Use Node.js or Bun when large `whole` file restores are required.
979
+
980
+ ---
981
+
982
+ ## Conclusion
983
+
984
+ git-cas provides strong at-rest encryption and integrity guarantees through AES-256-GCM and SHA-256 chunk verification. However, it is critical to understand the limitations and caller responsibilities:
985
+
986
+ - **Key management is entirely your responsibility**. git-cas does not store or manage keys.
987
+ - **Encrypted restore under the `whole` scheme is buffered, not streaming**. Large encrypted files may cause memory issues. The `framed` and `convergent` schemes provide true streaming restore with per-frame or per-chunk authentication.
988
+ - **Key rotation supported for envelope encryption** (v5.2.0+). Legacy (non-envelope) content still requires manual restore/store cycles.
989
+ - **Metadata is not encrypted**. File structure and sizes are visible to anyone with repository access.
990
+ - **Logical deletion does not physically remove data**. Use `git gc` to prune unreferenced objects.
991
+
992
+ For general security questions, file a GitHub issue. For roadmap context, see the
993
+ [repository roadmap](https://github.com/git-stunts/git-cas/blob/main/ROADMAP.md).