@git-stunts/git-cas 5.3.2 → 6.0.1

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 +1027 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +449 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +926 -0
  6. package/README.md +106 -366
  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 +1255 -212
  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 +367 -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 +2254 -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 +273 -80
  60. package/index.js +220 -59
  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 +153 -53
  103. package/src/domain/services/CasService.js +322 -837
  104. package/src/domain/services/ChunkRepository.js +268 -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 +180 -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 +10 -6
  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,1027 @@
1
+ # Advanced Guide -- git-cas
2
+
3
+ Deep-dive reference for advanced features, internals, and tuning. For
4
+ orientation and the productive-fast path, start with the [GUIDE.md](./GUIDE.md).
5
+
6
+ ---
7
+
8
+ ## Table of Contents
9
+
10
+ - [Content-Defined Chunking (CDC)](#content-defined-chunking-cdc)
11
+ - [Algorithm Overview](#algorithm-overview)
12
+ - [Buzhash Rolling Hash](#buzhash-rolling-hash)
13
+ - [Mask Derivation](#mask-derivation)
14
+ - [FastCDC Dual-Mask Normalization](#fastcdc-dual-mask-normalization)
15
+ - [Default Parameters](#default-parameters)
16
+ - [Encryption Penalty](#encryption-penalty)
17
+ - [Encryption Schemes](#encryption-schemes)
18
+ - [Legacy Scheme Rejection](#legacy-scheme-rejection)
19
+ - [whole](#whole)
20
+ - [framed (default for fixed encrypted stores)](#framed-default-for-fixed-encrypted-stores)
21
+ - [convergent](#convergent)
22
+ - [Why AAD Matters](#why-aad-matters)
23
+ - [Scheme Selection](#scheme-selection)
24
+ - [Auto-Selection](#auto-selection)
25
+ - [Convergent Encryption](#convergent-encryption)
26
+ - [Key Derivation](#key-derivation)
27
+ - [Blob Format](#blob-format)
28
+ - [Restore Verification](#restore-verification)
29
+ - [Trade-offs](#trade-offs)
30
+ - [KDF Policy](#kdf-policy)
31
+ - [PBKDF2-SHA512](#pbkdf2-sha512)
32
+ - [scrypt](#scrypt)
33
+ - [Enforcement Points](#enforcement-points)
34
+ - [Manifest Integrity Hash](#manifest-integrity-hash)
35
+ - [Computation (store)](#computation-store)
36
+ - [Verification (read)](#verification-read)
37
+ - [What It Catches](#what-it-catches)
38
+ - [Backward Compatibility](#backward-compatibility)
39
+ - [Format Version](#format-version)
40
+ - [Manifest Diffing](#manifest-diffing)
41
+ - [Return Value](#return-value)
42
+ - [Use Cases](#use-cases)
43
+ - [Example](#example)
44
+ - [Parallel Chunk Restore](#parallel-chunk-restore)
45
+ - [How It Works](#how-it-works)
46
+ - [Configuration](#configuration)
47
+ - [Merkle Manifests](#merkle-manifests)
48
+ - [Structure](#structure)
49
+ - [Git Tree Layout](#git-tree-layout)
50
+ - [Validation](#validation)
51
+ - [Limits](#limits)
52
+ - [Vault Privacy Mode](#vault-privacy-mode)
53
+ - [How It Works](#how-it-works)
54
+ - [Requirements](#requirements)
55
+ - [Limitations](#limitations)
56
+ - [Envelope Encryption](#envelope-encryption)
57
+ - [Multi-Recipient Model](#multi-recipient-model)
58
+ - [Trial Decryption](#trial-decryption)
59
+ - [Key Rotation](#key-rotation)
60
+ - [Adding and Removing Recipients](#adding-and-removing-recipients)
61
+ - [Streaming Decompression](#streaming-decompression)
62
+ - [CompressionPort Architecture](#compressionport-architecture)
63
+ - [Port Interface](#port-interface)
64
+ - [NodeCompressionAdapter](#nodecompressionadapter)
65
+ - [Pluggability](#pluggability)
66
+ - [Direct CasService and Custom Port Contracts](#direct-casservice-and-custom-port-contracts)
67
+ - [Minimal Direct Service](#minimal-direct-service)
68
+ - [Required Port Shape](#required-port-shape)
69
+ - [Runtime and Facade Split](#runtime-and-facade-split)
70
+ - [Security Hardening Summary](#security-hardening-summary)
71
+ - [Operational Tooling](#operational-tooling)
72
+ - [Migration](#migration)
73
+ - [Release Verification](#release-verification)
74
+ - [Build Metadata](#build-metadata)
75
+ - [Performance Baselines](#performance-baselines)
76
+ - [Configuration Reference](#configuration-reference)
77
+ - [store() Options](#store-options)
78
+ - [CdcChunker Options](#cdcchunker-options)
79
+
80
+ ---
81
+
82
+ ## Content-Defined Chunking (CDC)
83
+
84
+ `git-cas` ships two chunking strategies: **fixed** (default) and **CDC**
85
+ (content-defined chunking). CDC uses the Buzhash rolling hash algorithm to
86
+ find chunk boundaries that are determined by the content itself, not by byte
87
+ offset. Small edits to a file only affect nearby chunks, giving significantly
88
+ better deduplication across versions of the same asset.
89
+
90
+ ### Algorithm Overview
91
+
92
+ CDC processing runs in three sequential phases per chunk:
93
+
94
+ 1. **Fill window** -- the first 64 bytes of each new chunk populate a sliding
95
+ ring buffer. The hash is seeded by XOR-ing in byte-table entries without
96
+ removing an outgoing byte (the window is not yet full).
97
+
98
+ 2. **Pre-min feed** -- bytes between position 64 and `minChunkSize` are
99
+ bulk-copied into the chunk buffer while the rolling hash is updated
100
+ (incoming byte XOR-ed in, outgoing byte XOR-ed out), but no boundary check
101
+ is performed. This guarantees every emitted chunk is at least `minChunkSize`
102
+ bytes.
103
+
104
+ 3. **Boundary scan** -- from `minChunkSize` to `maxChunkSize`, each byte is
105
+ fed into the hash and tested against a bitmask. When `(hash & mask) === 0`,
106
+ a boundary is declared and the accumulated bytes are emitted as a chunk. If
107
+ `maxChunkSize` is reached without a match, the chunk is emitted anyway.
108
+
109
+ A final partial chunk smaller than `minChunkSize` is allowed at EOF.
110
+
111
+ ### Buzhash Rolling Hash
112
+
113
+ The hash function is Buzhash with a **64-byte sliding window**. The byte
114
+ table is a deterministic `Uint32Array[256]` generated from a seeded
115
+ **xorshift64 PRNG** (seed `0x6a09e667f3bcc908`). Because the table is
116
+ derived from a fixed seed, every runtime produces identical values without
117
+ needing `crypto.getRandomValues`.
118
+
119
+ The update step for a full window is:
120
+
121
+ ```
122
+ hash = rotateLeft32(hash, 1) XOR table[outgoingByte] XOR table[incomingByte]
123
+ ```
124
+
125
+ The window write position is tracked modulo 64 using a bitmask
126
+ (`winPos = (winPos + 1) & 63`).
127
+
128
+ ### Mask Derivation
129
+
130
+ The boundary mask is derived from `targetChunkSize`:
131
+
132
+ ```
133
+ bits = floor(log2(targetChunkSize))
134
+ mask = (1 << bits) - 1
135
+ ```
136
+
137
+ For the default target of 262,144 bytes (2^18), `mask = 0x3FFFF`. On average
138
+ the hash matches once every `mask + 1` bytes, centering the distribution
139
+ around the target.
140
+
141
+ ### FastCDC Dual-Mask Normalization
142
+
143
+ When `normalized: true` (the default), a dual-mask strategy from the FastCDC
144
+ paper is applied. Instead of a single mask, two masks control boundary
145
+ probability relative to the current chunk length:
146
+
147
+ | Region | Mask | Bits | Effect |
148
+ | :-------------------------------------------- | :--------- | :--------- | :------------------------------------------------------------------------------------------- |
149
+ | Below target (`chunkLen < targetSize`) | `hardMask` | `bits + 1` | More bits required to match -- boundaries are **less likely**, pushing chunks larger |
150
+ | At or above target (`chunkLen >= targetSize`) | `easyMask` | `bits - 1` | Fewer bits required -- boundaries are **more likely**, pulling chunks back toward the target |
151
+
152
+ Concrete formulas:
153
+
154
+ ```
155
+ hardMask = (1 << min(bits + 1, 31)) - 1
156
+ easyMask = (1 << max(bits - 1, 1)) - 1
157
+ ```
158
+
159
+ The effect is a tighter distribution of chunk sizes around the target, lower
160
+ variance, and better deduplication efficiency compared to a single-mask
161
+ approach.
162
+
163
+ To disable normalization:
164
+
165
+ ```js
166
+ const chunker = new CdcChunker({ targetChunkSize: 262144, normalized: false });
167
+ ```
168
+
169
+ ### Default Parameters
170
+
171
+ | Parameter | Default | Bounds |
172
+ | :---------------- | :---------------- | :---------------------------------------- |
173
+ | `targetChunkSize` | 262,144 (256 KiB) | Must be in `[minChunkSize, maxChunkSize]` |
174
+ | `minChunkSize` | 65,536 (64 KiB) | Must not exceed `maxChunkSize` |
175
+ | `maxChunkSize` | 1,048,576 (1 MiB) | Hard cap at 100 MiB |
176
+ | `normalized` | `true` | Boolean |
177
+
178
+ ### Encryption Penalty
179
+
180
+ CDC deduplication is **ineffective** when using `whole` or `framed` encryption.
181
+ Ciphertext is pseudorandom, so there are no structural byte patterns for the
182
+ rolling hash to latch onto. `CasService` emits a warning when CDC is combined
183
+ with these schemes. Use **convergent encryption** (`convergent` scheme) to
184
+ preserve deduplication across encrypted versions -- see the
185
+ [Convergent Encryption](#convergent-encryption) section below.
186
+
187
+ ---
188
+
189
+ ## Encryption Schemes
190
+
191
+ `git-cas` supports three AES-256-GCM encryption schemes. All use 256-bit keys
192
+ and 128-bit authentication tags. `whole` and `framed` use fresh 96-bit random
193
+ nonces; `convergent` derives per-chunk keys and nonces deterministically from
194
+ the plaintext content hash. AAD (Additional Authenticated Data) binding is
195
+ always active -- there are no non-AAD variants.
196
+
197
+ The single source of truth for scheme identifiers is
198
+ `src/domain/encryption/schemes.js`.
199
+
200
+ ### Legacy Scheme Rejection
201
+
202
+ The v1/v2 suffixed schemes (`whole-v1`, `whole-v2`, `framed-v1`, `framed-v2`,
203
+ `convergent-v1`) are no longer accepted. Any manifest referencing a legacy
204
+ scheme is rejected at runtime with a `LEGACY_SCHEME` error that directs the
205
+ user to the migration script:
206
+
207
+ ```
208
+ scripts/migrate-encryption.js
209
+ ```
210
+
211
+ The migration script migrates manifests to current scheme identifiers — renaming
212
+ v2 schemes directly and re-encrypting v1 schemes with AAD binding.
213
+
214
+ ### whole
215
+
216
+ Single AES-256-GCM envelope over the entire chunked ciphertext stream. The
217
+ nonce and authentication tag are stored in the manifest's `encryption` object.
218
+
219
+ - Store: plaintext source -> streaming encrypt -> chunk -> store blobs
220
+ - Restore: read blobs -> concatenate -> single-shot decrypt -> verify tag
221
+ - AAD: UTF-8 encoded slug bytes -- prevents cross-manifest blob
222
+ substitution by binding the ciphertext to the manifest slug
223
+ - Manifest fields: `scheme: "whole"`, `nonce`, `tag`
224
+
225
+ Limitations: the full ciphertext must fit in memory during restore (bounded by
226
+ `maxRestoreBufferSize`, default 512 MiB). No incremental authentication.
227
+
228
+ ### framed (default for fixed encrypted stores)
229
+
230
+ Per-frame authenticated encryption with independently verifiable records.
231
+ Plaintext is split into fixed-size frames (default 64 KiB, max 64 MiB),
232
+ each encrypted separately. Restore can authenticate and emit plaintext
233
+ incrementally without buffering the full payload.
234
+
235
+ **Per-frame AAD binding**:
236
+
237
+ ```
238
+ AAD = slug (UTF-8) + NUL byte (0x00) + frame index (4 bytes, big-endian)
239
+ ```
240
+
241
+ This prevents both slug tampering and frame reordering or deletion attacks.
242
+ Each frame's authentication tag commits to its position within the stream.
243
+
244
+ **Binary record layout** (one record per frame):
245
+
246
+ ```
247
+ 0 4 16 32
248
+ +-------------------+------------------+------------------+
249
+ | ciphertext length | nonce (12 bytes) | tag (16 bytes) |
250
+ | (4 bytes, BE) | | |
251
+ +-------------------+------------------+------------------+
252
+ | ciphertext ... |
253
+ +--------------------------------------------------------+
254
+ ```
255
+
256
+ - Byte 0-3: `uint32be` ciphertext length
257
+ - Byte 4-15: 12-byte AES-GCM nonce
258
+ - Byte 16-31: 16-byte authentication tag
259
+ - Byte 32+: ciphertext (length given by bytes 0-3)
260
+
261
+ Total header overhead per frame: **32 bytes**.
262
+
263
+ - Manifest fields: `scheme: "framed"`, `frameBytes`
264
+
265
+ ### convergent
266
+
267
+ Per-chunk deterministic encryption that preserves deduplication. Identical
268
+ plaintext chunks always produce identical ciphertext, so CDC deduplication
269
+ works even when encryption is enabled. See the dedicated
270
+ [Convergent Encryption](#convergent-encryption) section below.
271
+
272
+ - Manifest fields: `scheme: "convergent"`
273
+
274
+ ### Why AAD Matters
275
+
276
+ Without AAD, an attacker with write access to the repository can:
277
+
278
+ 1. Copy encrypted blob OIDs from manifest A into manifest B (cross-manifest
279
+ blob substitution). Decryption succeeds if both manifests share the same
280
+ key, but the restored content is wrong.
281
+ 2. For framed schemes, reorder or remove individual frame records within the
282
+ ciphertext stream.
283
+
284
+ AAD binds the encryption to the manifest identity and (for framed) the
285
+ frame sequence, so any such tampering causes GCM authentication failure.
286
+
287
+ ### Scheme Selection
288
+
289
+ | Scenario | Recommended Scheme |
290
+ | :------------------------------------- | :----------------- |
291
+ | Fixed chunking + encryption | `framed` (default) |
292
+ | Large assets needing streaming restore | `framed` |
293
+ | CDC with encryption (dedup-preserving) | `convergent` |
294
+ | Single-envelope simplicity | `whole` |
295
+
296
+ ### Auto-Selection
297
+
298
+ When an encryption key is provided without an explicit scheme, `CasService`
299
+ selects the scheme automatically:
300
+
301
+ - If the chunker strategy is `cdc`, the `convergent` scheme is selected
302
+ (preserving dedup).
303
+ - Otherwise, `framed` is selected.
304
+
305
+ This can be overridden by passing `encryption.convergent: false` or by
306
+ setting an explicit `encryption.scheme`.
307
+
308
+ ---
309
+
310
+ ## Convergent Encryption
311
+
312
+ Convergent encryption is extracted as its own service
313
+ (`src/domain/services/ConvergentEncryption.js`) and encapsulates per-chunk
314
+ deterministic encryption where the key and nonce are derived from the
315
+ plaintext content hash.
316
+
317
+ ### Key Derivation
318
+
319
+ For each chunk, the master encryption key and the chunk's SHA-256 digest are
320
+ used to derive a unique key and nonce:
321
+
322
+ ```
323
+ chunkKey = HMAC-SHA256(masterKey, "git-cas-convergent-key:<digest>")[0..31]
324
+ chunkNonce = HMAC-SHA256(masterKey, "git-cas-convergent-nonce:<digest>")[0..11]
325
+ ```
326
+
327
+ Because the derivation is deterministic, identical plaintext chunks (same
328
+ digest) always produce the same ciphertext, preserving content-addressed
329
+ deduplication.
330
+
331
+ ### Blob Format
332
+
333
+ Each encrypted chunk blob is stored as:
334
+
335
+ ```
336
+ ciphertext || 16-byte GCM authentication tag
337
+ ```
338
+
339
+ ### Restore Verification
340
+
341
+ On restore, each chunk is decrypted and its plaintext SHA-256 is recomputed.
342
+ If the recomputed digest does not match the expected digest from the manifest,
343
+ an `INTEGRITY_ERROR` is thrown. This catches both decryption failures and
344
+ post-decryption corruption.
345
+
346
+ ### Trade-offs
347
+
348
+ - Deduplication is preserved across encrypted versions of the same asset.
349
+ - Deterministic encryption means identical plaintext always yields identical
350
+ ciphertext, which leaks equality information. If this is a concern, use
351
+ `framed` or `whole` instead.
352
+ - Convergent encryption operates post-chunk (after CDC or fixed chunking),
353
+ unlike `whole` and `framed` which encrypt pre-chunk.
354
+
355
+ ---
356
+
357
+ ## KDF Policy
358
+
359
+ When passphrase-based encryption is used, `git-cas` derives 256-bit keys
360
+ using PBKDF2-SHA512 or scrypt. A strict policy enforces parameter bounds
361
+ at both store time and restore time.
362
+
363
+ ### PBKDF2-SHA512
364
+
365
+ | Parameter | Default | Min | Max |
366
+ | :----------- | ------: | ------: | ----------: |
367
+ | `iterations` | 600,000 | 100,000 | 2,000,000 |
368
+ | `keyLength` | 32 | -- | -- (locked) |
369
+
370
+ ### scrypt
371
+
372
+ | Parameter | Default | Min | Max |
373
+ | :-------------------- | -------------: | ------------: | ---------------: |
374
+ | `cost` (N) | 131,072 (2^17) | 16,384 (2^14) | 1,048,576 (2^20) |
375
+ | `blockSize` (r) | 8 | 8 | 32 |
376
+ | `parallelization` (p) | 1 | 1 | 16 |
377
+ | `keyLength` | 32 | -- | -- (locked) |
378
+
379
+ Additional constraints:
380
+
381
+ - `cost` must be a power of two.
382
+ - Combined scrypt memory budget `128 * N * r` is capped at **1 GiB**.
383
+ - Salt must be at least **16 bytes** (128 bits), per NIST SP 800-132.
384
+ - Salt must be canonical base64.
385
+ - `keyLength` is locked at exactly 32 bytes; any other value is rejected.
386
+ - Runtime support: Node and Bun adapters support scrypt. Web Crypto runtimes,
387
+ including the Deno adapter, report an explicit capability error for scrypt.
388
+
389
+ ### Enforcement Points
390
+
391
+ Policy is checked in four places:
392
+
393
+ 1. **`store()` with passphrase** -- new write defaults are applied and
394
+ validated before derivation.
395
+ 2. **`restore()` with passphrase** -- stored manifest KDF metadata is
396
+ validated against the policy window before derivation begins. Hostile or
397
+ out-of-policy parameters fail with `KDF_POLICY_VIOLATION`.
398
+ 3. **`initVault()` with passphrase** -- vault-level KDF parameters are
399
+ validated at initialization.
400
+ 4. **`rotateVaultPassphrase()`** -- both old and new KDF parameters are
401
+ validated.
402
+
403
+ ---
404
+
405
+ ## Manifest Integrity Hash
406
+
407
+ Every manifest written by `createTree()` includes a `manifestHash` field:
408
+ a SHA-256 hex digest of the codec-encoded manifest data (with the
409
+ `manifestHash` field itself excluded, and `undefined` values stripped to
410
+ match codec round-trip behavior).
411
+
412
+ ### Computation (store)
413
+
414
+ ```
415
+ 1. Serialize manifest data to JSON/CBOR (minus manifestHash and undefined keys)
416
+ 2. SHA-256 the resulting bytes
417
+ 3. Store the 64-char hex digest as manifestHash in the manifest
418
+ 4. Serialize the complete manifest (including manifestHash) for the blob
419
+ ```
420
+
421
+ ### Verification (read)
422
+
423
+ On `readManifest()`, if the decoded manifest contains a `manifestHash` field:
424
+
425
+ 1. Re-encode the manifest (minus `manifestHash` and undefined keys)
426
+ 2. SHA-256 the bytes
427
+ 3. Compare against the stored `manifestHash`
428
+ 4. If mismatch, throw `MANIFEST_INTEGRITY_ERROR`
429
+
430
+ ### What It Catches
431
+
432
+ - Git object store corruption (bit-rot, truncation)
433
+ - Codec round-trip bugs (JSON/CBOR encoding asymmetry)
434
+ - Manual manifest editing errors
435
+
436
+ ### Backward Compatibility
437
+
438
+ Old manifests without a `manifestHash` field skip verification silently. The
439
+ field is optional in the schema and only enforced when present.
440
+
441
+ ---
442
+
443
+ ## Format Version
444
+
445
+ Manifests may carry a `formatVersion` field -- a semver string (e.g.,
446
+ `"1.0.0"`) stamped by `CasService` when the instance is constructed with a
447
+ `formatVersion` option. This is distinct from the structural `version: 1|2`
448
+ field that distinguishes flat manifests from Merkle manifests.
449
+
450
+ ```js
451
+ import { FixedChunker, NodeCompressionAdapter } from '@git-stunts/git-cas';
452
+ import CasService from '@git-stunts/git-cas/service';
453
+
454
+ const cas = new CasService({
455
+ persistence,
456
+ codec,
457
+ crypto,
458
+ observability,
459
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
460
+ compressionAdapter: new NodeCompressionAdapter(),
461
+ formatVersion: '6.0.0',
462
+ });
463
+ ```
464
+
465
+ When present, `formatVersion` records which release of `git-cas` produced
466
+ the manifest. It is validated against the regex `/^\d+\.\d+\.\d+$/` by the
467
+ manifest schema. The facade sets this from package metadata automatically;
468
+ direct `CasService` callers provide it themselves when they want the stamp.
469
+
470
+ ---
471
+
472
+ ## Manifest Diffing
473
+
474
+ `CasService.diffManifests(oldManifest, newManifest)` is a static method that
475
+ compares two manifests by chunk digest. It is a pure domain function with no
476
+ I/O, no ports, and no state -- just set algebra over chunk arrays.
477
+
478
+ ### Return Value
479
+
480
+ ```js
481
+ {
482
+ added, // Chunks in newManifest not in oldManifest
483
+ removed, // Chunks in oldManifest not in newManifest
484
+ unchanged, // Chunks in both (by digest), taken from newManifest
485
+ summary: {
486
+ addedCount, removedCount, unchangedCount,
487
+ addedBytes, removedBytes, unchangedBytes,
488
+ },
489
+ }
490
+ ```
491
+
492
+ ### Use Cases
493
+
494
+ - **Incremental sync**: determine which chunks need to be transferred when
495
+ updating a previously stored asset.
496
+ - **Storage audit**: measure how much deduplication CDC achieves across
497
+ versions by inspecting `unchangedBytes / totalBytes`.
498
+ - **Garbage collection**: identify chunks that are no longer referenced after
499
+ an asset is updated.
500
+
501
+ ### Example
502
+
503
+ ```js
504
+ import CasService from '@git-stunts/git-cas/service';
505
+
506
+ const oldManifest = await cas.readManifest({ treeOid: oldOid });
507
+ const newManifest = await cas.readManifest({ treeOid: newOid });
508
+ const diff = CasService.diffManifests(oldManifest, newManifest);
509
+
510
+ console.log(diff.summary);
511
+ // { addedCount: 3, removedCount: 1, unchangedCount: 397, ... }
512
+ ```
513
+
514
+ ---
515
+
516
+ ## Parallel Chunk Restore
517
+
518
+ `git-cas` uses a **PrefetchWindow** sliding window to restore chunks in
519
+ parallel with bounded concurrency while preserving strict output ordering.
520
+
521
+ ### How It Works
522
+
523
+ The `prefetchChunks` async generator maintains a ring buffer of
524
+ `concurrency` in-flight fetch promises:
525
+
526
+ 1. **Initial fill**: the first `concurrency` chunks are fetched immediately,
527
+ populating the ring buffer.
528
+ 2. **Yield in order**: the yield cursor advances through the ring buffer
529
+ sequentially. Each slot is `await`-ed before yielding.
530
+ 3. **Slide forward**: after a slot is yielded, it is immediately refilled
531
+ with the next chunk fetch (if any remain), keeping the pipeline saturated.
532
+
533
+ This guarantees that:
534
+
535
+ - At most `concurrency` fetches are in-flight at any time (bounded memory).
536
+ - Output order matches manifest order (no reordering).
537
+ - Throughput scales with concurrency when I/O is the bottleneck.
538
+
539
+ ### Configuration
540
+
541
+ Set `concurrency` on the `CasService` constructor:
542
+
543
+ ```js
544
+ import { FixedChunker, NodeCompressionAdapter } from '@git-stunts/git-cas';
545
+ import CasService from '@git-stunts/git-cas/service';
546
+
547
+ const cas = new CasService({
548
+ persistence,
549
+ codec,
550
+ crypto,
551
+ observability,
552
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
553
+ compressionAdapter: new NodeCompressionAdapter(),
554
+ concurrency: 8, // up to 8 parallel chunk reads
555
+ });
556
+ ```
557
+
558
+ The `concurrency` option accepts an integer in `[1, 64]`. The default is `1`
559
+ (sequential reads). Higher values benefit network-backed or high-latency
560
+ persistence adapters.
561
+
562
+ ---
563
+
564
+ ## Merkle Manifests
565
+
566
+ When a stored asset produces more than `merkleThreshold` chunks (default
567
+ 1,000), `git-cas` automatically transitions to a two-level Merkle-style
568
+ manifest structure.
569
+
570
+ ### Structure
571
+
572
+ ```
573
+ Root manifest (version: 2)
574
+ +-- subManifests: [
575
+ | { oid: <sub-0>, chunkCount: 1000, startIndex: 0 },
576
+ | { oid: <sub-1>, chunkCount: 1000, startIndex: 1000 },
577
+ | { oid: <sub-2>, chunkCount: 423, startIndex: 2000 },
578
+ | ]
579
+ +-- chunks: [] (empty in root)
580
+ +-- ...standard manifest fields...
581
+ ```
582
+
583
+ Each sub-manifest blob contains a `{ chunks: [...] }` array of chunk entries.
584
+
585
+ ### Git Tree Layout
586
+
587
+ ```
588
+ manifest.json -- root manifest blob (version 2)
589
+ sub-manifest-0.json -- first sub-manifest blob
590
+ sub-manifest-1.json -- second sub-manifest blob
591
+ sub-manifest-2.json -- third sub-manifest blob
592
+ <chunk-digest-hex> -- chunk blob entries (deduplicated by digest)
593
+ ...
594
+ ```
595
+
596
+ ### Validation
597
+
598
+ On `readManifest()`, sub-manifests are resolved transparently:
599
+
600
+ 1. Root manifest is decoded and its `manifestHash` verified.
601
+ 2. Each `subManifests[i].oid` blob is read and decoded.
602
+ 3. Each chunk entry in each sub-manifest is validated through `ChunkSchema`.
603
+ 4. `chunkCount` declared in the root is compared against the actual decoded
604
+ count. Mismatch throws `MANIFEST_INTEGRITY_ERROR`.
605
+ 5. The flattened chunk array is returned as if it were a flat manifest.
606
+
607
+ ### Limits
608
+
609
+ - `subManifests` array capped at **10,000 entries** (schema enforced).
610
+ - With 1,000 chunks per sub-manifest, that supports up to 10 million chunks
611
+ per asset.
612
+
613
+ ---
614
+
615
+ ## Vault Privacy Mode
616
+
617
+ By default, vault tree entries use percent-encoded slug names, which are
618
+ visible to anyone with repository read access. Privacy mode replaces slugs
619
+ with opaque HMAC digests.
620
+
621
+ ### How It Works
622
+
623
+ 1. **Privacy key derivation**:
624
+
625
+ ```
626
+ privacyKey = HMAC-SHA256(vaultEncryptionKey, "git-cas-privacy-v1")
627
+ ```
628
+
629
+ The 32-byte privacy key is derived deterministically from the vault
630
+ encryption key using a fixed label.
631
+
632
+ 2. **Tree entry masking**: each slug is replaced with its HMAC:
633
+
634
+ ```
635
+ treeName = hex(HMAC-SHA256(privacyKey, slug)) // 64-char lowercase hex
636
+ ```
637
+
638
+ 3. **Encrypted privacy index**: a `.privacy-index` blob is written to the
639
+ vault tree, containing an AES-256-GCM encrypted JSON mapping of
640
+ `{ slug: hmacHex, ... }`. This allows `listVault()` and
641
+ `resolveVaultEntry()` to reverse the mapping.
642
+
643
+ ### Requirements
644
+
645
+ - Privacy mode requires vault encryption (`initVault({ passphrase, privacy: true })`).
646
+ - All vault read/write operations on a privacy-enabled vault require an
647
+ `encryptionKey` parameter.
648
+
649
+ ### Limitations
650
+
651
+ - Privacy mode does **not** scrub git history. Older commits created before
652
+ privacy was enabled may still contain plain-text slug names.
653
+ - The `.privacy-index` blob is re-encrypted on every vault write. Its size
654
+ grows linearly with the number of vault entries.
655
+ - HMAC is deterministic: the same slug always produces the same tree entry
656
+ name (given the same key), which allows correlation across vault commits.
657
+
658
+ ---
659
+
660
+ ## Envelope Encryption
661
+
662
+ Envelope encryption uses a two-tier key model:
663
+
664
+ - **DEK** (Data Encryption Key): a random 32-byte key that encrypts the
665
+ actual content. Generated once per `store()` call.
666
+ - **KEK** (Key Encryption Key): a per-recipient 32-byte key that wraps the
667
+ DEK. Each recipient gets their own wrapped copy.
668
+
669
+ ### Multi-Recipient Model
670
+
671
+ When storing with `recipients`:
672
+
673
+ ```js
674
+ await cas.store({
675
+ source,
676
+ slug: 'asset/photo.raw',
677
+ filename: 'photo.raw',
678
+ recipients: [
679
+ { label: 'alice', key: aliceKek },
680
+ { label: 'bob', key: bobKek },
681
+ ],
682
+ });
683
+ ```
684
+
685
+ 1. A random 32-byte DEK is generated via `crypto.randomBytes(32)`.
686
+ 2. Content is encrypted with the DEK using the configured scheme.
687
+ 3. For each recipient, the DEK is AES-256-GCM wrapped with their KEK.
688
+ 4. The manifest stores an array of `{ label, wrappedDek, nonce, tag }` entries.
689
+
690
+ ### Trial Decryption
691
+
692
+ On restore, `KeyResolver.resolveKeyForRecipients()` iterates **all** recipient
693
+ entries and attempts to unwrap each one. The first successful unwrap provides
694
+ the DEK. All entries are always tried -- there is no early exit, no index
695
+ leak, and no timing oracle that reveals which recipient matched.
696
+
697
+ ```
698
+ for each recipient entry:
699
+ try unwrapDek(entry, providedKey)
700
+ if success and no prior match: save result
701
+ if DEK_UNWRAP_FAILED: continue
702
+ if no match found: throw NO_MATCHING_RECIPIENT
703
+ ```
704
+
705
+ ### Key Rotation
706
+
707
+ `rotateKey()` re-wraps the DEK with a new KEK without touching data blobs:
708
+
709
+ 1. Unwrap DEK using `oldKey`.
710
+ 2. Wrap DEK with `newKey`.
711
+ 3. Replace the matched recipient entry.
712
+ 4. Increment `keyVersion` at both manifest and recipient level.
713
+
714
+ The old ciphertext blobs are never read. Rotation is a manifest-only mutation.
715
+
716
+ **Caveat**: rotation does not invalidate old ciphertext. An attacker with
717
+ both the old wrapped DEK (from a prior manifest commit) and the old KEK can
718
+ still decrypt. To fully revoke access, the old manifest commits must become
719
+ unreachable (e.g., via history rewrite + `git gc`).
720
+
721
+ ### Adding and Removing Recipients
722
+
723
+ - `addRecipient()`: unwraps the DEK with an existing KEK, wraps it with the
724
+ new recipient's KEK, and returns a new Manifest with the appended entry.
725
+ - `removeRecipient()`: removes the label from the recipients array. Cannot
726
+ remove the last recipient. Does not require a key (manifest-only mutation).
727
+
728
+ ---
729
+
730
+ ## Streaming Decompression
731
+
732
+ Plaintext+gzip, framed+gzip, and convergent+gzip restores use **streaming
733
+ decompression**. Compressed data is piped through the compression adapter's
734
+ `decompressStream()` method, which processes data incrementally without
735
+ buffering the full decompressed payload in memory. This applies to:
736
+
737
+ - Plain compressed restores (no encryption)
738
+ - Framed-encrypted + compressed restores
739
+ - Convergent-encrypted + compressed restores
740
+
741
+ The streaming approach keeps memory usage proportional to the chunk/frame size
742
+ rather than the total asset size. `whole` encrypted restores preserve the
743
+ whole-object authentication boundary and still use the bounded buffered path
744
+ for `restoreStream()` / `restore()`. Uncompressed `whole` `restoreFile()` streams
745
+ decryption into the temp-file publication path; `whole` + gzip preserves
746
+ auth-before-decompress and may buffer the encrypted compressed payload before
747
+ gunzip runs.
748
+
749
+ ---
750
+
751
+ ## CompressionPort Architecture
752
+
753
+ Compression in `git-cas` is fully abstracted behind the `CompressionPort`
754
+ interface. `CasService` has **zero platform-specific compression imports**.
755
+
756
+ ### Port Interface
757
+
758
+ ```
759
+ CompressionPort (abstract)
760
+ compressBuffer(buffer) -> Promise<Uint8Array>
761
+ decompressBuffer(buffer) -> Promise<Uint8Array>
762
+ compressStream(source) -> AsyncGenerator<Uint8Array>
763
+ decompressStream(source) -> AsyncGenerator<Uint8Array>
764
+ ```
765
+
766
+ ### NodeCompressionAdapter
767
+
768
+ The default adapter uses `node:zlib`:
769
+
770
+ - `compressBuffer` / `decompressBuffer`: promisified `gzip` / `gunzip`
771
+ - `compressStream`: `Readable.from(source).pipe(createGzip())`
772
+ - `decompressStream`: `Readable.from(source).pipe(createGunzip())` with
773
+ error forwarding from the input stream to the gunzip transform
774
+
775
+ ### Pluggability
776
+
777
+ Pass a custom adapter via the `compressionAdapter` constructor option:
778
+
779
+ ```js
780
+ import { FixedChunker } from '@git-stunts/git-cas';
781
+ import CasService from '@git-stunts/git-cas/service';
782
+
783
+ const cas = new CasService({
784
+ persistence,
785
+ codec,
786
+ crypto,
787
+ observability,
788
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
789
+ compressionAdapter: new MyBrotliAdapter(),
790
+ });
791
+ ```
792
+
793
+ The only currently supported compression algorithm at the schema level is
794
+ `gzip`. The port abstraction exists to support future Bun-native, Deno-native,
795
+ or browser compression adapters without changing `CasService`.
796
+
797
+ ---
798
+
799
+ ## Direct CasService and Custom Port Contracts
800
+
801
+ Most applications should use the `ContentAddressableStore` facade. It supplies
802
+ Git persistence, runtime crypto, a JSON codec, a silent observer, fixed
803
+ chunking, gzip compression, and package-version manifest stamping by default.
804
+ Direct `CasService` construction is for tests, non-Git persistence experiments,
805
+ or applications that own every adapter boundary. For a checklist-style guide to
806
+ custom adapters, see [docs/EXTENDING.md](./docs/EXTENDING.md).
807
+
808
+ ### Minimal Direct Service
809
+
810
+ Direct `CasService` construction requires all domain ports, including the
811
+ chunker and compression adapter. Those two are optional only on the facade.
812
+
813
+ ```js
814
+ import {
815
+ FixedChunker,
816
+ JsonCodec,
817
+ NodeCompressionAdapter,
818
+ NodeCryptoAdapter,
819
+ SilentObserver,
820
+ } from '@git-stunts/git-cas';
821
+ import CasService from '@git-stunts/git-cas/service';
822
+
823
+ const service = new CasService({
824
+ persistence,
825
+ codec: new JsonCodec(),
826
+ crypto: new NodeCryptoAdapter(),
827
+ observability: new SilentObserver(),
828
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
829
+ compressionAdapter: new NodeCompressionAdapter(),
830
+ formatVersion: '6.0.0',
831
+ });
832
+ ```
833
+
834
+ ### Required Port Shape
835
+
836
+ | Port | Required Surface | Notes |
837
+ | :------------------- | :--------------------------------------------------------------------------------- | :----------------------------------------------------------------------------------------------------- |
838
+ | `GitPersistencePort` | `writeBlob`, `writeTree`, `readBlob`, `readBlobStream`, `readTree` | Return and consume `Uint8Array` streams; `readBlobStream()` is required for bounded restore paths. |
839
+ | `CodecPort` | `encode`, `decode`, `extension` | `encode()` must return `Uint8Array`; JSON and CBOR are built in. |
840
+ | `CryptoPort` | SHA-256, random bytes, AES-GCM buffer/stream methods, nonce/tag helpers, HMAC, KDF | `scrypt` support is runtime-dependent; Web Crypto adapters report capability errors where unsupported. |
841
+ | `ObservabilityPort` | `metric`, `log`, `span` | Use `SilentObserver`, `EventEmitterObserver`, or `StatsCollector` unless you need custom telemetry. |
842
+ | `ChunkingPort` | `chunk(source)`, `strategy`, `params` | Use `FixedChunker` or `CdcChunker`; direct service callers must inject one. |
843
+ | `CompressionPort` | `compressBuffer`, `decompressBuffer`, `compressStream`, `decompressStream` | Direct service callers must inject one even if stores do not request compression. |
844
+
845
+ The public byte contract is `Uint8Array`. Node `Buffer` values work at Node
846
+ boundaries because `Buffer` extends `Uint8Array`, but custom adapters should
847
+ not expose Buffer-only APIs in their portable contracts.
848
+
849
+ ### Runtime and Facade Split
850
+
851
+ The facade owns infrastructure defaults:
852
+
853
+ - `GitPersistenceAdapter` and `GitRefAdapter` wrap `@git-stunts/plumbing`.
854
+ - `createCryptoAdapter()` chooses Node, Bun-compatible, or Web Crypto support.
855
+ - `resolveChunker()` maps declarative `{ strategy: 'fixed' | 'cdc' }` config
856
+ into `FixedChunker` or `CdcChunker` instances.
857
+ - `NodeCompressionAdapter` is the default compression adapter.
858
+ - `formatVersion` is stamped from package metadata.
859
+
860
+ The domain service owns behavior after the ports are injected. It validates
861
+ constructor numeric ranges, rejects missing `chunker` and `compressionAdapter`,
862
+ and keeps runtime-specific imports out of the domain.
863
+
864
+ ---
865
+
866
+ ## Security Hardening Summary
867
+
868
+ The following security fixes have been applied across the release line. Each
869
+ row describes the fix and what it prevents.
870
+
871
+ | # | Fix | Prevents |
872
+ | :-- | :------------------------------------------------------------------------------------ | :------------------------------------------------------------------------ |
873
+ | 1 | Encrypted manifest metadata downgrade rejection | Attacker strips `encrypted: true` to bypass decryption |
874
+ | 2 | Algorithm allowlist (`aes-256-gcm` only) | Attacker substitutes a weaker or non-existent algorithm |
875
+ | 3 | Nonce/tag format validation (canonical base64, correct byte length) | Malformed metadata crashes the runtime or produces garbage |
876
+ | 4 | Framed record parse hardening (`ciphertextLength <= frameBytes`) | Oversized length field causes unbounded allocation |
877
+ | 5 | `maxRestoreBufferSize` enforcement for buffered `restore()` / `restoreStream()` paths | Unbounded memory allocation on large encrypted/compressed memory restores |
878
+ | 6 | `maxEncryptionBufferSize` / `maxDecryptionBufferSize` for Web Crypto | One-shot Web Crypto API exhausts memory on large payloads |
879
+ | 7 | KDF policy enforcement (bounded iterations, cost, salt, keyLength) | Attacker-controlled manifest requests extreme KDF work or weak params |
880
+ | 8 | Manifest integrity hash (`manifestHash` field) | Silent manifest corruption or codec round-trip bugs |
881
+ | 9 | CDC + encryption dedup warning | False confidence in dedup savings when ciphertext is pseudorandom |
882
+ | 10 | Orphaned blob tracking on `STREAM_ERROR` / `STORE_ERROR` | Lost blob OIDs after partial store failures |
883
+ | 11 | AAD binding (always active on all schemes) | Cross-manifest blob substitution and frame reordering attacks |
884
+ | 12 | Legacy scheme rejection at runtime | Downgrade to weaker v1/v2 scheme variants |
885
+ | 13 | Convergent encryption post-decrypt digest verification | Chunk substitution or corruption after decryption |
886
+ | 14 | Encrypted vault key verifier in `.vault.json` | Wrong passphrase accepted for an empty encrypted vault |
887
+ | 15 | `restoreFile()` `baseDirectory` boundary | Path traversal outside the trusted restore root |
888
+ | 16 | Metadata blob `maxBlobSize` limit | Oversized manifest or sub-manifest blobs exhausting memory |
889
+ | 17 | Concurrency cap | Unbounded parallel Git/blob operations |
890
+ | 18 | `frameBytes` cap | Oversized framed records causing memory pressure |
891
+ | 19 | Source validation before `store()` processing | Late failures after partial writes from invalid async iterables |
892
+ | 20 | Salt length enforcement | Weak KDF metadata accepted from stored manifests or vault metadata |
893
+ | 21 | Vault encryption-count tracking | Silent drift toward nonce reuse risk |
894
+ | 22 | Constant-time recipient and verifier comparisons | Timing-based key or verifier identification |
895
+
896
+ ---
897
+
898
+ ## Operational Tooling
899
+
900
+ The release and migration scripts are part of the supported operator surface.
901
+ They are intentionally separate from the runtime library so production callers
902
+ do not inherit release-time dependencies.
903
+
904
+ ### Migration
905
+
906
+ ```sh
907
+ npm run upgrade
908
+ printf '%s\n' 'my-secret' | node scripts/migrate-encryption.js --execute --passphrase-file -
909
+ node scripts/migrate-encryption.js --execute --key-file ./asset.key
910
+ ```
911
+
912
+ The migration script is dry-run by default. It maps legacy v2 scheme names to
913
+ current names when safe, and re-encrypts legacy v1 content when AAD must be
914
+ added. Prefer `--passphrase-file -`, `--passphrase-file <path>`, or
915
+ `--key-file` for full migrations. Inline `--passphrase` is accepted for
916
+ compatibility, but prints a warning because it can leak through shell history
917
+ and process listings. Privacy-enabled vaults accept vault-specific
918
+ passphrase/key options when the vault credential differs from the content
919
+ credential; prefer `--vault-passphrase-file` or `--vault-key-file` there too.
920
+
921
+ ### Release Verification
922
+
923
+ ```sh
924
+ npm test
925
+ npx eslint .
926
+ npm run release:verify -- --skip-jsr
927
+ ```
928
+
929
+ `release:verify` checks package metadata, exports, docs, tests, pack contents,
930
+ Docker runtime suites, and release-state invariants. Use `--skip-jsr` when JSR
931
+ publication is intentionally deferred or unavailable.
932
+
933
+ ### Build Metadata
934
+
935
+ ```sh
936
+ npm run stamp
937
+ npm pack --dry-run
938
+ ```
939
+
940
+ `npm run stamp` writes `build-info.json` from the current Git state. The file
941
+ is included in the npm package and is regenerated by `prepublishOnly`; it
942
+ should not be treated as source truth when the working tree has moved.
943
+
944
+ ---
945
+
946
+ ## Performance Baselines
947
+
948
+ The following baselines are published for the current release line.
949
+
950
+ | Strategy | Asset Size | Total Chunks | Store (ms) | Restore (ms) | Dedupe (%) |
951
+ | :----------------- | :--------- | :----------- | :--------- | :----------- | :--------- |
952
+ | **Fixed (256K)** | 100 MiB | 400 | ~450 | ~300 | 0% |
953
+ | **CDC (256K avg)** | 100 MiB | ~390 | ~1200 | ~350 | 98%+ |
954
+
955
+ **Notes:**
956
+
957
+ - CDC store time includes Buzhash rolling hash overhead. Restore time is
958
+ comparable to fixed-size chunking because restore reads blobs by OID
959
+ regardless of how boundaries were chosen.
960
+ - CDC **normalization** (dual-mask) tightens the chunk size distribution but
961
+ does not materially affect throughput. The hash computation cost is the same;
962
+ only the mask comparison changes. The dedup benefit comes from more
963
+ predictable chunk sizes across versions.
964
+ - Encryption adds per-chunk (framed/convergent) or per-stream (whole)
965
+ AES-GCM overhead. On hardware with AES-NI, the throughput impact is
966
+ typically < 10%.
967
+ - Compression (gzip) can significantly reduce stored size but adds CPU cost
968
+ proportional to the data volume. Streaming decompression avoids
969
+ full-payload buffering for all restore paths.
970
+ - Parallel chunk restore (`concurrency > 1`) reduces wall-clock restore time
971
+ when the persistence adapter has I/O latency. Throughput scales linearly
972
+ up to the point where the adapter saturates.
973
+
974
+ ---
975
+
976
+ ## Configuration Reference
977
+
978
+ Direct `CasService` constructor options with types, defaults, and bounds. The
979
+ high-level `ContentAddressableStore` facade supplies defaults for `chunker`,
980
+ `compressionAdapter`, runtime crypto, and `formatVersion`.
981
+
982
+ | Option | Type | Default | Bounds | Description |
983
+ | :--------------------- | :------------------- | :-------------------- | :------------------------------------------------ | :------------------------------------------------------------------- |
984
+ | `persistence` | `GitPersistencePort` | _required_ | -- | Git blob/tree read/write adapter |
985
+ | `codec` | `CodecPort` | _required_ | -- | Manifest serialization (JSON or CBOR) |
986
+ | `crypto` | `CryptoPort` | _required_ | -- | Encryption, hashing, KDF adapter |
987
+ | `observability` | `ObservabilityPort` | _required_ | Must implement `metric()`, `log()`, `span()` | Metrics, logging, tracing |
988
+ | `chunkSize` | `number` | `262144` (256 KiB) | Integer in `[1024, 104857600]` (1 KiB -- 100 MiB) | Chunk size for fixed chunking; warning above 10 MiB |
989
+ | `merkleThreshold` | `number` | `1000` | Integer >= 1 | Chunk count above which Merkle manifests are used |
990
+ | `concurrency` | `number` | `1` | Integer in `[1, 64]` | Max parallel chunk I/O operations (PrefetchWindow size) |
991
+ | `chunker` | `ChunkingPort` | _required_ | -- | Chunking strategy instance (`FixedChunker` or `CdcChunker`) |
992
+ | `maxRestoreBufferSize` | `number` | `536870912` (512 MiB) | Integer >= 1024 | Max bytes for buffered restore (encrypted/compressed) |
993
+ | `compressionAdapter` | `CompressionPort` | _required_ | -- | Compression implementation |
994
+ | `formatVersion` | `string` | -- | Semver (`/^\d+\.\d+\.\d+$/`) | Version stamp for new manifests (distinct from structural `version`) |
995
+
996
+ ### store() Options
997
+
998
+ | Option | Type | Default | Description |
999
+ | :---------------------- | :-------------------------- | :--------------------------------------------- | :---------------------------------------------------------------------------- |
1000
+ | `source` | `AsyncIterable<Uint8Array>` | _required_ | Input byte stream |
1001
+ | `slug` | `string` | _required_ | Asset identifier |
1002
+ | `filename` | `string` | _required_ | Original filename |
1003
+ | `encryptionKey` | `Uint8Array` | -- | 32-byte key (mutually exclusive with `passphrase` and `recipients`) |
1004
+ | `passphrase` | `string` | -- | Derive key via KDF (mutually exclusive with `encryptionKey` and `recipients`) |
1005
+ | `encryption` | `object` | -- | `{ scheme?, frameBytes?, convergent? }` |
1006
+ | `encryption.scheme` | `string` | Auto: `convergent` for CDC, `framed` otherwise | `'whole'`, `'framed'`, or `'convergent'` |
1007
+ | `encryption.frameBytes` | `number` | `65536` (64 KiB) | Frame size for the `framed` scheme; max 64 MiB |
1008
+ | `encryption.convergent` | `boolean` | -- | Explicit convergent opt-in/opt-out (auto-selected for CDC chunkers) |
1009
+ | `kdfOptions` | `object` | -- | `{ algorithm?, iterations?, cost?, blockSize?, parallelization? }` |
1010
+ | `compression` | `object` | -- | `{ algorithm: 'gzip' }` |
1011
+ | `recipients` | `Array<{label, key}>` | -- | Envelope recipients (mutually exclusive with key/passphrase) |
1012
+
1013
+ ### CdcChunker Options
1014
+
1015
+ | Option | Type | Default | Bounds | Description |
1016
+ | :---------------- | :-------- | :-------- | :----------------------------- | :------------------------------------- |
1017
+ | `targetChunkSize` | `number` | `262144` | Must be in `[min, max]` | Target average chunk size |
1018
+ | `minChunkSize` | `number` | `65536` | Must not exceed `maxChunkSize` | Minimum chunk size |
1019
+ | `maxChunkSize` | `number` | `1048576` | Hard cap at 100 MiB | Maximum chunk size |
1020
+ | `normalized` | `boolean` | `true` | -- | Enable FastCDC dual-mask normalization |
1021
+
1022
+ ---
1023
+
1024
+ For orientation, quick starts, and common usage patterns, see [GUIDE.md](./GUIDE.md).
1025
+
1026
+ For the security model and threat analysis, see [SECURITY.md](./SECURITY.md)
1027
+ and [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md).