@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
@@ -0,0 +1,1006 @@
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
+ - `cost` must be a power of two.
381
+ - Combined scrypt memory budget `128 * N * r` is capped at **1 GiB**.
382
+ - Salt must be at least **16 bytes** (128 bits), per NIST SP 800-132.
383
+ - Salt must be canonical base64.
384
+ - `keyLength` is locked at exactly 32 bytes; any other value is rejected.
385
+ - Runtime support: Node and Bun adapters support scrypt. Web Crypto runtimes,
386
+ including the Deno adapter, report an explicit capability error for scrypt.
387
+
388
+ ### Enforcement Points
389
+
390
+ Policy is checked in four places:
391
+
392
+ 1. **`store()` with passphrase** -- new write defaults are applied and
393
+ validated before derivation.
394
+ 2. **`restore()` with passphrase** -- stored manifest KDF metadata is
395
+ validated against the policy window before derivation begins. Hostile or
396
+ out-of-policy parameters fail with `KDF_POLICY_VIOLATION`.
397
+ 3. **`initVault()` with passphrase** -- vault-level KDF parameters are
398
+ validated at initialization.
399
+ 4. **`rotateVaultPassphrase()`** -- both old and new KDF parameters are
400
+ validated.
401
+
402
+ ---
403
+
404
+ ## Manifest Integrity Hash
405
+
406
+ Every manifest written by `createTree()` includes a `manifestHash` field:
407
+ a SHA-256 hex digest of the codec-encoded manifest data (with the
408
+ `manifestHash` field itself excluded, and `undefined` values stripped to
409
+ match codec round-trip behavior).
410
+
411
+ ### Computation (store)
412
+
413
+ ```
414
+ 1. Serialize manifest data to JSON/CBOR (minus manifestHash and undefined keys)
415
+ 2. SHA-256 the resulting bytes
416
+ 3. Store the 64-char hex digest as manifestHash in the manifest
417
+ 4. Serialize the complete manifest (including manifestHash) for the blob
418
+ ```
419
+
420
+ ### Verification (read)
421
+
422
+ On `readManifest()`, if the decoded manifest contains a `manifestHash` field:
423
+
424
+ 1. Re-encode the manifest (minus `manifestHash` and undefined keys)
425
+ 2. SHA-256 the bytes
426
+ 3. Compare against the stored `manifestHash`
427
+ 4. If mismatch, throw `MANIFEST_INTEGRITY_ERROR`
428
+
429
+ ### What It Catches
430
+
431
+ - Git object store corruption (bit-rot, truncation)
432
+ - Codec round-trip bugs (JSON/CBOR encoding asymmetry)
433
+ - Manual manifest editing errors
434
+
435
+ ### Backward Compatibility
436
+
437
+ Old manifests without a `manifestHash` field skip verification silently. The
438
+ field is optional in the schema and only enforced when present.
439
+
440
+ ---
441
+
442
+ ## Format Version
443
+
444
+ Manifests may carry a `formatVersion` field -- a semver string (e.g.,
445
+ `"1.0.0"`) stamped by `CasService` when the instance is constructed with a
446
+ `formatVersion` option. This is distinct from the structural `version: 1|2`
447
+ field that distinguishes flat manifests from Merkle manifests.
448
+
449
+ ```js
450
+ import { FixedChunker, NodeCompressionAdapter } from '@git-stunts/git-cas';
451
+ import CasService from '@git-stunts/git-cas/service';
452
+
453
+ const cas = new CasService({
454
+ persistence, codec, crypto, observability,
455
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
456
+ compressionAdapter: new NodeCompressionAdapter(),
457
+ formatVersion: '6.0.0',
458
+ });
459
+ ```
460
+
461
+ When present, `formatVersion` records which release of `git-cas` produced
462
+ the manifest. It is validated against the regex `/^\d+\.\d+\.\d+$/` by the
463
+ manifest schema. The facade sets this from package metadata automatically;
464
+ direct `CasService` callers provide it themselves when they want the stamp.
465
+
466
+ ---
467
+
468
+ ## Manifest Diffing
469
+
470
+ `CasService.diffManifests(oldManifest, newManifest)` is a static method that
471
+ compares two manifests by chunk digest. It is a pure domain function with no
472
+ I/O, no ports, and no state -- just set algebra over chunk arrays.
473
+
474
+ ### Return Value
475
+
476
+ ```js
477
+ {
478
+ added, // Chunks in newManifest not in oldManifest
479
+ removed, // Chunks in oldManifest not in newManifest
480
+ unchanged, // Chunks in both (by digest), taken from newManifest
481
+ summary: {
482
+ addedCount, removedCount, unchangedCount,
483
+ addedBytes, removedBytes, unchangedBytes,
484
+ },
485
+ }
486
+ ```
487
+
488
+ ### Use Cases
489
+
490
+ - **Incremental sync**: determine which chunks need to be transferred when
491
+ updating a previously stored asset.
492
+ - **Storage audit**: measure how much deduplication CDC achieves across
493
+ versions by inspecting `unchangedBytes / totalBytes`.
494
+ - **Garbage collection**: identify chunks that are no longer referenced after
495
+ an asset is updated.
496
+
497
+ ### Example
498
+
499
+ ```js
500
+ import CasService from '@git-stunts/git-cas/service';
501
+
502
+ const oldManifest = await cas.readManifest({ treeOid: oldOid });
503
+ const newManifest = await cas.readManifest({ treeOid: newOid });
504
+ const diff = CasService.diffManifests(oldManifest, newManifest);
505
+
506
+ console.log(diff.summary);
507
+ // { addedCount: 3, removedCount: 1, unchangedCount: 397, ... }
508
+ ```
509
+
510
+ ---
511
+
512
+ ## Parallel Chunk Restore
513
+
514
+ `git-cas` uses a **PrefetchWindow** sliding window to restore chunks in
515
+ parallel with bounded concurrency while preserving strict output ordering.
516
+
517
+ ### How It Works
518
+
519
+ The `prefetchChunks` async generator maintains a ring buffer of
520
+ `concurrency` in-flight fetch promises:
521
+
522
+ 1. **Initial fill**: the first `concurrency` chunks are fetched immediately,
523
+ populating the ring buffer.
524
+ 2. **Yield in order**: the yield cursor advances through the ring buffer
525
+ sequentially. Each slot is `await`-ed before yielding.
526
+ 3. **Slide forward**: after a slot is yielded, it is immediately refilled
527
+ with the next chunk fetch (if any remain), keeping the pipeline saturated.
528
+
529
+ This guarantees that:
530
+
531
+ - At most `concurrency` fetches are in-flight at any time (bounded memory).
532
+ - Output order matches manifest order (no reordering).
533
+ - Throughput scales with concurrency when I/O is the bottleneck.
534
+
535
+ ### Configuration
536
+
537
+ Set `concurrency` on the `CasService` constructor:
538
+
539
+ ```js
540
+ import { FixedChunker, NodeCompressionAdapter } from '@git-stunts/git-cas';
541
+ import CasService from '@git-stunts/git-cas/service';
542
+
543
+ const cas = new CasService({
544
+ persistence, codec, crypto, observability,
545
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
546
+ compressionAdapter: new NodeCompressionAdapter(),
547
+ concurrency: 8, // up to 8 parallel chunk reads
548
+ });
549
+ ```
550
+
551
+ The `concurrency` option accepts an integer in `[1, 64]`. The default is `1`
552
+ (sequential reads). Higher values benefit network-backed or high-latency
553
+ persistence adapters.
554
+
555
+ ---
556
+
557
+ ## Merkle Manifests
558
+
559
+ When a stored asset produces more than `merkleThreshold` chunks (default
560
+ 1,000), `git-cas` automatically transitions to a two-level Merkle-style
561
+ manifest structure.
562
+
563
+ ### Structure
564
+
565
+ ```
566
+ Root manifest (version: 2)
567
+ +-- subManifests: [
568
+ | { oid: <sub-0>, chunkCount: 1000, startIndex: 0 },
569
+ | { oid: <sub-1>, chunkCount: 1000, startIndex: 1000 },
570
+ | { oid: <sub-2>, chunkCount: 423, startIndex: 2000 },
571
+ | ]
572
+ +-- chunks: [] (empty in root)
573
+ +-- ...standard manifest fields...
574
+ ```
575
+
576
+ Each sub-manifest blob contains a `{ chunks: [...] }` array of chunk entries.
577
+
578
+ ### Git Tree Layout
579
+
580
+ ```
581
+ manifest.json -- root manifest blob (version 2)
582
+ sub-manifest-0.json -- first sub-manifest blob
583
+ sub-manifest-1.json -- second sub-manifest blob
584
+ sub-manifest-2.json -- third sub-manifest blob
585
+ <chunk-digest-hex> -- chunk blob entries (deduplicated by digest)
586
+ ...
587
+ ```
588
+
589
+ ### Validation
590
+
591
+ On `readManifest()`, sub-manifests are resolved transparently:
592
+
593
+ 1. Root manifest is decoded and its `manifestHash` verified.
594
+ 2. Each `subManifests[i].oid` blob is read and decoded.
595
+ 3. Each chunk entry in each sub-manifest is validated through `ChunkSchema`.
596
+ 4. `chunkCount` declared in the root is compared against the actual decoded
597
+ count. Mismatch throws `MANIFEST_INTEGRITY_ERROR`.
598
+ 5. The flattened chunk array is returned as if it were a flat manifest.
599
+
600
+ ### Limits
601
+
602
+ - `subManifests` array capped at **10,000 entries** (schema enforced).
603
+ - With 1,000 chunks per sub-manifest, that supports up to 10 million chunks
604
+ per asset.
605
+
606
+ ---
607
+
608
+ ## Vault Privacy Mode
609
+
610
+ By default, vault tree entries use percent-encoded slug names, which are
611
+ visible to anyone with repository read access. Privacy mode replaces slugs
612
+ with opaque HMAC digests.
613
+
614
+ ### How It Works
615
+
616
+ 1. **Privacy key derivation**:
617
+ ```
618
+ privacyKey = HMAC-SHA256(vaultEncryptionKey, "git-cas-privacy-v1")
619
+ ```
620
+ The 32-byte privacy key is derived deterministically from the vault
621
+ encryption key using a fixed label.
622
+
623
+ 2. **Tree entry masking**: each slug is replaced with its HMAC:
624
+ ```
625
+ treeName = hex(HMAC-SHA256(privacyKey, slug)) // 64-char lowercase hex
626
+ ```
627
+
628
+ 3. **Encrypted privacy index**: a `.privacy-index` blob is written to the
629
+ vault tree, containing an AES-256-GCM encrypted JSON mapping of
630
+ `{ slug: hmacHex, ... }`. This allows `listVault()` and
631
+ `resolveVaultEntry()` to reverse the mapping.
632
+
633
+ ### Requirements
634
+
635
+ - Privacy mode requires vault encryption (`initVault({ passphrase, privacy: true })`).
636
+ - All vault read/write operations on a privacy-enabled vault require an
637
+ `encryptionKey` parameter.
638
+
639
+ ### Limitations
640
+
641
+ - Privacy mode does **not** scrub git history. Older commits created before
642
+ privacy was enabled may still contain plain-text slug names.
643
+ - The `.privacy-index` blob is re-encrypted on every vault write. Its size
644
+ grows linearly with the number of vault entries.
645
+ - HMAC is deterministic: the same slug always produces the same tree entry
646
+ name (given the same key), which allows correlation across vault commits.
647
+
648
+ ---
649
+
650
+ ## Envelope Encryption
651
+
652
+ Envelope encryption uses a two-tier key model:
653
+
654
+ - **DEK** (Data Encryption Key): a random 32-byte key that encrypts the
655
+ actual content. Generated once per `store()` call.
656
+ - **KEK** (Key Encryption Key): a per-recipient 32-byte key that wraps the
657
+ DEK. Each recipient gets their own wrapped copy.
658
+
659
+ ### Multi-Recipient Model
660
+
661
+ When storing with `recipients`:
662
+
663
+ ```js
664
+ await cas.store({
665
+ source,
666
+ slug: 'asset/photo.raw',
667
+ filename: 'photo.raw',
668
+ recipients: [
669
+ { label: 'alice', key: aliceKek },
670
+ { label: 'bob', key: bobKek },
671
+ ],
672
+ });
673
+ ```
674
+
675
+ 1. A random 32-byte DEK is generated via `crypto.randomBytes(32)`.
676
+ 2. Content is encrypted with the DEK using the configured scheme.
677
+ 3. For each recipient, the DEK is AES-256-GCM wrapped with their KEK.
678
+ 4. The manifest stores an array of `{ label, wrappedDek, nonce, tag }` entries.
679
+
680
+ ### Trial Decryption
681
+
682
+ On restore, `KeyResolver.resolveKeyForRecipients()` iterates **all** recipient
683
+ entries and attempts to unwrap each one. The first successful unwrap provides
684
+ the DEK. All entries are always tried -- there is no early exit, no index
685
+ leak, and no timing oracle that reveals which recipient matched.
686
+
687
+ ```
688
+ for each recipient entry:
689
+ try unwrapDek(entry, providedKey)
690
+ if success and no prior match: save result
691
+ if DEK_UNWRAP_FAILED: continue
692
+ if no match found: throw NO_MATCHING_RECIPIENT
693
+ ```
694
+
695
+ ### Key Rotation
696
+
697
+ `rotateKey()` re-wraps the DEK with a new KEK without touching data blobs:
698
+
699
+ 1. Unwrap DEK using `oldKey`.
700
+ 2. Wrap DEK with `newKey`.
701
+ 3. Replace the matched recipient entry.
702
+ 4. Increment `keyVersion` at both manifest and recipient level.
703
+
704
+ The old ciphertext blobs are never read. Rotation is a manifest-only mutation.
705
+
706
+ **Caveat**: rotation does not invalidate old ciphertext. An attacker with
707
+ both the old wrapped DEK (from a prior manifest commit) and the old KEK can
708
+ still decrypt. To fully revoke access, the old manifest commits must become
709
+ unreachable (e.g., via history rewrite + `git gc`).
710
+
711
+ ### Adding and Removing Recipients
712
+
713
+ - `addRecipient()`: unwraps the DEK with an existing KEK, wraps it with the
714
+ new recipient's KEK, and returns a new Manifest with the appended entry.
715
+ - `removeRecipient()`: removes the label from the recipients array. Cannot
716
+ remove the last recipient. Does not require a key (manifest-only mutation).
717
+
718
+ ---
719
+
720
+ ## Streaming Decompression
721
+
722
+ Plaintext+gzip, framed+gzip, and convergent+gzip restores use **streaming
723
+ decompression**. Compressed data is piped through the compression adapter's
724
+ `decompressStream()` method, which processes data incrementally without
725
+ buffering the full decompressed payload in memory. This applies to:
726
+
727
+ - Plain compressed restores (no encryption)
728
+ - Framed-encrypted + compressed restores
729
+ - Convergent-encrypted + compressed restores
730
+
731
+ The streaming approach keeps memory usage proportional to the chunk/frame size
732
+ rather than the total asset size. `whole` encrypted restores preserve the
733
+ whole-object authentication boundary and still use the bounded buffered path
734
+ for `restoreStream()` / `restore()`. Uncompressed `whole` `restoreFile()` streams
735
+ decryption into the temp-file publication path; `whole` + gzip preserves
736
+ auth-before-decompress and may buffer the encrypted compressed payload before
737
+ gunzip runs.
738
+
739
+ ---
740
+
741
+ ## CompressionPort Architecture
742
+
743
+ Compression in `git-cas` is fully abstracted behind the `CompressionPort`
744
+ interface. `CasService` has **zero platform-specific compression imports**.
745
+
746
+ ### Port Interface
747
+
748
+ ```
749
+ CompressionPort (abstract)
750
+ compressBuffer(buffer) -> Promise<Uint8Array>
751
+ decompressBuffer(buffer) -> Promise<Uint8Array>
752
+ compressStream(source) -> AsyncGenerator<Uint8Array>
753
+ decompressStream(source) -> AsyncGenerator<Uint8Array>
754
+ ```
755
+
756
+ ### NodeCompressionAdapter
757
+
758
+ The default adapter uses `node:zlib`:
759
+
760
+ - `compressBuffer` / `decompressBuffer`: promisified `gzip` / `gunzip`
761
+ - `compressStream`: `Readable.from(source).pipe(createGzip())`
762
+ - `decompressStream`: `Readable.from(source).pipe(createGunzip())` with
763
+ error forwarding from the input stream to the gunzip transform
764
+
765
+ ### Pluggability
766
+
767
+ Pass a custom adapter via the `compressionAdapter` constructor option:
768
+
769
+ ```js
770
+ import { FixedChunker } from '@git-stunts/git-cas';
771
+ import CasService from '@git-stunts/git-cas/service';
772
+
773
+ const cas = new CasService({
774
+ persistence, codec, crypto, observability,
775
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
776
+ compressionAdapter: new MyBrotliAdapter(),
777
+ });
778
+ ```
779
+
780
+ The only currently supported compression algorithm at the schema level is
781
+ `gzip`. The port abstraction exists to support future Bun-native, Deno-native,
782
+ or browser compression adapters without changing `CasService`.
783
+
784
+ ---
785
+
786
+ ## Direct CasService and Custom Port Contracts
787
+
788
+ Most applications should use the `ContentAddressableStore` facade. It supplies
789
+ Git persistence, runtime crypto, a JSON codec, a silent observer, fixed
790
+ chunking, gzip compression, and package-version manifest stamping by default.
791
+ Direct `CasService` construction is for tests, non-Git persistence experiments,
792
+ or applications that own every adapter boundary. For a checklist-style guide to
793
+ custom adapters, see [docs/EXTENDING.md](./docs/EXTENDING.md).
794
+
795
+ ### Minimal Direct Service
796
+
797
+ Direct `CasService` construction requires all domain ports, including the
798
+ chunker and compression adapter. Those two are optional only on the facade.
799
+
800
+ ```js
801
+ import {
802
+ FixedChunker,
803
+ JsonCodec,
804
+ NodeCompressionAdapter,
805
+ NodeCryptoAdapter,
806
+ SilentObserver,
807
+ } from '@git-stunts/git-cas';
808
+ import CasService from '@git-stunts/git-cas/service';
809
+
810
+ const service = new CasService({
811
+ persistence,
812
+ codec: new JsonCodec(),
813
+ crypto: new NodeCryptoAdapter(),
814
+ observability: new SilentObserver(),
815
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
816
+ compressionAdapter: new NodeCompressionAdapter(),
817
+ formatVersion: '6.0.0',
818
+ });
819
+ ```
820
+
821
+ ### Required Port Shape
822
+
823
+ | Port | Required Surface | Notes |
824
+ | :--- | :--- | :--- |
825
+ | `GitPersistencePort` | `writeBlob`, `writeTree`, `readBlob`, `readBlobStream`, `readTree` | Return and consume `Uint8Array` streams; `readBlobStream()` is required for bounded restore paths. |
826
+ | `CodecPort` | `encode`, `decode`, `extension` | `encode()` must return `Uint8Array`; JSON and CBOR are built in. |
827
+ | `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. |
828
+ | `ObservabilityPort` | `metric`, `log`, `span` | Use `SilentObserver`, `EventEmitterObserver`, or `StatsCollector` unless you need custom telemetry. |
829
+ | `ChunkingPort` | `chunk(source)`, `strategy`, `params` | Use `FixedChunker` or `CdcChunker`; direct service callers must inject one. |
830
+ | `CompressionPort` | `compressBuffer`, `decompressBuffer`, `compressStream`, `decompressStream` | Direct service callers must inject one even if stores do not request compression. |
831
+
832
+ The public byte contract is `Uint8Array`. Node `Buffer` values work at Node
833
+ boundaries because `Buffer` extends `Uint8Array`, but custom adapters should
834
+ not expose Buffer-only APIs in their portable contracts.
835
+
836
+ ### Runtime and Facade Split
837
+
838
+ The facade owns infrastructure defaults:
839
+
840
+ - `GitPersistenceAdapter` and `GitRefAdapter` wrap `@git-stunts/plumbing`.
841
+ - `createCryptoAdapter()` chooses Node, Bun-compatible, or Web Crypto support.
842
+ - `resolveChunker()` maps declarative `{ strategy: 'fixed' | 'cdc' }` config
843
+ into `FixedChunker` or `CdcChunker` instances.
844
+ - `NodeCompressionAdapter` is the default compression adapter.
845
+ - `formatVersion` is stamped from package metadata.
846
+
847
+ The domain service owns behavior after the ports are injected. It validates
848
+ constructor numeric ranges, rejects missing `chunker` and `compressionAdapter`,
849
+ and keeps runtime-specific imports out of the domain.
850
+
851
+ ---
852
+
853
+ ## Security Hardening Summary
854
+
855
+ The following security fixes have been applied across the release line. Each
856
+ row describes the fix and what it prevents.
857
+
858
+ | # | Fix | Prevents |
859
+ | :--- | :--- | :--- |
860
+ | 1 | Encrypted manifest metadata downgrade rejection | Attacker strips `encrypted: true` to bypass decryption |
861
+ | 2 | Algorithm allowlist (`aes-256-gcm` only) | Attacker substitutes a weaker or non-existent algorithm |
862
+ | 3 | Nonce/tag format validation (canonical base64, correct byte length) | Malformed metadata crashes the runtime or produces garbage |
863
+ | 4 | Framed record parse hardening (`ciphertextLength <= frameBytes`) | Oversized length field causes unbounded allocation |
864
+ | 5 | `maxRestoreBufferSize` enforcement for buffered `restore()` / `restoreStream()` paths | Unbounded memory allocation on large encrypted/compressed memory restores |
865
+ | 6 | `maxEncryptionBufferSize` / `maxDecryptionBufferSize` for Web Crypto | One-shot Web Crypto API exhausts memory on large payloads |
866
+ | 7 | KDF policy enforcement (bounded iterations, cost, salt, keyLength) | Attacker-controlled manifest requests extreme KDF work or weak params |
867
+ | 8 | Manifest integrity hash (`manifestHash` field) | Silent manifest corruption or codec round-trip bugs |
868
+ | 9 | CDC + encryption dedup warning | False confidence in dedup savings when ciphertext is pseudorandom |
869
+ | 10 | Orphaned blob tracking on `STREAM_ERROR` / `STORE_ERROR` | Lost blob OIDs after partial store failures |
870
+ | 11 | AAD binding (always active on all schemes) | Cross-manifest blob substitution and frame reordering attacks |
871
+ | 12 | Legacy scheme rejection at runtime | Downgrade to weaker v1/v2 scheme variants |
872
+ | 13 | Convergent encryption post-decrypt digest verification | Chunk substitution or corruption after decryption |
873
+ | 14 | Encrypted vault key verifier in `.vault.json` | Wrong passphrase accepted for an empty encrypted vault |
874
+
875
+ ---
876
+
877
+ ## Operational Tooling
878
+
879
+ The release and migration scripts are part of the supported operator surface.
880
+ They are intentionally separate from the runtime library so production callers
881
+ do not inherit release-time dependencies.
882
+
883
+ ### Migration
884
+
885
+ ```sh
886
+ npm run upgrade
887
+ printf '%s\n' 'my-secret' | node scripts/migrate-encryption.js --execute --passphrase-file -
888
+ node scripts/migrate-encryption.js --execute --key-file ./asset.key
889
+ ```
890
+
891
+ The migration script is dry-run by default. It maps legacy v2 scheme names to
892
+ current names when safe, and re-encrypts legacy v1 content when AAD must be
893
+ added. Prefer `--passphrase-file -`, `--passphrase-file <path>`, or
894
+ `--key-file` for full migrations. Inline `--passphrase` is accepted for
895
+ compatibility, but prints a warning because it can leak through shell history
896
+ and process listings. Privacy-enabled vaults accept vault-specific
897
+ passphrase/key options when the vault credential differs from the content
898
+ credential; prefer `--vault-passphrase-file` or `--vault-key-file` there too.
899
+
900
+ ### Release Verification
901
+
902
+ ```sh
903
+ npm test
904
+ npx eslint .
905
+ npm run release:verify -- --skip-jsr
906
+ ```
907
+
908
+ `release:verify` checks package metadata, exports, docs, tests, pack contents,
909
+ Docker runtime suites, and release-state invariants. Use `--skip-jsr` when JSR
910
+ publication is intentionally deferred or unavailable.
911
+
912
+ ### Build Metadata
913
+
914
+ ```sh
915
+ npm run stamp
916
+ npm pack --dry-run
917
+ ```
918
+
919
+ `npm run stamp` writes `build-info.json` from the current Git state. The file
920
+ is included in the npm package and is regenerated by `prepublishOnly`; it
921
+ should not be treated as source truth when the working tree has moved.
922
+
923
+ ---
924
+
925
+ ## Performance Baselines
926
+
927
+ The following baselines are published for the current release line.
928
+
929
+ | Strategy | Asset Size | Total Chunks | Store (ms) | Restore (ms) | Dedupe (%) |
930
+ | :--- | :--- | :--- | :--- | :--- | :--- |
931
+ | **Fixed (256K)** | 100 MiB | 400 | ~450 | ~300 | 0% |
932
+ | **CDC (256K avg)** | 100 MiB | ~390 | ~1200 | ~350 | 98%+ |
933
+
934
+ **Notes:**
935
+
936
+ - CDC store time includes Buzhash rolling hash overhead. Restore time is
937
+ comparable to fixed-size chunking because restore reads blobs by OID
938
+ regardless of how boundaries were chosen.
939
+ - CDC **normalization** (dual-mask) tightens the chunk size distribution but
940
+ does not materially affect throughput. The hash computation cost is the same;
941
+ only the mask comparison changes. The dedup benefit comes from more
942
+ predictable chunk sizes across versions.
943
+ - Encryption adds per-chunk (framed/convergent) or per-stream (whole)
944
+ AES-GCM overhead. On hardware with AES-NI, the throughput impact is
945
+ typically < 10%.
946
+ - Compression (gzip) can significantly reduce stored size but adds CPU cost
947
+ proportional to the data volume. Streaming decompression avoids
948
+ full-payload buffering for all restore paths.
949
+ - Parallel chunk restore (`concurrency > 1`) reduces wall-clock restore time
950
+ when the persistence adapter has I/O latency. Throughput scales linearly
951
+ up to the point where the adapter saturates.
952
+
953
+ ---
954
+
955
+ ## Configuration Reference
956
+
957
+ Direct `CasService` constructor options with types, defaults, and bounds. The
958
+ high-level `ContentAddressableStore` facade supplies defaults for `chunker`,
959
+ `compressionAdapter`, runtime crypto, and `formatVersion`.
960
+
961
+ | Option | Type | Default | Bounds | Description |
962
+ | :--- | :--- | :--- | :--- | :--- |
963
+ | `persistence` | `GitPersistencePort` | *required* | -- | Git blob/tree read/write adapter |
964
+ | `codec` | `CodecPort` | *required* | -- | Manifest serialization (JSON or CBOR) |
965
+ | `crypto` | `CryptoPort` | *required* | -- | Encryption, hashing, KDF adapter |
966
+ | `observability` | `ObservabilityPort` | *required* | Must implement `metric()`, `log()`, `span()` | Metrics, logging, tracing |
967
+ | `chunkSize` | `number` | `262144` (256 KiB) | Integer in `[1024, 104857600]` (1 KiB -- 100 MiB) | Chunk size for fixed chunking; warning above 10 MiB |
968
+ | `merkleThreshold` | `number` | `1000` | Integer >= 1 | Chunk count above which Merkle manifests are used |
969
+ | `concurrency` | `number` | `1` | Integer in `[1, 64]` | Max parallel chunk I/O operations (PrefetchWindow size) |
970
+ | `chunker` | `ChunkingPort` | *required* | -- | Chunking strategy instance (`FixedChunker` or `CdcChunker`) |
971
+ | `maxRestoreBufferSize` | `number` | `536870912` (512 MiB) | Integer >= 1024 | Max bytes for buffered restore (encrypted/compressed) |
972
+ | `compressionAdapter` | `CompressionPort` | *required* | -- | Compression implementation |
973
+ | `formatVersion` | `string` | -- | Semver (`/^\d+\.\d+\.\d+$/`) | Version stamp for new manifests (distinct from structural `version`) |
974
+
975
+ ### store() Options
976
+
977
+ | Option | Type | Default | Description |
978
+ | :--- | :--- | :--- | :--- |
979
+ | `source` | `AsyncIterable<Uint8Array>` | *required* | Input byte stream |
980
+ | `slug` | `string` | *required* | Asset identifier |
981
+ | `filename` | `string` | *required* | Original filename |
982
+ | `encryptionKey` | `Uint8Array` | -- | 32-byte key (mutually exclusive with `passphrase` and `recipients`) |
983
+ | `passphrase` | `string` | -- | Derive key via KDF (mutually exclusive with `encryptionKey` and `recipients`) |
984
+ | `encryption` | `object` | -- | `{ scheme?, frameBytes?, convergent? }` |
985
+ | `encryption.scheme` | `string` | Auto: `convergent` for CDC, `framed` otherwise | `'whole'`, `'framed'`, or `'convergent'` |
986
+ | `encryption.frameBytes` | `number` | `65536` (64 KiB) | Frame size for the `framed` scheme; max 64 MiB |
987
+ | `encryption.convergent` | `boolean` | -- | Explicit convergent opt-in/opt-out (auto-selected for CDC chunkers) |
988
+ | `kdfOptions` | `object` | -- | `{ algorithm?, iterations?, cost?, blockSize?, parallelization? }` |
989
+ | `compression` | `object` | -- | `{ algorithm: 'gzip' }` |
990
+ | `recipients` | `Array<{label, key}>` | -- | Envelope recipients (mutually exclusive with key/passphrase) |
991
+
992
+ ### CdcChunker Options
993
+
994
+ | Option | Type | Default | Bounds | Description |
995
+ | :--- | :--- | :--- | :--- | :--- |
996
+ | `targetChunkSize` | `number` | `262144` | Must be in `[min, max]` | Target average chunk size |
997
+ | `minChunkSize` | `number` | `65536` | Must not exceed `maxChunkSize` | Minimum chunk size |
998
+ | `maxChunkSize` | `number` | `1048576` | Hard cap at 100 MiB | Maximum chunk size |
999
+ | `normalized` | `boolean` | `true` | -- | Enable FastCDC dual-mask normalization |
1000
+
1001
+ ---
1002
+
1003
+ For orientation, quick starts, and common usage patterns, see [GUIDE.md](./GUIDE.md).
1004
+
1005
+ For the security model and threat analysis, see [SECURITY.md](./SECURITY.md)
1006
+ and [docs/THREAT_MODEL.md](./docs/THREAT_MODEL.md).