@git-stunts/git-cas 5.3.1 → 6.0.0

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