@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
package/docs/API.md ADDED
@@ -0,0 +1,2254 @@
1
+ # API Reference
2
+
3
+ This document provides the complete API reference for git-cas.
4
+
5
+ For cryptographic design, nonce and KDF guidance, and security-relevant
6
+ implementation details, see [SECURITY.md](../SECURITY.md). For attacker models,
7
+ trust boundaries, exposed metadata, and explicit non-goals, see
8
+ [docs/THREAT_MODEL.md](./THREAT_MODEL.md).
9
+
10
+ All public byte-oriented APIs use `Uint8Array`. Node callers can still pass
11
+ `Buffer` instances because `Buffer` extends `Uint8Array`, but portable code
12
+ should treat restored data, chunker output, codec output, and keys as
13
+ `Uint8Array`.
14
+
15
+ ## Table of Contents
16
+
17
+ 1. [ContentAddressableStore](#contentaddressablestore)
18
+ 2. [Vault](#vault)
19
+ 3. [CasService](#casservice)
20
+ 4. [Events](#events)
21
+ 5. [Value Objects](#value-objects)
22
+ 6. [Ports](#ports)
23
+ 7. [Codecs](#codecs)
24
+ 8. [Error Codes](#error-codes)
25
+
26
+ ## ContentAddressableStore
27
+
28
+ The main facade class providing high-level API for content-addressable storage.
29
+
30
+ ### open
31
+
32
+ ```javascript
33
+ await ContentAddressableStore.open({ cwd, chunkSize, policy });
34
+ ```
35
+
36
+ Creates the default JSON-codec facade from a Git working directory. This is the
37
+ recommended entry point for normal application code.
38
+
39
+ **Parameters:**
40
+
41
+ - `cwd` (optional): Git working directory (default: `"."`)
42
+ - `chunkSize` (optional): Chunk size in bytes
43
+ - `policy` (optional): Resilience policy
44
+ - Any other `ContentAddressableStore` constructor option except `plumbing`
45
+
46
+ **Returns:** `Promise<ContentAddressableStore>`
47
+
48
+ **Example:**
49
+
50
+ ```javascript
51
+ import ContentAddressableStore from '@git-stunts/git-cas';
52
+
53
+ const cas = await ContentAddressableStore.open({ cwd: '/path/to/repo' });
54
+ ```
55
+
56
+ ### Constructor
57
+
58
+ ```javascript
59
+ new ContentAddressableStore(options);
60
+ ```
61
+
62
+ **Parameters:**
63
+
64
+ - `options.plumbing` (required): Plumbing instance from `@git-stunts/plumbing`
65
+ - `options.chunkSize` (optional): Chunk size in bytes (default: 262144 / 256 KiB)
66
+ - `options.codec` (optional): CodecPort implementation (default: JsonCodec)
67
+ - `options.crypto` (optional): CryptoPort implementation (default: auto-detected)
68
+ - `options.observability` (optional): ObservabilityPort implementation (default: SilentObserver)
69
+ - `options.policy` (optional): Resilience policy from `@git-stunts/alfred` for Git I/O
70
+ - `options.merkleThreshold` (optional): Chunk count threshold for Merkle manifests (default: 1000)
71
+ - `options.concurrency` (optional): Maximum parallel chunk I/O operations (default: 1)
72
+ - `options.chunking` (optional): Declarative chunking strategy config `{ strategy: 'fixed'|'cdc', chunkSize?, targetChunkSize?, minChunkSize?, maxChunkSize? }`
73
+ - `options.chunker` (optional): Pre-built ChunkingPort instance (advanced; overrides `chunking`)
74
+ - `options.maxRestoreBufferSize` (optional): Max bytes for buffered encrypted/compressed restore (default: 536870912 / 512 MiB)
75
+ - `options.maxBlobSize` (optional): Max bytes for metadata blob reads (default: 10485760 / 10 MiB)
76
+ - `options.compressionAdapter` (optional): CompressionPort implementation (default: NodeCompressionAdapter)
77
+
78
+ **Example:**
79
+
80
+ ```javascript
81
+ import ContentAddressableStore from '@git-stunts/git-cas';
82
+ import GitPlumbing from '@git-stunts/plumbing';
83
+
84
+ const plumbing = await GitPlumbing.createDefault({ cwd: '/path/to/repo' });
85
+ const cas = new ContentAddressableStore({ plumbing });
86
+ ```
87
+
88
+ ### Factory Methods
89
+
90
+ Use these factories when you already have a custom Git plumbing instance.
91
+
92
+ #### createJson
93
+
94
+ ```javascript
95
+ ContentAddressableStore.createJson({ plumbing, chunkSize, policy, chunking });
96
+ ```
97
+
98
+ Creates a CAS instance with JSON codec.
99
+
100
+ **Parameters:**
101
+
102
+ - `plumbing` (required): Plumbing instance
103
+ - `chunkSize` (optional): Chunk size in bytes
104
+ - `policy` (optional): Resilience policy
105
+ - Any other `ContentAddressableStore` constructor option except `codec`
106
+
107
+ **Returns:** `ContentAddressableStore`
108
+
109
+ **Example:**
110
+
111
+ ```javascript
112
+ const cas = ContentAddressableStore.createJson({ plumbing });
113
+ ```
114
+
115
+ #### createCbor
116
+
117
+ ```javascript
118
+ ContentAddressableStore.createCbor({ plumbing, chunkSize, policy, chunking });
119
+ ```
120
+
121
+ Creates a CAS instance with CBOR codec.
122
+
123
+ **Parameters:**
124
+
125
+ - `plumbing` (required): Plumbing instance
126
+ - `chunkSize` (optional): Chunk size in bytes
127
+ - `policy` (optional): Resilience policy
128
+ - Any other `ContentAddressableStore` constructor option except `codec`
129
+
130
+ **Returns:** `ContentAddressableStore`
131
+
132
+ **Example:**
133
+
134
+ ```javascript
135
+ const cas = ContentAddressableStore.createCbor({ plumbing });
136
+ ```
137
+
138
+ ### Methods
139
+
140
+ #### getService
141
+
142
+ ```javascript
143
+ await cas.getService();
144
+ ```
145
+
146
+ Lazily initializes and returns the underlying CasService instance.
147
+
148
+ **Returns:** `Promise<CasService>`
149
+
150
+ **Example:**
151
+
152
+ ```javascript
153
+ const service = await cas.getService();
154
+ ```
155
+
156
+ #### getVaultService
157
+
158
+ ```javascript
159
+ await cas.getVaultService();
160
+ ```
161
+
162
+ Lazily initializes and returns the underlying VaultService instance.
163
+
164
+ **Returns:** `Promise<VaultService>`
165
+
166
+ **Example:**
167
+
168
+ ```javascript
169
+ const vaultService = await cas.getVaultService();
170
+ ```
171
+
172
+ #### store
173
+
174
+ ```javascript
175
+ await cas.store({
176
+ source,
177
+ slug,
178
+ filename,
179
+ encryptionKey,
180
+ passphrase,
181
+ encryption,
182
+ kdfOptions,
183
+ compression,
184
+ chunking,
185
+ recipients,
186
+ merkleThreshold,
187
+ });
188
+ ```
189
+
190
+ Stores content from an async iterable source.
191
+
192
+ **Parameters:**
193
+
194
+ - `source` (required): `AsyncIterable<Uint8Array>` - Content stream
195
+ - `slug` (required): `string` - Unique identifier for the asset
196
+ - `filename` (required): `string` - Original filename
197
+ - `encryptionKey` (optional): `Uint8Array` - 32-byte encryption key
198
+ - `passphrase` (optional): `string` - Derive encryption key from passphrase (alternative to `encryptionKey`)
199
+ - `encryption` (optional): `Object` - Explicit encryption mode selection for encrypted stores. If omitted, encrypted stores default to `convergent` for CDC chunkers and `framed` otherwise
200
+ - `encryption.scheme` (optional): `'whole' | 'framed' | 'convergent'` - `whole` is the explicit compatibility whole-object AES-GCM format; `framed` stores independently authenticated frames so restore can stream verified plaintext incrementally and is the fixed-chunk default; `convergent` derives per-chunk keys from content, enabling deduplication across encrypted stores and is the default when using CDC chunking with encryption
201
+ - `encryption.frameBytes` (optional): `number` - Plaintext bytes per framed record (default `65536`)
202
+ - `encryption.convergent` (optional): `boolean` - Explicit convergent opt-in/opt-out when `encryption.scheme` is omitted
203
+ - `kdfOptions` (optional): `Object` - KDF options when using `passphrase` (`{ algorithm, iterations, cost, ... }`). New passphrase stores default to PBKDF2 `600000` iterations or scrypt `N=131072`, and out-of-policy values fail with `KDF_POLICY_VIOLATION`
204
+ - `compression` (optional): `{ algorithm: 'gzip' }` - Enable compression before encryption/chunking
205
+ - `chunking` (optional): `{ strategy: 'fixed' | 'cdc', chunkSize?, targetChunkSize?, minChunkSize?, maxChunkSize?, normalized? }` - Per-operation chunking override. It affects only this store call; the facade's default chunker is unchanged
206
+ - `recipients` (optional): `Array<{ label: string, key: Uint8Array }>` - Envelope recipients for multi-recipient encryption (mutually exclusive with `encryptionKey`/`passphrase`)
207
+ - `merkleThreshold` (optional): `number` - Per-operation chunk count threshold used when this manifest is later published with `createTree()`
208
+
209
+ **Returns:** `Promise<Manifest>`
210
+
211
+ **Throws:**
212
+
213
+ - `CasError` with code `INVALID_KEY_TYPE` if encryptionKey is not a Uint8Array
214
+ - `CasError` with code `INVALID_KEY_LENGTH` if encryptionKey is not 32 bytes
215
+ - `CasError` with code `STREAM_ERROR` if the source stream fails
216
+ - `CasError` with code `INVALID_OPTIONS` if both `passphrase` and `encryptionKey` are provided
217
+ - `CasError` with code `INVALID_OPTIONS` if an unsupported encryption scheme is specified
218
+ - `CasError` with code `INVALID_OPTIONS` if an unsupported compression algorithm is specified
219
+
220
+ **Example:**
221
+
222
+ ```javascript
223
+ import { createReadStream } from 'node:fs';
224
+ import { randomBytes } from 'node:crypto';
225
+
226
+ const stream = createReadStream('/path/to/file.txt');
227
+ const key = randomBytes(32);
228
+ const manifest = await cas.store({
229
+ source: stream,
230
+ slug: 'my-asset',
231
+ filename: 'file.txt',
232
+ encryptionKey: key,
233
+ });
234
+ ```
235
+
236
+ #### storeFile
237
+
238
+ ```javascript
239
+ await cas.storeFile({
240
+ filePath,
241
+ slug,
242
+ filename,
243
+ encryptionKey,
244
+ passphrase,
245
+ encryption,
246
+ kdfOptions,
247
+ compression,
248
+ chunking,
249
+ recipients,
250
+ merkleThreshold,
251
+ });
252
+ ```
253
+
254
+ Convenience method that opens a file and stores it.
255
+
256
+ **Parameters:**
257
+
258
+ - `filePath` (required): `string` - Path to file
259
+ - `slug` (required): `string` - Unique identifier for the asset
260
+ - `filename` (optional): `string` - Filename (defaults to basename of filePath)
261
+ - `encryptionKey` (optional): `Uint8Array` - 32-byte encryption key
262
+ - `passphrase` (optional): `string` - Derive encryption key from passphrase
263
+ - `encryption` (optional): `Object` - Explicit encryption mode selection for encrypted stores. If omitted, encrypted stores default to `convergent` for CDC chunkers and `framed` otherwise
264
+ - `encryption.scheme` (optional): `'whole' | 'framed' | 'convergent'` - `whole` is the explicit compatibility whole-object AES-GCM format; `framed` stores independently authenticated frames so restore can stream verified plaintext incrementally and is the fixed-chunk default; `convergent` derives per-chunk keys from content, enabling deduplication across encrypted stores and is the default when using CDC chunking with encryption
265
+ - `encryption.frameBytes` (optional): `number` - Plaintext bytes per framed record (default `65536`)
266
+ - `encryption.convergent` (optional): `boolean` - Explicit convergent opt-in/opt-out when `encryption.scheme` is omitted
267
+ - `kdfOptions` (optional): `Object` - KDF options when using `passphrase`. New passphrase stores default to PBKDF2 `600000` iterations or scrypt `N=131072`, and out-of-policy values fail with `KDF_POLICY_VIOLATION`
268
+ - `compression` (optional): `{ algorithm: 'gzip' }` - Enable compression
269
+ - `chunking` (optional): `{ strategy: 'fixed' | 'cdc', chunkSize?, targetChunkSize?, minChunkSize?, maxChunkSize?, normalized? }` - Per-operation chunking override. It affects only this file store; the facade's default chunker is unchanged
270
+ - `recipients` (optional): `Array<{ label: string, key: Uint8Array }>` - Envelope recipients for multi-recipient encryption (mutually exclusive with `encryptionKey`/`passphrase`)
271
+ - `merkleThreshold` (optional): `number` - Per-operation chunk count threshold used when this manifest is later published with `createTree()`
272
+
273
+ **Returns:** `Promise<Manifest>`
274
+
275
+ **Throws:** Same as `store()`
276
+
277
+ **Example:**
278
+
279
+ ```javascript
280
+ const manifest = await cas.storeFile({
281
+ filePath: '/path/to/file.txt',
282
+ slug: 'my-asset',
283
+ encryptionKey: key,
284
+ chunking: { strategy: 'cdc' },
285
+ });
286
+ ```
287
+
288
+ #### restore
289
+
290
+ ```javascript
291
+ await cas.restore({ manifest, encryptionKey, passphrase });
292
+ ```
293
+
294
+ Restores content from a manifest and returns the buffer.
295
+
296
+ For encrypted content, `whole` still buffers the full ciphertext before
297
+ authenticating and decrypting. `framed` restores authenticated plaintext
298
+ frame-by-frame and only the final `restore()` collector buffers the result.
299
+
300
+ **Parameters:**
301
+
302
+ - `manifest` (required): `Manifest` - Manifest object
303
+ - `encryptionKey` (optional): `Uint8Array` - 32-byte encryption key (required if content is encrypted)
304
+ - `passphrase` (optional): `string` - Passphrase for KDF-based decryption (alternative to `encryptionKey`)
305
+
306
+ **Returns:** `Promise<{ buffer: Uint8Array, bytesWritten: number }>`
307
+
308
+ **Throws:**
309
+
310
+ - `CasError` with code `MISSING_KEY` if content is encrypted but no key provided
311
+ - `CasError` with code `INVALID_KEY_TYPE` if encryptionKey is not a Uint8Array
312
+ - `CasError` with code `INVALID_KEY_LENGTH` if encryptionKey is not 32 bytes
313
+ - `CasError` with code `INTEGRITY_ERROR` if chunk digest verification fails
314
+ - `CasError` with code `INTEGRITY_ERROR` if decryption fails
315
+ - `CasError` with code `INTEGRITY_ERROR` if decompression fails
316
+ - `CasError` with code `INVALID_OPTIONS` if both `passphrase` and `encryptionKey` are provided
317
+
318
+ **Example:**
319
+
320
+ ```javascript
321
+ const { buffer, bytesWritten } = await cas.restore({ manifest });
322
+ ```
323
+
324
+ #### restoreFile
325
+
326
+ ```javascript
327
+ await cas.restoreFile({ manifest, encryptionKey, passphrase, outputPath, baseDirectory });
328
+ ```
329
+
330
+ Restores content from a manifest and writes it to a file.
331
+
332
+ **Security Boundary:** `baseDirectory` is required. The `outputPath` is resolved
333
+ relative to `baseDirectory`, and the system will throw a
334
+ `SECURITY_BOUNDARY_VIOLATION` if the canonical path escapes the base directory,
335
+ including through symlinked path components.
336
+
337
+ For plaintext, `framed`, `convergent`, and uncompressed `whole`, this writes
338
+ from a streaming restore path. For `whole`, bytes are verified, streamed through
339
+ AES-GCM decryption into a temporary sibling path, and renamed into place only
340
+ after the pipeline completes successfully. This improves file restores without
341
+ changing the contract of `restoreStream()`, which remains buffered for `whole`.
342
+
343
+ For `whole` + gzip, authentication must complete before gunzip sees plaintext.
344
+ That path preserves the auth-before-decompress boundary and may buffer the
345
+ encrypted compressed payload; use `framed` or `convergent` for large compressed
346
+ encrypted assets.
347
+ On Web Crypto runtimes, the whole-object decrypt step is still internally
348
+ one-shot; the parity improvement is that this path now stays bounded by the
349
+ adapter's decryption buffer limit instead of collecting ciphertext without a
350
+ guard.
351
+
352
+ **Parameters:**
353
+
354
+ - `manifest` (required): `Manifest` - Manifest object
355
+ - `encryptionKey` (optional): `Uint8Array` - 32-byte encryption key
356
+ - `passphrase` (optional): `string` - Passphrase for KDF-based decryption
357
+ - `outputPath` (required): `string` - Path to write the restored file
358
+ - `baseDirectory` (required): `string` - Directory boundary that `outputPath` must stay inside
359
+
360
+ **Returns:** `Promise<{ bytesWritten: number }>`
361
+
362
+ **Throws:** Same as `restore()`
363
+
364
+ **Example:**
365
+
366
+ ```javascript
367
+ await cas.restoreFile({
368
+ manifest,
369
+ outputPath: 'restored.txt',
370
+ baseDirectory: process.cwd(),
371
+ });
372
+ ```
373
+
374
+ #### createTree
375
+
376
+ ```javascript
377
+ await cas.createTree({ manifest, merkleThreshold });
378
+ ```
379
+
380
+ Creates a Git tree object from a manifest.
381
+
382
+ **Parameters:**
383
+
384
+ - `manifest` (required): `Manifest` - Manifest object
385
+ - `merkleThreshold` (optional): `number` - Override the constructor-level chunk count threshold for this tree publication
386
+
387
+ **Returns:** `Promise<string>` - Git tree OID
388
+
389
+ **Example:**
390
+
391
+ ```javascript
392
+ const treeOid = await cas.createTree({ manifest });
393
+ ```
394
+
395
+ #### verifyIntegrity
396
+
397
+ ```javascript
398
+ await cas.verifyIntegrity(manifest);
399
+ ```
400
+
401
+ Verifies the integrity of stored content by re-hashing all chunks. For
402
+ encrypted manifests, pass the same decryption credentials you would use for
403
+ `restore()` so the ciphertext is also authenticated. `whole` authenticates
404
+ the full ciphertext as one unit, `framed` authenticates every stored frame,
405
+ and `convergent` decrypts each chunk and verifies its plaintext digest.
406
+
407
+ **Parameters:**
408
+
409
+ - `manifest` (required): `Manifest` - Manifest object
410
+ - `options` (optional): `object`
411
+ - `options.encryptionKey` (optional): `Uint8Array` - 32-byte key for encrypted manifests
412
+ - `options.passphrase` (optional): `string` - Passphrase for KDF-based encrypted manifests
413
+
414
+ **Returns:** `Promise<boolean>` - True if all chunks pass verification
415
+
416
+ **Example:**
417
+
418
+ ```javascript
419
+ const isValid = await cas.verifyIntegrity(manifest);
420
+ if (!isValid) {
421
+ console.log('Integrity check failed');
422
+ }
423
+ ```
424
+
425
+ Encrypted example:
426
+
427
+ ```javascript
428
+ const isValid = await cas.verifyIntegrity(manifest, {
429
+ encryptionKey: key,
430
+ });
431
+ ```
432
+
433
+ #### readManifest
434
+
435
+ ```javascript
436
+ await cas.readManifest({ treeOid });
437
+ ```
438
+
439
+ Reads a Git tree, locates the manifest entry, decodes it, and returns a validated Manifest value object.
440
+
441
+ **Parameters:**
442
+
443
+ - `treeOid` (required): `string` - Git tree OID
444
+
445
+ **Returns:** `Promise<Manifest>` - Frozen, Zod-validated Manifest
446
+
447
+ **Throws:**
448
+
449
+ - `CasError` with code `MANIFEST_NOT_FOUND` if no manifest entry exists in the tree
450
+ - `CasError` with code `GIT_ERROR` if the underlying Git command fails
451
+ - Zod validation error if the manifest blob is corrupt
452
+
453
+ **Example:**
454
+
455
+ ```javascript
456
+ const treeOid = 'a1b2c3d4e5f6...';
457
+ const manifest = await cas.readManifest({ treeOid });
458
+ console.log(manifest.slug); // "photos/vacation"
459
+ console.log(manifest.chunks); // array of Chunk objects
460
+ ```
461
+
462
+ #### restoreStream
463
+
464
+ ```javascript
465
+ const stream = cas.restoreStream({ manifest, encryptionKey, passphrase });
466
+ ```
467
+
468
+ Restores content from a manifest as an async iterable of Uint8Array chunks.
469
+
470
+ For unencrypted, uncompressed files this is true per-chunk streaming with O(chunkSize) memory. `whole` encrypted paths still collect internally before yielding, while `framed` encrypted payloads authenticate and emit plaintext incrementally.
471
+
472
+ **Parameters:**
473
+
474
+ - `manifest` (required): `Manifest` - Manifest object
475
+ - `encryptionKey` (optional): `Uint8Array` - 32-byte encryption key (required if content is encrypted)
476
+ - `passphrase` (optional): `string` - Passphrase for KDF-based decryption (alternative to `encryptionKey`)
477
+
478
+ **Returns:** `AsyncIterable<Uint8Array>`
479
+
480
+ **Throws:**
481
+
482
+ - `CasError` with code `MISSING_KEY` if content is encrypted but no key provided
483
+ - `CasError` with code `INTEGRITY_ERROR` if chunk verification or decryption fails
484
+
485
+ **Example:**
486
+
487
+ ```javascript
488
+ for await (const chunk of cas.restoreStream({ manifest })) {
489
+ process.stdout.write(chunk);
490
+ }
491
+ ```
492
+
493
+ #### inspectAsset
494
+
495
+ ```javascript
496
+ await cas.inspectAsset({ treeOid });
497
+ ```
498
+
499
+ Reads a manifest from a Git tree and returns inspection metadata. Does not perform any destructive Git operations.
500
+
501
+ **Parameters:**
502
+
503
+ - `treeOid` (required): `string` - Git tree OID of the asset
504
+
505
+ **Returns:** `Promise<{ slug: string, chunksOrphaned: number }>`
506
+
507
+ **Throws:**
508
+
509
+ - `CasError` with code `MANIFEST_NOT_FOUND` if the tree has no manifest
510
+ - `CasError` with code `GIT_ERROR` if the underlying Git command fails
511
+
512
+ **Example:**
513
+
514
+ ```javascript
515
+ const { slug, chunksOrphaned } = await cas.inspectAsset({ treeOid });
516
+ console.log(`Asset "${slug}" has ${chunksOrphaned} chunks`);
517
+ ```
518
+
519
+ #### diffManifests (static)
520
+
521
+ ```javascript
522
+ ContentAddressableStore.diffManifests(oldManifest, newManifest);
523
+ ```
524
+
525
+ Compares two manifests by chunk digest to find added, removed, and unchanged chunks. Pure function — no I/O. Does not require initialization.
526
+
527
+ **Parameters:**
528
+
529
+ - `oldManifest` (required): `Manifest` - Previous manifest
530
+ - `newManifest` (required): `Manifest` - Updated manifest
531
+
532
+ **Returns:** `ManifestDiffResult` — object with `added`, `removed`, and `unchanged` chunk arrays
533
+
534
+ **Example:**
535
+
536
+ ```javascript
537
+ const diff = ContentAddressableStore.diffManifests(oldManifest, newManifest);
538
+ console.log(`Added: ${diff.added.length}, Removed: ${diff.removed.length}`);
539
+ ```
540
+
541
+ #### addRecipient
542
+
543
+ ```javascript
544
+ await cas.addRecipient({ manifest, existingKey, newRecipientKey, label });
545
+ ```
546
+
547
+ Adds a recipient to an envelope-encrypted manifest. Unwraps the DEK using `existingKey`, then re-wraps it with `newRecipientKey` for the new recipient.
548
+
549
+ **Parameters:**
550
+
551
+ - `manifest` (required): `Manifest` - Envelope-encrypted manifest
552
+ - `existingKey` (required): `Uint8Array` - KEK of an existing recipient (used to unwrap the DEK)
553
+ - `newRecipientKey` (required): `Uint8Array` - KEK for the new recipient
554
+ - `label` (required): `string` - Label for the new recipient
555
+
556
+ **Returns:** `Promise<Manifest>` - Updated manifest with the new recipient entry
557
+
558
+ **Throws:**
559
+
560
+ - `CasError` with code `INVALID_OPTIONS` if manifest has no recipients
561
+ - `CasError` with code `RECIPIENT_ALREADY_EXISTS` if label is a duplicate
562
+ - `CasError` with code `DEK_UNWRAP_FAILED` if existingKey doesn't match any recipient
563
+
564
+ **Example:**
565
+
566
+ ```javascript
567
+ const updated = await cas.addRecipient({
568
+ manifest,
569
+ existingKey: aliceKey,
570
+ newRecipientKey: bobKey,
571
+ label: 'bob',
572
+ });
573
+ ```
574
+
575
+ #### removeRecipient
576
+
577
+ ```javascript
578
+ await cas.removeRecipient({ manifest, label });
579
+ ```
580
+
581
+ Removes a recipient from an envelope-encrypted manifest.
582
+
583
+ **Parameters:**
584
+
585
+ - `manifest` (required): `Manifest` - Envelope-encrypted manifest
586
+ - `label` (required): `string` - Label of the recipient to remove
587
+
588
+ **Returns:** `Promise<Manifest>` - Updated manifest without the removed recipient
589
+
590
+ **Throws:**
591
+
592
+ - `CasError` with code `RECIPIENT_NOT_FOUND` if label doesn't exist
593
+ - `CasError` with code `CANNOT_REMOVE_LAST_RECIPIENT` if only one recipient remains
594
+
595
+ **Example:**
596
+
597
+ ```javascript
598
+ const updated = await cas.removeRecipient({ manifest, label: 'bob' });
599
+ ```
600
+
601
+ #### listRecipients
602
+
603
+ ```javascript
604
+ await cas.listRecipients(manifest);
605
+ ```
606
+
607
+ Lists recipient labels from an envelope-encrypted manifest.
608
+
609
+ **Parameters:**
610
+
611
+ - `manifest` (required): `Manifest` - Manifest to inspect
612
+
613
+ **Returns:** `Promise<string[]>` - Recipient labels, or empty array if not envelope-encrypted
614
+
615
+ **Example:**
616
+
617
+ ```javascript
618
+ const labels = await cas.listRecipients(manifest);
619
+ console.log('Recipients:', labels.join(', '));
620
+ ```
621
+
622
+ #### collectReferencedChunks
623
+
624
+ ```javascript
625
+ await cas.collectReferencedChunks({ treeOids });
626
+ ```
627
+
628
+ Aggregates referenced chunk blob OIDs across multiple stored assets. Analysis only — does not delete or modify anything.
629
+
630
+ **Parameters:**
631
+
632
+ - `treeOids` (required): `Array<string>` - Git tree OIDs to analyze
633
+
634
+ **Returns:** `Promise<{ referenced: Set<string>, total: number }>`
635
+
636
+ - `referenced` — deduplicated Set of all chunk blob OIDs across the given trees
637
+ - `total` — total number of chunk references (before deduplication)
638
+
639
+ **Throws:**
640
+
641
+ - `CasError` with code `MANIFEST_NOT_FOUND` if any `treeOid` lacks a manifest (fail closed)
642
+ - `CasError` with code `GIT_ERROR` if the underlying Git command fails
643
+
644
+ **Example:**
645
+
646
+ ```javascript
647
+ const { referenced, total } = await cas.collectReferencedChunks({
648
+ treeOids: [treeOid1, treeOid2, treeOid3],
649
+ });
650
+ console.log(`${referenced.size} unique blobs across ${total} total chunk references`);
651
+ ```
652
+
653
+ #### deleteAsset
654
+
655
+ > **Deprecated.** Use [`inspectAsset`](#inspectasset) instead.
656
+
657
+ ```javascript
658
+ await cas.deleteAsset({ treeOid });
659
+ ```
660
+
661
+ Returns logical deletion metadata for an asset. Does not perform any destructive Git operations — the caller must remove refs, and physical deletion requires `git gc --prune`.
662
+
663
+ **Parameters:**
664
+
665
+ - `treeOid` (required): `string` - Git tree OID
666
+
667
+ **Returns:** `Promise<{ slug: string, chunksOrphaned: number }>`
668
+
669
+ **Throws:**
670
+
671
+ - `CasError` with code `MANIFEST_NOT_FOUND` (delegates to `readManifest`)
672
+ - `CasError` with code `GIT_ERROR` if the underlying Git command fails
673
+
674
+ **Example:**
675
+
676
+ ```javascript
677
+ const { slug, chunksOrphaned } = await cas.deleteAsset({ treeOid });
678
+ console.log(`Asset "${slug}" has ${chunksOrphaned} chunks to clean up`);
679
+ // Caller must remove refs pointing to treeOid; run `git gc --prune` to reclaim space
680
+ ```
681
+
682
+ #### deriveKey
683
+
684
+ ```javascript
685
+ await cas.deriveKey(options);
686
+ ```
687
+
688
+ Derives an encryption key from a passphrase using PBKDF2 or scrypt. PBKDF2 is
689
+ available across Node, Bun, and Web Crypto runtimes. scrypt requires a
690
+ Node/Bun-compatible crypto adapter; Web Crypto runtimes report an explicit
691
+ capability error.
692
+
693
+ **Parameters:**
694
+
695
+ - `options.passphrase` (required): `string` - The passphrase
696
+ - `options.salt` (optional): `Uint8Array` - Salt (random if omitted)
697
+ - `options.algorithm` (optional): `'pbkdf2' | 'scrypt'` - KDF algorithm (default: `'pbkdf2'`)
698
+ - `options.iterations` (optional): `number` - PBKDF2 iterations (default: 600000)
699
+ - `options.cost` (optional): `number` - scrypt cost parameter N (default: 131072)
700
+ - `options.blockSize` (optional): `number` - scrypt block size r (default: 8)
701
+ - `options.parallelization` (optional): `number` - scrypt parallelization p (default: 1)
702
+ - `options.keyLength` (optional): `number` - Derived key length (default: 32)
703
+
704
+ **Returns:** `Promise<{ key: Uint8Array, salt: Uint8Array, params: Object }>`
705
+
706
+ - `key` — the derived 32-byte encryption key
707
+ - `salt` — the salt used (save this for re-derivation)
708
+ - `params` — full KDF parameters object (stored in manifest when using `passphrase` option)
709
+
710
+ **Example:**
711
+
712
+ ```javascript
713
+ const { key, salt, params } = await cas.deriveKey({
714
+ passphrase: 'my secret passphrase',
715
+ algorithm: 'pbkdf2',
716
+ iterations: 600000,
717
+ });
718
+
719
+ // Use the derived key for encryption
720
+ const manifest = await cas.storeFile({
721
+ filePath: '/path/to/file.txt',
722
+ slug: 'my-asset',
723
+ encryptionKey: key,
724
+ });
725
+ ```
726
+
727
+ #### findOrphanedChunks
728
+
729
+ > **Deprecated.** Use [`collectReferencedChunks`](#collectreferencedchunks) instead.
730
+
731
+ ```javascript
732
+ await cas.findOrphanedChunks({ treeOids });
733
+ ```
734
+
735
+ Aggregates all chunk blob OIDs referenced across multiple assets and returns a report. Analysis only — does not delete or modify anything.
736
+
737
+ **Parameters:**
738
+
739
+ - `treeOids` (required): `Array<string>` - Array of Git tree OIDs
740
+
741
+ **Returns:** `Promise<{ referenced: Set<string>, total: number }>`
742
+
743
+ - `referenced` — deduplicated Set of all chunk blob OIDs across the given trees
744
+ - `total` — total number of chunk references (before deduplication)
745
+
746
+ **Throws:**
747
+
748
+ - `CasError` with code `MANIFEST_NOT_FOUND` if any `treeOid` lacks a manifest (fail closed)
749
+ - `CasError` with code `GIT_ERROR` if the underlying Git command fails
750
+
751
+ **Example:**
752
+
753
+ ```javascript
754
+ const { referenced, total } = await cas.findOrphanedChunks({
755
+ treeOids: [treeOid1, treeOid2, treeOid3],
756
+ });
757
+ console.log(`${referenced.size} unique blobs across ${total} total chunk references`);
758
+ ```
759
+
760
+ #### encrypt
761
+
762
+ ```javascript
763
+ await cas.encrypt({ buffer, key });
764
+ ```
765
+
766
+ Encrypts a buffer using AES-256-GCM.
767
+
768
+ **Parameters:**
769
+
770
+ - `buffer` (required): `Uint8Array` - Data to encrypt
771
+ - `key` (required): `Uint8Array` - 32-byte encryption key
772
+
773
+ **Returns:** `Promise<{ buf: Uint8Array, meta: Object }>`
774
+
775
+ **Throws:**
776
+
777
+ - `CasError` with code `INVALID_KEY_TYPE` if key is not a Uint8Array
778
+ - `CasError` with code `INVALID_KEY_LENGTH` if key is not 32 bytes
779
+
780
+ **Example:**
781
+
782
+ ```javascript
783
+ const { buf, meta } = await cas.encrypt({
784
+ buffer: new TextEncoder().encode('secret data'),
785
+ key: crypto.randomBytes(32),
786
+ });
787
+ ```
788
+
789
+ #### decrypt
790
+
791
+ ```javascript
792
+ await cas.decrypt({ buffer, key, meta });
793
+ ```
794
+
795
+ Decrypts a buffer using AES-256-GCM.
796
+
797
+ **Parameters:**
798
+
799
+ - `buffer` (required): `Uint8Array` - Encrypted data
800
+ - `key` (required): `Uint8Array` - 32-byte encryption key
801
+ - `meta` (required): `Object` - Encryption metadata (from encrypt result)
802
+
803
+ **Returns:** `Promise<Uint8Array>` - Decrypted data
804
+
805
+ **Throws:**
806
+
807
+ - `CasError` with code `INTEGRITY_ERROR` if decryption fails
808
+
809
+ **Example:**
810
+
811
+ ```javascript
812
+ const decrypted = await cas.decrypt({ buffer: buf, key, meta });
813
+ ```
814
+
815
+ #### rotateKey
816
+
817
+ ```javascript
818
+ await cas.rotateKey({ manifest, oldKey, newKey, label });
819
+ ```
820
+
821
+ Rotates a recipient's encryption key without re-encrypting data blobs. Unwraps
822
+ the DEK with `oldKey`, re-wraps with `newKey`, and increments `keyVersion`
823
+ counters. When `label` is omitted, git-cas scans every recipient candidate and
824
+ rotates the first matching entry.
825
+
826
+ **Parameters:**
827
+
828
+ - `manifest` (required): `Manifest` - Envelope-encrypted manifest
829
+ - `oldKey` (required): `Uint8Array` - Current 32-byte KEK
830
+ - `newKey` (required): `Uint8Array` - New 32-byte KEK
831
+ - `label` (optional): `string` - If provided, only rotate the named recipient
832
+
833
+ **Returns:** `Promise<Manifest>` - Updated manifest with re-wrapped DEK and incremented `keyVersion`
834
+
835
+ **Throws:**
836
+
837
+ - `CasError` with code `ROTATION_NOT_SUPPORTED` if manifest has no recipients (legacy/unencrypted)
838
+ - `CasError` with code `RECIPIENT_NOT_FOUND` if `label` doesn't exist
839
+ - `CasError` with code `DEK_UNWRAP_FAILED` if `oldKey` doesn't match the recipient
840
+ - `CasError` with code `NO_MATCHING_RECIPIENT` if no label is provided and `oldKey` matches no entry
841
+
842
+ **Example:**
843
+
844
+ ```javascript
845
+ const rotated = await cas.rotateKey({
846
+ manifest,
847
+ oldKey: aliceOldKey,
848
+ newKey: aliceNewKey,
849
+ label: 'alice',
850
+ });
851
+ const treeOid = await cas.createTree({ manifest: rotated });
852
+ await cas.addToVault({ slug: 'my-asset', treeOid, force: true });
853
+ ```
854
+
855
+ #### rotateVaultPassphrase
856
+
857
+ ```javascript
858
+ await cas.rotateVaultPassphrase({ oldPassphrase, newPassphrase, kdfOptions });
859
+ ```
860
+
861
+ Rotates the vault-level encryption passphrase. Re-wraps every envelope-encrypted entry's DEK with a new KEK derived from `newPassphrase`. Non-envelope entries are skipped.
862
+
863
+ **Parameters:**
864
+
865
+ - `oldPassphrase` (required): `string` - Current vault passphrase
866
+ - `newPassphrase` (required): `string` - New vault passphrase
867
+ - `kdfOptions` (optional): `Object` - KDF options for new passphrase (e.g., `{ algorithm: 'scrypt' }`). Defaults use PBKDF2 `600000` or scrypt `N=131072`, and out-of-policy values fail with `KDF_POLICY_VIOLATION`
868
+
869
+ **Returns:** `Promise<{ commitOid: string, rotatedSlugs: string[], skippedSlugs: string[] }>`
870
+
871
+ **Throws:**
872
+
873
+ - `CasError` with code `VAULT_METADATA_INVALID` if vault is not encrypted
874
+ - `CasError` with code `DEK_UNWRAP_FAILED` or `NO_MATCHING_RECIPIENT` if old passphrase is wrong
875
+ - `CasError` with code `KDF_POLICY_VIOLATION` if stored or requested KDF parameters fall outside policy
876
+ - `CasError` with code `VAULT_CONFLICT` if concurrent vault updates exhaust retries
877
+
878
+ **Example:**
879
+
880
+ ```javascript
881
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase({
882
+ oldPassphrase: 'old-secret',
883
+ newPassphrase: 'new-secret',
884
+ });
885
+ console.log(`Rotated: ${rotatedSlugs.join(', ')}`);
886
+ console.log(`Skipped: ${skippedSlugs.join(', ')}`);
887
+ ```
888
+
889
+ ### Properties
890
+
891
+ #### chunkSize
892
+
893
+ ```javascript
894
+ cas.chunkSize;
895
+ ```
896
+
897
+ Returns the configured chunk size in bytes.
898
+
899
+ **Type:** `number`
900
+
901
+ **Example:**
902
+
903
+ ```javascript
904
+ console.log(cas.chunkSize); // 262144
905
+ ```
906
+
907
+ ## Vault
908
+
909
+ The vault provides GC-safe storage by maintaining a single Git ref (`refs/cas/vault`) pointing to a commit chain. The commit's tree indexes all stored assets by slug. This prevents `git gc` from garbage-collecting stored data.
910
+
911
+ ### Vault Tree Structure
912
+
913
+ ```text
914
+ refs/cas/vault → commit → tree
915
+ ├── 100644 blob <oid> .vault.json
916
+ ├── 040000 tree <oid> demo/hello
917
+ ├── 040000 tree <oid> photos/beach
918
+ ```
919
+
920
+ ### Types
921
+
922
+ #### VaultEntry
923
+
924
+ ```typescript
925
+ interface VaultEntry {
926
+ slug: string;
927
+ treeOid: string;
928
+ }
929
+ ```
930
+
931
+ #### VaultMetadata
932
+
933
+ ```typescript
934
+ interface VaultEncryptionVerifier {
935
+ version: 1;
936
+ ciphertext: string;
937
+ meta: EncryptionMeta;
938
+ }
939
+
940
+ interface VaultMetadata {
941
+ version: number;
942
+ encryption?: {
943
+ cipher: string;
944
+ kdf: {
945
+ algorithm: string;
946
+ salt: string;
947
+ iterations?: number;
948
+ cost?: number;
949
+ blockSize?: number;
950
+ parallelization?: number;
951
+ keyLength: number;
952
+ };
953
+ verifier?: VaultEncryptionVerifier;
954
+ };
955
+ privacy?: {
956
+ enabled: boolean;
957
+ indexMeta?: EncryptionMeta;
958
+ };
959
+ encryptionCount?: number;
960
+ }
961
+ ```
962
+
963
+ Encrypted vaults created by v6 include `encryption.verifier`, an AES-GCM
964
+ encrypted metadata verifier that authenticates a derived vault key even when the
965
+ vault has no entries yet. Older encrypted vaults may lack the field; `git-cas`
966
+ adds it on the next vault write that provides the vault encryption key.
967
+
968
+ ### Methods
969
+
970
+ #### initVault
971
+
972
+ ```javascript
973
+ await cas.initVault({ passphrase?, kdfOptions? })
974
+ ```
975
+
976
+ Initializes the vault. Optionally configures vault-level encryption with a passphrase.
977
+
978
+ **Parameters:**
979
+
980
+ - `passphrase` (optional): `string` - Passphrase for vault-level key derivation
981
+ - `kdfOptions` (optional): `Object` - KDF options (`{ algorithm, iterations, cost, ... }`). Defaults use PBKDF2 `600000` or scrypt `N=131072`, and out-of-policy values fail with `KDF_POLICY_VIOLATION`
982
+
983
+ **Returns:** `Promise<{ commitOid: string }>`
984
+
985
+ **Throws:**
986
+
987
+ - `CasError` with code `VAULT_ENCRYPTION_ALREADY_CONFIGURED` if vault already has encryption
988
+ - `CasError` with code `KDF_POLICY_VIOLATION` if requested KDF parameters fall outside policy
989
+
990
+ **Example:**
991
+
992
+ ```javascript
993
+ // Without encryption
994
+ await cas.initVault();
995
+
996
+ // With encryption
997
+ await cas.initVault({
998
+ passphrase: 'my secret passphrase',
999
+ kdfOptions: { algorithm: 'pbkdf2' },
1000
+ });
1001
+ ```
1002
+
1003
+ #### addToVault
1004
+
1005
+ ```javascript
1006
+ await cas.addToVault({ slug, treeOid, force? })
1007
+ ```
1008
+
1009
+ Adds an entry to the vault. Auto-initializes the vault if it doesn't exist.
1010
+
1011
+ **Parameters:**
1012
+
1013
+ - `slug` (required): `string` - Entry slug (e.g., `"demo/hello"`, `"photos/beach-2024"`)
1014
+ - `treeOid` (required): `string` - Git tree OID
1015
+ - `force` (optional): `boolean` - Overwrite existing entry (default: `false`)
1016
+
1017
+ **Returns:** `Promise<{ commitOid: string }>`
1018
+
1019
+ **Throws:**
1020
+
1021
+ - `CasError` with code `INVALID_SLUG` if slug fails validation
1022
+ - `CasError` with code `VAULT_ENTRY_EXISTS` if slug exists and `force` is false
1023
+ - `CasError` with code `VAULT_CONFLICT` if concurrent update detected after retries
1024
+
1025
+ **Example:**
1026
+
1027
+ ```javascript
1028
+ const treeOid = await cas.createTree({ manifest });
1029
+ await cas.addToVault({ slug: 'demo/hello', treeOid });
1030
+ ```
1031
+
1032
+ #### listVault
1033
+
1034
+ ```javascript
1035
+ await cas.listVault();
1036
+ ```
1037
+
1038
+ Lists all vault entries sorted by slug.
1039
+
1040
+ **Returns:** `Promise<VaultEntry[]>`
1041
+
1042
+ **Example:**
1043
+
1044
+ ```javascript
1045
+ const entries = await cas.listVault();
1046
+ for (const { slug, treeOid } of entries) {
1047
+ console.log(`${slug}\t${treeOid}`);
1048
+ }
1049
+ ```
1050
+
1051
+ #### removeFromVault
1052
+
1053
+ ```javascript
1054
+ await cas.removeFromVault({ slug });
1055
+ ```
1056
+
1057
+ Removes an entry from the vault.
1058
+
1059
+ **Parameters:**
1060
+
1061
+ - `slug` (required): `string` - Entry slug to remove
1062
+
1063
+ **Returns:** `Promise<{ commitOid: string, removedTreeOid: string }>`
1064
+
1065
+ **Throws:**
1066
+
1067
+ - `CasError` with code `VAULT_ENTRY_NOT_FOUND` if slug does not exist
1068
+
1069
+ **Example:**
1070
+
1071
+ ```javascript
1072
+ const { removedTreeOid } = await cas.removeFromVault({ slug: 'demo/hello' });
1073
+ ```
1074
+
1075
+ #### resolveVaultEntry
1076
+
1077
+ ```javascript
1078
+ await cas.resolveVaultEntry({ slug });
1079
+ ```
1080
+
1081
+ Resolves a vault entry slug to its tree OID.
1082
+
1083
+ **Parameters:**
1084
+
1085
+ - `slug` (required): `string` - Entry slug
1086
+
1087
+ **Returns:** `Promise<string>` - The tree OID
1088
+
1089
+ **Throws:**
1090
+
1091
+ - `CasError` with code `VAULT_ENTRY_NOT_FOUND` if slug does not exist
1092
+
1093
+ **Example:**
1094
+
1095
+ ```javascript
1096
+ const treeOid = await cas.resolveVaultEntry({ slug: 'demo/hello' });
1097
+ const manifest = await cas.readManifest({ treeOid });
1098
+ ```
1099
+
1100
+ #### verifyVaultKey
1101
+
1102
+ ```javascript
1103
+ await cas.verifyVaultKey({ encryptionKey });
1104
+ ```
1105
+
1106
+ Verifies a derived vault encryption key against verifier metadata when the
1107
+ vault has a verifier. This is primarily useful for tools that derive keys
1108
+ themselves from `getVaultMetadata()` and `deriveKey()`.
1109
+
1110
+ **Parameters:**
1111
+
1112
+ - `encryptionKey` (required): `Uint8Array` - Derived vault encryption key
1113
+
1114
+ **Returns:** `Promise<{ verified: boolean, requiresMigration: boolean }>`
1115
+
1116
+ `verified` is `true` when verifier metadata exists and the key authenticated.
1117
+ `requiresMigration` is `true` for older encrypted vaults that have no verifier
1118
+ yet; the next keyed vault write adds the verifier.
1119
+
1120
+ **Throws:**
1121
+
1122
+ - `CasError` with code `INTEGRITY_ERROR` if verifier authentication fails
1123
+ - `CasError` with code `VAULT_METADATA_INVALID` if the vault is not encrypted
1124
+
1125
+ #### getVaultMetadata
1126
+
1127
+ ```javascript
1128
+ await cas.getVaultMetadata();
1129
+ ```
1130
+
1131
+ Returns the vault metadata, or `null` if no vault exists.
1132
+
1133
+ **Returns:** `Promise<VaultMetadata | null>`
1134
+
1135
+ **Example:**
1136
+
1137
+ ```javascript
1138
+ const metadata = await cas.getVaultMetadata();
1139
+ if (metadata?.encryption) {
1140
+ console.log('Vault is encrypted with', metadata.encryption.kdf.algorithm);
1141
+ }
1142
+ ```
1143
+
1144
+ ### Slug Validation
1145
+
1146
+ Slugs are validated with the following rules:
1147
+
1148
+ - Must be a non-empty string
1149
+ - Must not start or end with `/`
1150
+ - Must not contain empty segments (`a//b`)
1151
+ - Must not contain `.` or `..` segments
1152
+ - Must not contain control characters (0x00–0x1f, 0x7f)
1153
+ - Each segment must not exceed 255 bytes
1154
+ - Total slug must not exceed 1024 bytes
1155
+
1156
+ ### Vault-Configured Passphrase Encryption
1157
+
1158
+ When a vault is initialized with a passphrase, the human CLI can derive an
1159
+ asset encryption key from the vault's KDF configuration when you supply
1160
+ `GIT_CAS_PASSPHRASE`, `--vault-passphrase-file`, or `--os-keychain-target`
1161
+ during store and restore. The inline `--vault-passphrase` flag remains
1162
+ available for compatibility, but it prints a warning because command-line
1163
+ arguments can be captured by shell history and process listings:
1164
+
1165
+ ```javascript
1166
+ // Initialize vault with encryption
1167
+ await cas.initVault({ passphrase: 'secret' });
1168
+
1169
+ // Store with vault-configured passphrase derivation (human CLI convenience)
1170
+ // GIT_CAS_PASSPHRASE=secret git-cas store file.txt --slug demo/hello --tree
1171
+
1172
+ // Restore with vault-configured passphrase derivation
1173
+ // GIT_CAS_PASSPHRASE=secret git-cas restore --slug demo/hello --out file.txt
1174
+
1175
+ // Or resolve the vault passphrase from stdin or the OS keychain
1176
+ // printf '%s\n' 'secret' | git-cas restore --slug demo/hello --out file.txt --vault-passphrase-file -
1177
+ // git-cas restore --slug demo/hello --out file.txt --os-keychain-target demo/passphrase
1178
+ ```
1179
+
1180
+ The vault stores the KDF parameters (algorithm, salt, iterations) in
1181
+ `.vault.json`; the passphrase is never stored.
1182
+
1183
+ This does not make `refs/cas/vault` itself confidential. The vault remains a
1184
+ readable slug-to-tree index for repository readers. See
1185
+ [SECURITY.md](../SECURITY.md) for the cryptographic design details and
1186
+ [docs/THREAT_MODEL.md](./THREAT_MODEL.md) for the explicit boundary.
1187
+
1188
+ This is not an implicit library-level `store()` or `restore()` behavior.
1189
+ Library callers still pass explicit `encryptionKey` or `passphrase` values, or
1190
+ derive keys themselves through `getVaultMetadata()` plus `deriveKey()` before
1191
+ calling the content APIs.
1192
+
1193
+ When `--os-keychain-target` is used, the human CLI resolves the passphrase
1194
+ through `@git-stunts/vault` using OS-native secure storage. The optional
1195
+ `--os-keychain-account` flag scopes the lookup; the default account is
1196
+ `git-cas`.
1197
+
1198
+ The machine-facing `git cas agent` surface now supports the same explicit
1199
+ keychain lookup model for vault-derived passphrase flows through structured
1200
+ request fields:
1201
+
1202
+ - `osKeychainTarget` / `osKeychainAccount` for agent store, restore, and vault init
1203
+ - `oldOsKeychainTarget` / `oldOsKeychainAccount` and
1204
+ `newOsKeychainTarget` / `newOsKeychainAccount` for agent vault rotate
1205
+
1206
+ ### CLI Vault Commands
1207
+
1208
+ ```bash
1209
+ git cas vault init # Initialize vault
1210
+ printf '%s\n' 'secret' | git cas vault init --vault-passphrase-file -
1211
+ git cas vault init --os-keychain-target demo/passphrase
1212
+ git cas vault list # List all entries
1213
+ git cas vault info <slug> # Show slug + tree OID
1214
+ git cas vault remove <slug> # Remove an entry
1215
+ git cas vault history # Show commit history
1216
+ git cas vault history -n 10 # Last N commits
1217
+ git cas vault rotate --old-passphrase-file old.txt --new-passphrase-file new.txt
1218
+ git cas vault rotate --old-passphrase-file old.txt --new-passphrase-file new.txt --algorithm scrypt
1219
+ ```
1220
+
1221
+ ### CLI Key Rotation Commands
1222
+
1223
+ ```bash
1224
+ # Rotate a single asset's key (by vault slug)
1225
+ git cas rotate --slug demo/hello \
1226
+ --old-key-file old.key --new-key-file new.key
1227
+
1228
+ # Rotate a single asset's key (by tree OID)
1229
+ git cas rotate --oid <tree-oid> \
1230
+ --old-key-file old.key --new-key-file new.key
1231
+
1232
+ # Rotate only a named recipient
1233
+ git cas rotate --slug demo/hello \
1234
+ --old-key-file old.key --new-key-file new.key --label alice
1235
+ ```
1236
+
1237
+ #### `git cas rotate` flags
1238
+
1239
+ | Flag | Description |
1240
+ | ----------------------- | ------------------------------------------------------ |
1241
+ | `--slug <slug>` | Resolve tree OID from vault slug (updates vault entry) |
1242
+ | `--oid <tree-oid>` | Direct tree OID (outputs updated manifest) |
1243
+ | `--old-key-file <path>` | Path to current 32-byte key file (required) |
1244
+ | `--new-key-file <path>` | Path to new 32-byte key file (required) |
1245
+ | `--label <label>` | Only rotate the named recipient entry |
1246
+ | `--cwd <dir>` | Git working directory (default: `.`) |
1247
+
1248
+ #### `git cas vault rotate` flags
1249
+
1250
+ | Flag | Description |
1251
+ | ------------------------------ | ------------------------------------------------------- |
1252
+ | `--old-passphrase <pass>` | Current inline passphrase (warns; prefer file) |
1253
+ | `--new-passphrase <pass>` | New inline passphrase (warns; prefer file) |
1254
+ | `--old-passphrase-file <path>` | Read current passphrase from file (`-` for stdin) |
1255
+ | `--new-passphrase-file <path>` | Read new passphrase from file (`-` for stdin) |
1256
+ | `--algorithm <alg>` | KDF algorithm for new passphrase (`pbkdf2` or `scrypt`) |
1257
+ | `--cwd <dir>` | Git working directory (default: `.`) |
1258
+
1259
+ ### Vault History
1260
+
1261
+ The vault maintains a full commit history via `refs/cas/vault`. Each mutation (add, remove, init) creates a new commit. Use `vault history` (or `git log refs/cas/vault`) to inspect the audit trail.
1262
+
1263
+ ## VaultService
1264
+
1265
+ Domain service for vault operations. Requires three ports:
1266
+
1267
+ - `persistence` (`GitPersistencePort`) — blob/tree read/write
1268
+ - `ref` (`GitRefPort`) — ref resolution, commits, atomic updates
1269
+ - `crypto` (`CryptoPort`) — KDF for vault-level encryption
1270
+
1271
+ ```javascript
1272
+ import { VaultService } from '@git-stunts/git-cas'; // or via facade
1273
+ const vault = await cas.getVaultService();
1274
+ ```
1275
+
1276
+ ## CasService
1277
+
1278
+ Core domain service implementing CAS operations. Usually accessed via ContentAddressableStore, but can be used directly for advanced scenarios.
1279
+
1280
+ ### Constructor
1281
+
1282
+ ```javascript
1283
+ new CasService({
1284
+ persistence,
1285
+ codec,
1286
+ crypto,
1287
+ observability,
1288
+ chunkSize,
1289
+ merkleThreshold,
1290
+ concurrency,
1291
+ chunker,
1292
+ compressionAdapter,
1293
+ maxRestoreBufferSize,
1294
+ maxBlobSize,
1295
+ formatVersion,
1296
+ legacyMode,
1297
+ });
1298
+ ```
1299
+
1300
+ **Parameters:**
1301
+
1302
+ - `persistence` (required): `GitPersistencePort` implementation
1303
+ - `codec` (required): `CodecPort` implementation
1304
+ - `crypto` (required): `CryptoPort` implementation
1305
+ - `observability` (required): `ObservabilityPort` implementation
1306
+ - `chunkSize` (optional): `number` - Chunk size in bytes (default: 262144, minimum: 1024)
1307
+ - `merkleThreshold` (optional): `number` - Chunk count threshold for Merkle manifests (default: 1000)
1308
+ - `concurrency` (optional): `number` - Maximum parallel chunk I/O operations (default: 1, max: 64)
1309
+ - `chunker` (required): `ChunkingPort` - Chunking strategy instance (e.g., `FixedChunker`, `CdcChunker`)
1310
+ - `compressionAdapter` (required): `CompressionPort` - Compression adapter (e.g., `NodeCompressionAdapter`)
1311
+ - `maxRestoreBufferSize` (optional): `number` - Max bytes for buffered encrypted/compressed restore (default: 536870912 / 512 MiB)
1312
+ - `maxBlobSize` (optional): `number` - Max bytes for metadata blob reads (default: 10485760 / 10 MiB)
1313
+ - `formatVersion` (optional): `string` - Semver version stamped into new manifests
1314
+ - `legacyMode` (optional): `boolean` - When true, allows reading manifests with legacy encryption schemes (default: false)
1315
+
1316
+ **Throws:**
1317
+
1318
+ - `Error` if chunkSize is less than 1024 bytes
1319
+ - `Error` if merkleThreshold is not a positive integer
1320
+ - `Error` if chunker is not provided
1321
+ - `Error` if compressionAdapter is not provided
1322
+ - `Error` if observability does not implement ObservabilityPort
1323
+
1324
+ **Example:**
1325
+
1326
+ ```javascript
1327
+ import CasService from '@git-stunts/git-cas/service';
1328
+ // Or: import { CasService } from '@git-stunts/git-cas';
1329
+ import {
1330
+ GitPersistenceAdapter,
1331
+ JsonCodec,
1332
+ NodeCryptoAdapter,
1333
+ SilentObserver,
1334
+ FixedChunker,
1335
+ NodeCompressionAdapter,
1336
+ } from '@git-stunts/git-cas';
1337
+
1338
+ const service = new CasService({
1339
+ persistence: new GitPersistenceAdapter({ plumbing }),
1340
+ codec: new JsonCodec(),
1341
+ crypto: new NodeCryptoAdapter(),
1342
+ observability: new SilentObserver(),
1343
+ chunker: new FixedChunker({ chunkSize: 512 * 1024 }),
1344
+ compressionAdapter: new NodeCompressionAdapter(),
1345
+ });
1346
+ ```
1347
+
1348
+ ### Methods
1349
+
1350
+ All methods from ContentAddressableStore delegate to CasService. See ContentAddressableStore documentation above for:
1351
+
1352
+ - `store({ source, slug, filename, encryptionKey, passphrase, encryption, kdfOptions, compression, chunker, recipients })`
1353
+ - `restore({ manifest, encryptionKey, passphrase })`
1354
+ - `restoreStream({ manifest, encryptionKey, passphrase })`
1355
+ - `createTree({ manifest })`
1356
+ - `verifyIntegrity(manifest, { encryptionKey, passphrase })`
1357
+ - `readManifest({ treeOid })`
1358
+ - `inspectAsset({ treeOid })`
1359
+ - `collectReferencedChunks({ treeOids })`
1360
+ - `addRecipient({ manifest, existingKey, newRecipientKey, label })`
1361
+ - `removeRecipient({ manifest, label })`
1362
+ - `listRecipients(manifest)` — **synchronous** on CasService (returns `string[]`, not a Promise)
1363
+ - `rotateKey({ manifest, oldKey, newKey, label })`
1364
+ - `encrypt({ buffer, key })`
1365
+ - `decrypt({ buffer, key, meta })`
1366
+ - `deriveKey(options)`
1367
+ - `deleteAsset({ treeOid })` — **deprecated**, use `inspectAsset`
1368
+ - `findOrphanedChunks({ treeOids })` — **deprecated**, use `collectReferencedChunks`
1369
+
1370
+ #### CasService-only methods
1371
+
1372
+ The following methods are available only on CasService (not on the facade):
1373
+
1374
+ ##### readManifestRaw
1375
+
1376
+ ```javascript
1377
+ await service.readManifestRaw({ treeOid });
1378
+ ```
1379
+
1380
+ Reads a manifest from a Git tree OID and returns the raw decoded object WITHOUT Manifest construction or scheme assertion. This is the migration entry point -- it can read manifests with legacy encryption scheme identifiers that the normal `readManifest` rejects.
1381
+
1382
+ **Parameters:**
1383
+
1384
+ - `treeOid` (required): `string` - Git tree OID
1385
+
1386
+ **Returns:** `Promise<Record<string, unknown>>` - Raw decoded manifest data
1387
+
1388
+ **Throws:**
1389
+
1390
+ - `CasError` with code `MANIFEST_NOT_FOUND` if no manifest entry exists in the tree
1391
+ - `CasError` with code `GIT_ERROR` if the underlying Git command fails
1392
+
1393
+ > **Warning**: This method skips manifest hash verification and schema validation.
1394
+ > It is intended for migration tooling only. Do not use for production reads.
1395
+
1396
+ **Example:**
1397
+
1398
+ ```javascript
1399
+ const service = await cas.getService();
1400
+ const raw = await service.readManifestRaw({ treeOid });
1401
+ console.log(raw.slug, raw.encryption?.scheme);
1402
+ ```
1403
+
1404
+ ##### createFileRestorePlan
1405
+
1406
+ ```javascript
1407
+ await service.createFileRestorePlan({ manifest, encryptionKey, passphrase });
1408
+ ```
1409
+
1410
+ Creates a named restore plan for file publication without leaking internal helper coupling into infrastructure adapters. `stream` plans can be piped directly to the destination file. `bounded-file` plans preserve the whole-object auth boundary by writing to a temp file and only publishing on success.
1411
+
1412
+ **Parameters:**
1413
+
1414
+ - `manifest` (required): `Manifest` - The file manifest
1415
+ - `encryptionKey` (optional): `Uint8Array` - 32-byte encryption key
1416
+ - `passphrase` (optional): `string` - Passphrase for KDF-based decryption
1417
+
1418
+ **Returns:** `Promise<FileRestorePlan>`
1419
+
1420
+ ```typescript
1421
+ interface FileRestorePlan {
1422
+ mode: 'stream' | 'bounded-file';
1423
+ source: AsyncIterable<Uint8Array>;
1424
+ encryptionMeta?: EncryptionMeta;
1425
+ }
1426
+ ```
1427
+
1428
+ **Example:**
1429
+
1430
+ ```javascript
1431
+ const service = await cas.getService();
1432
+ const plan = await service.createFileRestorePlan({ manifest, encryptionKey });
1433
+ if (plan.mode === 'stream') {
1434
+ // Pipe plan.source directly to disk
1435
+ } else {
1436
+ // Write to temp, rename on success
1437
+ }
1438
+ ```
1439
+
1440
+ ### Observability
1441
+
1442
+ CasService delegates metrics and logging to the injected `ObservabilityPort` adapter. Use `EventEmitterObserver` for event-based monitoring or `StatsCollector` for metric aggregation.
1443
+
1444
+ ## Events
1445
+
1446
+ Events are emitted through the `ObservabilityPort` adapter, not directly from CasService. Attach an `EventEmitterObserver` to listen:
1447
+
1448
+ ```javascript
1449
+ import ContentAddressableStore, { EventEmitterObserver } from '@git-stunts/git-cas';
1450
+
1451
+ const observability = new EventEmitterObserver();
1452
+ const cas = new ContentAddressableStore({ plumbing, observability });
1453
+
1454
+ observability.on('chunk:stored', (payload) => {
1455
+ console.log('Chunk stored:', payload);
1456
+ });
1457
+ ```
1458
+
1459
+ ### chunk:stored
1460
+
1461
+ Emitted when a chunk is successfully stored.
1462
+
1463
+ **Payload:**
1464
+
1465
+ ```javascript
1466
+ {
1467
+ index: number, // Chunk index (0-based)
1468
+ size: number, // Chunk size in bytes
1469
+ digest: string, // SHA-256 hex digest (64 chars)
1470
+ blob: string // Git blob OID
1471
+ }
1472
+ ```
1473
+
1474
+ ### chunk:restored
1475
+
1476
+ Emitted when a chunk is successfully restored and verified.
1477
+
1478
+ **Payload:**
1479
+
1480
+ ```javascript
1481
+ {
1482
+ index: number, // Chunk index (0-based)
1483
+ size: number, // Chunk size in bytes
1484
+ digest: string // SHA-256 hex digest (64 chars)
1485
+ }
1486
+ ```
1487
+
1488
+ ### file:stored
1489
+
1490
+ Emitted when a complete file is successfully stored.
1491
+
1492
+ **Payload:**
1493
+
1494
+ ```javascript
1495
+ {
1496
+ slug: string, // Asset slug
1497
+ size: number, // Total file size in bytes
1498
+ chunkCount: number, // Number of chunks
1499
+ encrypted: boolean // Whether content was encrypted
1500
+ }
1501
+ ```
1502
+
1503
+ ### file:restored
1504
+
1505
+ Emitted when a complete file is successfully restored.
1506
+
1507
+ **Payload:**
1508
+
1509
+ ```javascript
1510
+ {
1511
+ slug: string, // Asset slug
1512
+ size: number, // Total file size in bytes
1513
+ chunkCount: number // Number of chunks
1514
+ }
1515
+ ```
1516
+
1517
+ ### integrity:pass
1518
+
1519
+ Emitted when integrity verification passes for all chunks.
1520
+
1521
+ **Payload:**
1522
+
1523
+ ```javascript
1524
+ {
1525
+ slug: string; // Asset slug
1526
+ }
1527
+ ```
1528
+
1529
+ ### integrity:fail
1530
+
1531
+ Emitted when integrity verification fails for a chunk.
1532
+
1533
+ **Payload:**
1534
+
1535
+ ```javascript
1536
+ {
1537
+ slug: string, // Asset slug
1538
+ chunkIndex: number, // Failed chunk index
1539
+ expected: string, // Expected SHA-256 digest
1540
+ actual: string // Actual SHA-256 digest
1541
+ }
1542
+ ```
1543
+
1544
+ ### error
1545
+
1546
+ Emitted when an error occurs during streaming operations (if listeners are registered).
1547
+
1548
+ **Payload:**
1549
+
1550
+ ```javascript
1551
+ {
1552
+ code: string, // CasError code
1553
+ message: string // Error message
1554
+ }
1555
+ ```
1556
+
1557
+ ## Value Objects
1558
+
1559
+ ### Manifest
1560
+
1561
+ Immutable value object representing a file manifest.
1562
+
1563
+ #### Constructor
1564
+
1565
+ ```javascript
1566
+ new Manifest(data);
1567
+ ```
1568
+
1569
+ **Parameters:**
1570
+
1571
+ - `data.slug` (required): `string` - Unique identifier (min length: 1)
1572
+ - `data.filename` (required): `string` - Original filename (min length: 1)
1573
+ - `data.size` (required): `number` - Total file size in bytes (>= 0)
1574
+ - `data.chunks` (required): `Array<Object>` - Chunk metadata array
1575
+ - `data.encryption` (optional): `Object` - Encryption metadata (may include `kdf` field for passphrase-derived keys)
1576
+ - `data.version` (optional): `number` - Manifest version (1 = flat, 2 = Merkle; default: 1)
1577
+ - `data.compression` (optional): `Object` - Compression metadata `{ algorithm: 'gzip' }`
1578
+ - `data.subManifests` (optional): `Array<Object>` - Sub-manifest references (v2 Merkle manifests only)
1579
+
1580
+ **Throws:** `Error` if data does not match ManifestSchema
1581
+
1582
+ **Example:**
1583
+
1584
+ ```javascript
1585
+ const manifest = new Manifest({
1586
+ slug: 'my-asset',
1587
+ filename: 'file.txt',
1588
+ size: 1024,
1589
+ chunks: [
1590
+ {
1591
+ index: 0,
1592
+ size: 1024,
1593
+ digest: 'a'.repeat(64),
1594
+ blob: 'abc123def456',
1595
+ },
1596
+ ],
1597
+ });
1598
+ ```
1599
+
1600
+ #### Fields
1601
+
1602
+ - `slug`: `string` - Asset identifier
1603
+ - `filename`: `string` - Original filename
1604
+ - `size`: `number` - Total file size
1605
+ - `chunks`: `Array<Chunk>` - Array of Chunk objects
1606
+ - `encryption`: `Object | undefined` - Encryption metadata (may include `kdf` sub-object)
1607
+ - `version`: `number` - Manifest version (1 or 2, default: 1)
1608
+ - `compression`: `Object | undefined` - Compression metadata `{ algorithm }`
1609
+ - `subManifests`: `Array | undefined` - Sub-manifest references (v2 only)
1610
+
1611
+ #### Methods
1612
+
1613
+ ##### toJSON
1614
+
1615
+ ```javascript
1616
+ manifest.toJSON();
1617
+ ```
1618
+
1619
+ Returns a plain object representation suitable for serialization.
1620
+
1621
+ **Returns:** `Object`
1622
+
1623
+ **Example:**
1624
+
1625
+ ```javascript
1626
+ const json = manifest.toJSON();
1627
+ console.log(JSON.stringify(json, null, 2));
1628
+ ```
1629
+
1630
+ ### Chunk
1631
+
1632
+ Immutable value object representing a content chunk.
1633
+
1634
+ #### Constructor
1635
+
1636
+ ```javascript
1637
+ new Chunk(data);
1638
+ ```
1639
+
1640
+ **Parameters:**
1641
+
1642
+ - `data.index` (required): `number` - Chunk index (>= 0)
1643
+ - `data.size` (required): `number` - Chunk size in bytes (> 0)
1644
+ - `data.digest` (required): `string` - SHA-256 hex digest (exactly 64 chars)
1645
+ - `data.blob` (required): `string` - Git blob OID (min length: 1)
1646
+
1647
+ **Throws:** `Error` if data does not match ChunkSchema
1648
+
1649
+ **Example:**
1650
+
1651
+ ```javascript
1652
+ const chunk = new Chunk({
1653
+ index: 0,
1654
+ size: 262144,
1655
+ digest: 'a'.repeat(64),
1656
+ blob: 'abc123def456',
1657
+ });
1658
+ ```
1659
+
1660
+ #### Fields
1661
+
1662
+ - `index`: `number` - Chunk index (0-based)
1663
+ - `size`: `number` - Chunk size in bytes
1664
+ - `digest`: `string` - SHA-256 hex digest
1665
+ - `blob`: `string` - Git blob OID
1666
+
1667
+ ## Ports
1668
+
1669
+ Ports define the interfaces for pluggable adapters. Implementations are provided but you can create custom adapters.
1670
+
1671
+ ### GitPersistencePort
1672
+
1673
+ Interface for Git persistence operations.
1674
+
1675
+ #### Methods
1676
+
1677
+ ##### writeBlob
1678
+
1679
+ ```javascript
1680
+ await port.writeBlob(content);
1681
+ ```
1682
+
1683
+ Writes content as a Git blob.
1684
+
1685
+ **Parameters:**
1686
+
1687
+ - `content`: `Uint8Array` - Content to store
1688
+
1689
+ **Returns:** `Promise<string>` - Git blob OID
1690
+
1691
+ ##### writeTree
1692
+
1693
+ ```javascript
1694
+ await port.writeTree(entries);
1695
+ ```
1696
+
1697
+ Creates a Git tree object.
1698
+
1699
+ **Parameters:**
1700
+
1701
+ - `entries`: `Array<string>` - Git mktree format lines (e.g., `"100644 blob <oid>\t<name>"`)
1702
+
1703
+ **Returns:** `Promise<string>` - Git tree OID
1704
+
1705
+ ##### readBlob
1706
+
1707
+ ```javascript
1708
+ await port.readBlob(oid, maxBytes);
1709
+ ```
1710
+
1711
+ Reads a Git blob.
1712
+
1713
+ **Parameters:**
1714
+
1715
+ - `oid`: `string` - Git blob OID
1716
+ - `maxBytes` (optional): positive integer per-call safety limit for adapters
1717
+ that support bounded blob reads
1718
+
1719
+ **Returns:** `Promise<Uint8Array>` - Blob content
1720
+
1721
+ ##### readBlobStream
1722
+
1723
+ ```javascript
1724
+ await port.readBlobStream(oid);
1725
+ ```
1726
+
1727
+ Reads a Git blob as an async stream of `Uint8Array` chunks.
1728
+
1729
+ For custom persistence adapters, this method is required for hard-limited
1730
+ buffered restore modes such as `whole` encrypted restore and buffered
1731
+ compression restore. `readBlob()` remains a compatibility fallback for
1732
+ plaintext restore only.
1733
+
1734
+ **Parameters:**
1735
+
1736
+ - `oid`: `string` - Git blob OID
1737
+
1738
+ **Returns:** `Promise<AsyncIterable<Uint8Array>>` - Blob byte stream
1739
+
1740
+ ##### readTree
1741
+
1742
+ ```javascript
1743
+ await port.readTree(treeOid);
1744
+ ```
1745
+
1746
+ Reads a Git tree object.
1747
+
1748
+ **Parameters:**
1749
+
1750
+ - `treeOid`: `string` - Git tree OID
1751
+
1752
+ **Returns:** `Promise<Array<{ mode: string, type: string, oid: string, name: string }>>`
1753
+
1754
+ **Example Implementation:**
1755
+
1756
+ ```javascript
1757
+ class CustomGitAdapter {
1758
+ async writeBlob(content) {
1759
+ // Implementation
1760
+ }
1761
+
1762
+ async writeTree(entries) {
1763
+ // Implementation
1764
+ }
1765
+
1766
+ async readBlobStream(oid) {
1767
+ // Implementation
1768
+ }
1769
+
1770
+ async readBlob(oid) {
1771
+ // Implementation
1772
+ }
1773
+
1774
+ async readTree(treeOid) {
1775
+ // Implementation
1776
+ }
1777
+ }
1778
+ ```
1779
+
1780
+ ### CodecPort
1781
+
1782
+ Interface for encoding/decoding manifest data.
1783
+
1784
+ #### Methods
1785
+
1786
+ ##### encode
1787
+
1788
+ ```javascript
1789
+ port.encode(data);
1790
+ ```
1791
+
1792
+ Encodes data to bytes.
1793
+
1794
+ **Parameters:**
1795
+
1796
+ - `data`: `Object` - Data to encode
1797
+
1798
+ **Returns:** `Uint8Array` - Encoded data
1799
+
1800
+ ##### decode
1801
+
1802
+ ```javascript
1803
+ port.decode(buffer);
1804
+ ```
1805
+
1806
+ Decodes data from bytes.
1807
+
1808
+ **Parameters:**
1809
+
1810
+ - `buffer`: `Uint8Array` - Encoded data
1811
+
1812
+ **Returns:** `Object` - Decoded data
1813
+
1814
+ #### Properties
1815
+
1816
+ ##### extension
1817
+
1818
+ ```javascript
1819
+ port.extension;
1820
+ ```
1821
+
1822
+ File extension for this codec (e.g., 'json', 'cbor').
1823
+
1824
+ **Returns:** `string`
1825
+
1826
+ **Example Implementation:**
1827
+
1828
+ ```javascript
1829
+ class XmlCodec {
1830
+ encode(data) {
1831
+ return new TextEncoder().encode(convertToXml(data));
1832
+ }
1833
+
1834
+ decode(buffer) {
1835
+ return parseXml(new TextDecoder().decode(buffer));
1836
+ }
1837
+
1838
+ get extension() {
1839
+ return 'xml';
1840
+ }
1841
+ }
1842
+ ```
1843
+
1844
+ ### CryptoPort
1845
+
1846
+ Interface for cryptographic operations.
1847
+
1848
+ #### Methods
1849
+
1850
+ ##### sha256
1851
+
1852
+ ```javascript
1853
+ port.sha256(buf);
1854
+ ```
1855
+
1856
+ Computes SHA-256 hash.
1857
+
1858
+ **Parameters:**
1859
+
1860
+ - `buf`: `Uint8Array` - Data to hash
1861
+
1862
+ **Returns:** `Promise<string>` - 64-character hex digest
1863
+
1864
+ ##### randomBytes
1865
+
1866
+ ```javascript
1867
+ port.randomBytes(n);
1868
+ ```
1869
+
1870
+ Generates cryptographically random bytes.
1871
+
1872
+ **Parameters:**
1873
+
1874
+ - `n`: `number` - Number of bytes
1875
+
1876
+ **Returns:** `Uint8Array` - Random bytes
1877
+
1878
+ ##### encryptBuffer
1879
+
1880
+ ```javascript
1881
+ port.encryptBuffer(buffer, key, aad);
1882
+ ```
1883
+
1884
+ Encrypts a buffer using AES-256-GCM.
1885
+
1886
+ **Parameters:**
1887
+
1888
+ - `buffer`: `Uint8Array` - Data to encrypt
1889
+ - `key`: `Uint8Array` - 32-byte encryption key
1890
+ - `aad` (optional): `Uint8Array` - Additional authenticated data (AAD)
1891
+
1892
+ **Returns:** `{ buf: Uint8Array, meta: { algorithm: string, nonce: string, tag: string, encrypted: boolean } } | Promise<...>`
1893
+
1894
+ ##### decryptBuffer
1895
+
1896
+ ```javascript
1897
+ port.decryptBuffer(buffer, key, meta, aad);
1898
+ ```
1899
+
1900
+ Decrypts a buffer using AES-256-GCM.
1901
+
1902
+ **Parameters:**
1903
+
1904
+ - `buffer`: `Uint8Array` - Encrypted data
1905
+ - `key`: `Uint8Array` - 32-byte encryption key
1906
+ - `meta`: `Object` - Encryption metadata with `algorithm`, `nonce`, `tag`, `encrypted`
1907
+ - `aad` (optional): `Uint8Array` - Additional authenticated data (AAD). Must match the AAD used during encryption
1908
+
1909
+ **Returns:** `Uint8Array | Promise<Uint8Array>` - Decrypted data
1910
+
1911
+ **Throws:** On authentication failure
1912
+
1913
+ ##### createEncryptionStream
1914
+
1915
+ ```javascript
1916
+ port.createEncryptionStream(key, aad);
1917
+ ```
1918
+
1919
+ Creates a streaming encryption context.
1920
+
1921
+ **Parameters:**
1922
+
1923
+ - `key`: `Uint8Array` - 32-byte encryption key
1924
+ - `aad` (optional): `Uint8Array` - Additional authenticated data (AAD)
1925
+
1926
+ **Returns:** `{ encrypt: Function, finalize: Function }`
1927
+
1928
+ - `encrypt`: `(source: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array>` - Transform function
1929
+ - `finalize`: `() => { algorithm: string, nonce: string, tag: string, encrypted: boolean }` - Get metadata
1930
+
1931
+ ##### createDecryptionStream
1932
+
1933
+ ```javascript
1934
+ port.createDecryptionStream(key, meta, aad);
1935
+ ```
1936
+
1937
+ Creates a streaming decryption context. The returned stream may yield tentative plaintext before final auth succeeds, so callers must control publication semantics themselves.
1938
+
1939
+ **Parameters:**
1940
+
1941
+ - `key`: `Uint8Array` - 32-byte encryption key
1942
+ - `meta`: `Object` - Encryption metadata from the encrypt operation
1943
+ - `aad` (optional): `Uint8Array` - Additional authenticated data (AAD). Must match the AAD used during encryption
1944
+
1945
+ **Returns:** `{ decrypt: Function }`
1946
+
1947
+ - `decrypt`: `(source: AsyncIterable<Uint8Array>) => AsyncIterable<Uint8Array>` - Transform function
1948
+
1949
+ ##### hmacSha256
1950
+
1951
+ ```javascript
1952
+ port.hmacSha256(key, data);
1953
+ ```
1954
+
1955
+ Computes HMAC-SHA256 of the given data with the given key.
1956
+
1957
+ **Parameters:**
1958
+
1959
+ - `key`: `Uint8Array` - HMAC key
1960
+ - `data`: `Uint8Array` - Data to authenticate
1961
+
1962
+ **Returns:** `Uint8Array` - 32-byte HMAC digest
1963
+
1964
+ ##### encryptBufferWithNonce
1965
+
1966
+ ```javascript
1967
+ port.encryptBufferWithNonce(buffer, key, nonce);
1968
+ ```
1969
+
1970
+ Encrypts a buffer using AES-256-GCM with a caller-provided nonce. Used by convergent encryption where the nonce must be deterministic (derived from content hash) to enable deduplication.
1971
+
1972
+ **Parameters:**
1973
+
1974
+ - `buffer`: `Uint8Array` - Plaintext to encrypt
1975
+ - `key`: `Uint8Array` - 32-byte encryption key
1976
+ - `nonce`: `Uint8Array` - 12-byte nonce (IV)
1977
+
1978
+ **Returns:** `{ buf: Uint8Array, tag: Uint8Array } | Promise<{ buf: Uint8Array, tag: Uint8Array }>`
1979
+
1980
+ ##### decryptBufferWithNonceTag
1981
+
1982
+ ```javascript
1983
+ port.decryptBufferWithNonceTag(buffer, key, nonce, tag);
1984
+ ```
1985
+
1986
+ Decrypts a buffer using AES-256-GCM with explicit nonce and tag. Used by convergent encryption to decrypt per-chunk ciphertext where the nonce and tag are stored/derived externally.
1987
+
1988
+ **Parameters:**
1989
+
1990
+ - `buffer`: `Uint8Array` - Ciphertext to decrypt
1991
+ - `key`: `Uint8Array` - 32-byte encryption key
1992
+ - `nonce`: `Uint8Array` - 12-byte nonce (IV)
1993
+ - `tag`: `Uint8Array` - 16-byte GCM authentication tag
1994
+
1995
+ **Returns:** `Uint8Array | Promise<Uint8Array>`
1996
+
1997
+ **Throws:** On authentication failure
1998
+
1999
+ ##### deriveKey
2000
+
2001
+ ```javascript
2002
+ await port.deriveKey(options);
2003
+ ```
2004
+
2005
+ Derives an encryption key from a passphrase using PBKDF2 or scrypt. PBKDF2 is
2006
+ available across Node, Bun, and Web Crypto runtimes. scrypt requires a
2007
+ Node/Bun-compatible crypto adapter; Web Crypto runtimes report an explicit
2008
+ capability error.
2009
+
2010
+ **Parameters:**
2011
+
2012
+ - `options.passphrase`: `string` - The passphrase
2013
+ - `options.salt` (optional): `Uint8Array` - Salt (random if omitted)
2014
+ - `options.algorithm` (optional): `'pbkdf2' | 'scrypt'` - KDF algorithm (default: `'pbkdf2'`)
2015
+ - `options.iterations` (optional): `number` - PBKDF2 iterations (default: `600000`)
2016
+ - `options.cost` (optional): `number` - scrypt cost N (default: `131072`)
2017
+ - `options.blockSize` (optional): `number` - scrypt block size r
2018
+ - `options.parallelization` (optional): `number` - scrypt parallelization p
2019
+ - `options.keyLength` (optional): `number` - Derived key length (default: 32)
2020
+
2021
+ `deriveKey()` is the raw derivation primitive. Policy enforcement for persisted
2022
+ KDF metadata happens in `store()`, `restore()`, `initVault()`, and
2023
+ `rotateVaultPassphrase()`.
2024
+
2025
+ **Returns:** `Promise<{ key: Uint8Array, salt: Uint8Array, params: Object }>`
2026
+
2027
+ **Example Implementation:**
2028
+
2029
+ ```javascript
2030
+ import { CryptoPort } from '@git-stunts/git-cas';
2031
+
2032
+ class CustomCryptoAdapter extends CryptoPort {
2033
+ sha256(buf) {
2034
+ // Implementation — returns Promise<string>
2035
+ }
2036
+
2037
+ randomBytes(n) {
2038
+ // Implementation
2039
+ }
2040
+
2041
+ encryptBuffer(buffer, key, aad) {
2042
+ // Implementation
2043
+ }
2044
+
2045
+ decryptBuffer(buffer, key, meta, aad) {
2046
+ // Implementation
2047
+ }
2048
+
2049
+ createEncryptionStream(key, aad) {
2050
+ // Implementation
2051
+ }
2052
+
2053
+ createDecryptionStream(key, meta, aad) {
2054
+ // Implementation
2055
+ }
2056
+
2057
+ hmacSha256(key, data) {
2058
+ // Implementation
2059
+ }
2060
+
2061
+ encryptBufferWithNonce(buffer, key, nonce) {
2062
+ // Implementation
2063
+ }
2064
+
2065
+ decryptBufferWithNonceTag(buffer, key, nonce, tag) {
2066
+ // Implementation
2067
+ }
2068
+
2069
+ async deriveKey(options) {
2070
+ // Implementation
2071
+ }
2072
+ }
2073
+ ```
2074
+
2075
+ ## Codecs
2076
+
2077
+ Built-in codec implementations.
2078
+
2079
+ ### JsonCodec
2080
+
2081
+ JSON codec for manifest serialization.
2082
+
2083
+ ```javascript
2084
+ import { JsonCodec } from '@git-stunts/git-cas';
2085
+
2086
+ const codec = new JsonCodec();
2087
+ const encoded = codec.encode({ key: 'value' });
2088
+ const decoded = codec.decode(encoded);
2089
+ console.log(codec.extension); // 'json'
2090
+ ```
2091
+
2092
+ ### CborCodec
2093
+
2094
+ CBOR codec for compact binary serialization.
2095
+
2096
+ ```javascript
2097
+ import { CborCodec } from '@git-stunts/git-cas';
2098
+
2099
+ const codec = new CborCodec();
2100
+ const encoded = codec.encode({ key: 'value' });
2101
+ const decoded = codec.decode(encoded);
2102
+ console.log(codec.extension); // 'cbor'
2103
+ ```
2104
+
2105
+ ## Error Codes
2106
+
2107
+ All errors thrown by git-cas are instances of `CasError`.
2108
+
2109
+ ### CasError
2110
+
2111
+ `CasError` is the runtime error class and is re-exported from the package root.
2112
+ Public callers should branch on the stable `code` field; `documentationUrl` is
2113
+ present when an error has a canonical docs page.
2114
+
2115
+ #### Constructor
2116
+
2117
+ ```javascript
2118
+ new CasError(message, code, meta);
2119
+ new CasError({ message, code, meta, documentationUrl });
2120
+ ```
2121
+
2122
+ **Parameters:**
2123
+
2124
+ - `message`: `string` - Error message
2125
+ - `code`: `string` - Error code (see below)
2126
+ - `meta`: `Object` - Additional error context (default: `{}`)
2127
+ - `documentationUrl`: `string` - Optional documentation URL
2128
+
2129
+ #### Fields
2130
+
2131
+ - `name`: `string` - Always "CasError"
2132
+ - `message`: `string` - Error message
2133
+ - `code`: `string` - Error code
2134
+ - `meta`: `Object` - Additional context
2135
+ - `documentationUrl`: `string | undefined` - Optional documentation URL
2136
+ - `stack`: `string` - Stack trace
2137
+
2138
+ ### Error Codes
2139
+
2140
+ | Code | Description | Thrown By |
2141
+ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------- |
2142
+ | `INVALID_KEY_TYPE` | Encryption key must be a Uint8Array | `encrypt()`, `decrypt()`, `store()`, `restore()` |
2143
+ | `INVALID_KEY_LENGTH` | Encryption key must be exactly 32 bytes | `encrypt()`, `decrypt()`, `store()`, `restore()` |
2144
+ | `MISSING_KEY` | Encryption key required to restore encrypted content but none was provided | `restore()` |
2145
+ | `INTEGRITY_ERROR` | Chunk digest verification failed or decryption authentication failed | `restore()`, `verifyIntegrity()`, `decrypt()` |
2146
+ | `PERSISTENCE_CAPABILITY_REQUIRED` | Buffered restore mode requires `readBlobStream()` so `maxRestoreBufferSize` can be enforced with memory-safe reads | `restore()`, `restoreStream()` |
2147
+ | `DECRYPTION_BUFFER_EXCEEDED` | Web Crypto whole-object decrypt exceeded the configured buffer limit | `createDecryptionStream()` via Web Crypto restore paths |
2148
+ | `KDF_POLICY_VIOLATION` | KDF parameters fell outside the accepted policy window | `store()`, `restore()`, `initVault()`, `rotateVaultPassphrase()`, `readState()` |
2149
+ | `STREAM_ERROR` | Stream error occurred during store operation | `store()` |
2150
+ | `STORE_ERROR` | Chunk write failed during store after dispatch | `store()` |
2151
+ | `MANIFEST_NOT_FOUND` | No manifest entry found in the Git tree | `readManifest()`, `inspectAsset()`, `collectReferencedChunks()` |
2152
+ | `GIT_ERROR` | Underlying Git plumbing command failed | `readManifest()`, `inspectAsset()`, `collectReferencedChunks()` |
2153
+ | `GIT_REF_NOT_FOUND` | Git ref lookup found no ref; vault reads normalize this to empty state | `GitRefAdapter`, `VaultPersistence` |
2154
+ | `INVALID_OPTIONS` | Mutually exclusive options provided or unsupported option value | `store()`, `restore()` |
2155
+ | `INVALID_SLUG` | Slug fails validation (empty, control chars, `..` segments, etc.) | `addToVault()` |
2156
+ | `VAULT_ENTRY_NOT_FOUND` | Slug does not exist in vault | `removeFromVault()`, `resolveVaultEntry()` |
2157
+ | `VAULT_ENTRY_EXISTS` | Slug already exists (use `force` to overwrite) | `addToVault()` |
2158
+ | `VAULT_CONFLICT` | Concurrent vault update detected (CAS failure after retries) | `addToVault()`, `removeFromVault()`, `initVault()`, `rotateVaultPassphrase()` |
2159
+ | `VAULT_REF_MISSING` | Vault ref is absent during diagnostics | `git cas doctor` |
2160
+ | `VAULT_REF_UPDATE_FAILED` | Vault ref update failed for a non-CAS reason | `addToVault()`, `removeFromVault()`, `initVault()`, `rotateVaultPassphrase()` |
2161
+ | `VAULT_HEAD_INVALID` | Vault ref exists but cannot be resolved to a readable commit tree | `readState()`, `getVaultMetadata()`, `git cas doctor` |
2162
+ | `VAULT_METADATA_INVALID` | `.vault.json` malformed, unknown version, unsupported cipher, or missing required fields | `readState()`, `rotateVaultPassphrase()`, `git cas doctor` |
2163
+ | `VAULT_PRIVACY_INDEX_INVALID` | Privacy index metadata, payload, or raw HMAC tree coverage is invalid | `readState()`, `listVault()`, `resolveVaultEntry()`, `git cas doctor` |
2164
+ | `VAULT_PRIVACY_INDEX_MISSING` | Privacy mode is enabled but `.privacy-index` is missing | `readState()`, `listVault()`, `git cas doctor` |
2165
+ | `VAULT_PRIVACY_KEY_REQUIRED` | Privacy mode requires a vault encryption key for state reads | `readState()`, `listVault()`, `resolveVaultEntry()` |
2166
+ | `VAULT_ENCRYPTION_ALREADY_CONFIGURED` | Cannot reconfigure encryption without key rotation | `initVault()` |
2167
+ | `NO_MATCHING_RECIPIENT` | No recipient entry matches the provided KEK | `restore()`, `rotateKey()` |
2168
+ | `DEK_UNWRAP_FAILED` | Failed to unwrap DEK with the provided KEK | `addRecipient()`, `rotateKey()` |
2169
+ | `RECIPIENT_NOT_FOUND` | Recipient label not found in manifest | `removeRecipient()`, `rotateKey()` |
2170
+ | `RECIPIENT_ALREADY_EXISTS` | Recipient label already exists | `addRecipient()` |
2171
+ | `CANNOT_REMOVE_LAST_RECIPIENT` | Cannot remove the last recipient | `removeRecipient()` |
2172
+ | `ROTATION_NOT_SUPPORTED` | Key rotation requires envelope encryption (recipients) | `rotateKey()` |
2173
+
2174
+ ### Error Handling
2175
+
2176
+ **Example:**
2177
+
2178
+ ```javascript
2179
+ try {
2180
+ await cas.restore({ manifest, encryptionKey });
2181
+ } catch (err) {
2182
+ if (err && typeof err === 'object' && 'code' in err) {
2183
+ console.error('CAS Error:', err.code);
2184
+ console.error('Message:', err.message);
2185
+ console.error('Meta:', err.meta);
2186
+
2187
+ switch (err.code) {
2188
+ case 'MISSING_KEY':
2189
+ console.log('Content is encrypted - please provide a key');
2190
+ break;
2191
+ case 'INTEGRITY_ERROR':
2192
+ console.log('Content verification failed - may be corrupted');
2193
+ break;
2194
+ case 'INVALID_KEY_LENGTH':
2195
+ console.log('Key must be 32 bytes');
2196
+ break;
2197
+ }
2198
+ } else {
2199
+ throw err;
2200
+ }
2201
+ }
2202
+ ```
2203
+
2204
+ ### Error Metadata
2205
+
2206
+ Different error codes include different metadata:
2207
+
2208
+ **INVALID_KEY_LENGTH:**
2209
+
2210
+ ```javascript
2211
+ {
2212
+ expected: 32,
2213
+ actual: <number>
2214
+ }
2215
+ ```
2216
+
2217
+ **INTEGRITY_ERROR (chunk verification):**
2218
+
2219
+ ```javascript
2220
+ {
2221
+ chunkIndex: <number>,
2222
+ expected: <string>, // Expected SHA-256 digest
2223
+ actual: <string> // Actual SHA-256 digest
2224
+ }
2225
+ ```
2226
+
2227
+ **INTEGRITY_ERROR (decryption):**
2228
+
2229
+ ```javascript
2230
+ {
2231
+ originalError: <Error>
2232
+ }
2233
+ ```
2234
+
2235
+ **STREAM_ERROR:**
2236
+
2237
+ ```javascript
2238
+ {
2239
+ chunksDispatched: <number>,
2240
+ orphanedBlobs: <string[]>,
2241
+ originalError: <Error>
2242
+ }
2243
+ ```
2244
+
2245
+ **STORE_ERROR:**
2246
+
2247
+ ```javascript
2248
+ {
2249
+ chunksDispatched: <number>,
2250
+ orphanedBlobs: <string[]>,
2251
+ failedIndex: <number>,
2252
+ originalError: <Error>
2253
+ }
2254
+ ```