@git-stunts/git-cas 5.3.2 → 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 (173) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  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 +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 +998 -214
  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 +296 -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 +2224 -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 +208 -65
  60. package/index.js +163 -54
  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 +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -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 +178 -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 +3 -1
  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
@@ -1,18 +1,44 @@
1
1
  /**
2
2
  * @fileoverview Domain service for vault (GC-safe ref-based asset index) operations.
3
3
  */
4
- import CasError from '../errors/CasError.js';
4
+ import { CasError, ErrorCodes } from '../errors/index.js';
5
5
  import buildKdfMetadata from '../helpers/buildKdfMetadata.js';
6
+ import { prepareKdfOptions } from '../../helpers/kdfPolicy.js';
7
+ import Slug from '../value-objects/Slug.js';
8
+ import RedactingObservability from './RedactingObservability.js';
9
+ import VaultMetadataCodec, {
10
+ VAULT_ENCRYPTION_COUNT_MAX,
11
+ VAULT_ENCRYPTION_COUNT_WARN,
12
+ } from './VaultMetadataCodec.js';
13
+ import VaultMutationRetryPolicy from './VaultMutationRetryPolicy.js';
14
+ import VaultPersistence, { VAULT_REF } from './VaultPersistence.js';
15
+ import VaultPrivacyIndex from './VaultPrivacyIndex.js';
16
+ import VaultStateCache from './VaultStateCache.js';
17
+ import VaultTreeCodec, {
18
+ VAULT_METADATA_ENTRY,
19
+ VAULT_PRIVACY_INDEX_ENTRY,
20
+ } from './VaultTreeCodec.js';
21
+ import VaultKeyVerifier from './VaultKeyVerifier.js';
22
+
23
+ const PRIVACY_INDEX_META_FIELD = 'privacy.indexMeta';
24
+ const VAULT_PERSISTENCE_OPTION = 'vaultPersistence';
25
+ const PERSISTENCE_OPTION = 'persistence';
26
+ const REF_OPTION = 'ref';
6
27
 
7
- const VAULT_REF = 'refs/cas/vault';
8
- const MAX_CAS_RETRIES = 3;
9
- const CAS_RETRY_BASE_MS = 50;
28
+ /**
29
+ * Vault key verifier stored in .vault.json.
30
+ * @typedef {Object} VaultEncryptionVerifier
31
+ * @property {number} version - Verifier format version.
32
+ * @property {string} ciphertext - Base64 ciphertext of the verifier plaintext.
33
+ * @property {import('../../ports/CryptoPort.js').EncryptionMeta} meta - AES-GCM metadata.
34
+ */
10
35
 
11
36
  /**
12
37
  * Vault encryption metadata stored in .vault.json.
13
38
  * @typedef {Object} VaultEncryptionMeta
14
39
  * @property {string} cipher - Cipher algorithm (e.g. 'aes-256-gcm').
15
40
  * @property {{ algorithm: string, salt: string, iterations?: number, cost?: number, blockSize?: number, parallelization?: number, keyLength: number }} kdf - KDF parameters.
41
+ * @property {VaultEncryptionVerifier} [verifier] - Encrypted verifier for the vault key.
16
42
  */
17
43
 
18
44
  /**
@@ -20,10 +46,11 @@ const CAS_RETRY_BASE_MS = 50;
20
46
  * @typedef {Object} VaultMetadata
21
47
  * @property {number} version - Metadata version (currently 1).
22
48
  * @property {VaultEncryptionMeta} [encryption] - Encryption configuration.
49
+ * @property {number} [encryptionCount] - Number of encrypted vault writes under the current key.
23
50
  */
24
51
 
25
52
  /**
26
- * Vault state read from refs/cas/vault.
53
+ * Vault state read from the current vault head.
27
54
  * @typedef {Object} VaultState
28
55
  * @property {Map<string, string>} entries - Slug→treeOid map.
29
56
  * @property {string|null} parentCommitOid - Parent commit OID.
@@ -31,57 +58,49 @@ const CAS_RETRY_BASE_MS = 50;
31
58
  */
32
59
 
33
60
  /**
34
- * Percent-encodes a vault slug for use as a git tree entry name.
35
- * Git tree entry names cannot contain '/'.
36
- * @param {string} slug
37
- * @returns {string}
61
+ * Git tree entry shape returned by the persistence port.
62
+ * @typedef {Object} VaultTreeEntry
63
+ * @property {string} mode - Git file mode.
64
+ * @property {string} type - Git object type.
65
+ * @property {string} oid - Git object OID.
66
+ * @property {string} name - Tree entry name.
38
67
  */
39
- function encodeSlug(slug) {
40
- return slug.replaceAll('%', '%25').replaceAll('/', '%2F');
41
- }
42
-
43
- /**
44
- * Decodes a percent-encoded tree entry name back to a vault slug.
45
- * @param {string} name
46
- * @returns {string}
47
- */
48
- function decodeSlug(name) {
49
- return name.replaceAll('%2F', '/').replaceAll('%25', '%');
50
- }
51
68
 
52
69
  /**
53
- * Returns true if the string contains ASCII control characters (0x00–0x1f, 0x7f).
54
- * @param {string} str
55
- * @returns {boolean}
70
+ * Cached parse-stable vault tree data.
71
+ * @typedef {Object} CachedVaultTree
72
+ * @property {VaultTreeEntry[]} rawEntries - Raw tree entries from persistence.
73
+ * @property {VaultMetadata|null} metadata - Parsed vault metadata.
74
+ * @property {Map<string, string>|null} plainEntries - Parsed plain slug entries.
75
+ * @property {WeakMap<Uint8Array, {
76
+ * keyBytes: Uint8Array,
77
+ * entries: Map<string, string>|null,
78
+ * pending: Promise<Map<string, string>>|null
79
+ * }>} privacyEntriesByKey
80
+ * Privacy entries by key object and byte snapshot.
81
+ * @property {WeakMap<Uint8Array, Uint8Array>} verifiedEncryptionKeys
82
+ * Vault keys already checked against metadata by key object and byte snapshot.
56
83
  */
57
- function hasControlChars(str) {
58
- for (let i = 0; i < str.length; i++) {
59
- const code = str.charCodeAt(i);
60
- if (code <= 0x1f || code === 0x7f) {
61
- return true;
62
- }
63
- }
64
- return false;
65
- }
66
84
 
67
85
  /**
68
86
  * Domain service for vault operations.
69
87
  *
70
88
  * The vault is a GC-safe ref-based index that maps slugs to Git tree OIDs.
71
- * It is backed by a single Git ref (`refs/cas/vault`) pointing to a commit
72
- * chain. Each commit's tree contains one entry per stored asset plus a
73
- * `.vault.json` metadata blob.
89
+ * It is backed by a vault-head commit chain. Each commit's tree contains one
90
+ * entry per stored asset plus a `.vault.json` metadata blob.
74
91
  *
75
- * Requires three ports:
76
- * - `persistence` ({@link GitPersistencePort}) for blob/tree read/write
77
- * - `ref` ({@link GitRefPort}) for ref resolution, commits, and atomic updates
78
- * - `crypto` ({@link CryptoPort}) for KDF when vault-level encryption is enabled
92
+ * `VaultService` orchestrates public vault use cases. Persistence, cache,
93
+ * boundary codecs, privacy indexing, key verification, and retry timing are
94
+ * injected collaborators.
79
95
  */
80
96
  export default class VaultService {
81
97
  static VAULT_REF = VAULT_REF;
82
98
 
83
99
  /** @type {number} Nonce usage warning threshold (2^31). */
84
- static ENCRYPTION_COUNT_WARN = 2 ** 31;
100
+ static ENCRYPTION_COUNT_WARN = VAULT_ENCRYPTION_COUNT_WARN;
101
+
102
+ /** @type {number} Maximum encrypted vault writes before key rotation is required (2^32 - 1). */
103
+ static ENCRYPTION_COUNT_MAX = VAULT_ENCRYPTION_COUNT_MAX;
85
104
 
86
105
  /**
87
106
  * @param {Object} options
@@ -89,159 +108,285 @@ export default class VaultService {
89
108
  * @param {import('../../ports/GitRefPort.js').default} options.ref
90
109
  * @param {import('../../ports/CryptoPort.js').default} options.crypto
91
110
  * @param {import('../../ports/ObservabilityPort.js').default} [options.observability]
111
+ * @param {VaultPersistence} [options.vaultPersistence]
112
+ * @param {VaultStateCache} [options.stateCache]
113
+ * @param {VaultMetadataCodec} [options.metadataCodec]
114
+ * @param {VaultTreeCodec} [options.treeCodec]
115
+ * @param {VaultKeyVerifier} [options.keyVerifier]
116
+ * @param {VaultPrivacyIndex} [options.privacyIndex]
117
+ * @param {VaultMutationRetryPolicy} [options.retryPolicy]
92
118
  */
93
- constructor({ persistence, ref, crypto, observability }) {
94
- this.persistence = persistence;
95
- this.ref = ref;
119
+ constructor({
120
+ persistence,
121
+ ref,
122
+ crypto,
123
+ observability,
124
+ vaultPersistence,
125
+ stateCache,
126
+ metadataCodec,
127
+ treeCodec,
128
+ keyVerifier,
129
+ privacyIndex,
130
+ retryPolicy,
131
+ }) {
132
+ validateConstructorPersistenceDependencies({ vaultPersistence, persistence, ref });
96
133
  this.crypto = crypto;
134
+ this.metadataCodec = metadataCodec || new VaultMetadataCodec();
135
+ this.treeCodec = treeCodec || new VaultTreeCodec();
136
+ this.vaultPersistence = vaultPersistence || new VaultPersistence({
137
+ persistence,
138
+ ref,
139
+ treeCodec: this.treeCodec,
140
+ metadataCodec: this.metadataCodec,
141
+ });
142
+ this.stateCache = stateCache || new VaultStateCache();
143
+ this.keyVerifier = keyVerifier || new VaultKeyVerifier({ crypto });
144
+ this.privacyIndex = privacyIndex || new VaultPrivacyIndex({ crypto });
145
+ this.retryPolicy = retryPolicy || new VaultMutationRetryPolicy();
97
146
  /** @type {import('../../ports/ObservabilityPort.js').default} */
98
- this.observability = observability || { metric() {}, log() {}, span: () => ({ end() {} }) };
147
+ this.observability = RedactingObservability.wrap(
148
+ observability || { metric() {}, log() {}, span: () => ({ end() {} }) },
149
+ );
150
+ }
151
+
152
+ /**
153
+ * Validates a vault slug.
154
+ * @param {string} slug
155
+ * @throws {CasError} INVALID_SLUG if the slug is invalid.
156
+ */
157
+ validateSlug(slug) {
158
+ Slug.validate(slug);
99
159
  }
100
160
 
101
161
  // ---------------------------------------------------------------------------
102
- // Slug validation
162
+ // State read / write
103
163
  // ---------------------------------------------------------------------------
104
164
 
105
165
  /**
106
- * Validates a single slug segment.
107
- * @param {string} seg - Segment to validate.
108
- * @param {string} slug - Full slug (for error context).
166
+ * Loads and caches parse-stable vault tree data by tree OID.
167
+ * @param {string} treeOid
168
+ * @returns {Promise<CachedVaultTree>}
109
169
  */
110
- static #validateSegment(seg, slug) {
111
- if (seg.length === 0) {
112
- throw new CasError('Slug contains empty segment', 'INVALID_SLUG', { slug });
113
- }
114
- if (seg === '.' || seg === '..') {
115
- throw new CasError('Slug contains "." or ".." segment', 'INVALID_SLUG', { slug });
116
- }
117
- if (Buffer.byteLength(seg, 'utf8') > 255) {
118
- throw new CasError('Slug segment exceeds 255 bytes', 'INVALID_SLUG', { slug });
119
- }
120
- if (hasControlChars(seg)) {
121
- throw new CasError('Slug contains control characters', 'INVALID_SLUG', { slug });
170
+ async #readCachedVaultTree(treeOid) {
171
+ const cached = this.stateCache.get(treeOid);
172
+ if (cached) {
173
+ return cached;
122
174
  }
175
+ return this.stateCache.rememberTree(
176
+ treeOid,
177
+ await this.vaultPersistence.readTreeSnapshot(treeOid),
178
+ );
123
179
  }
124
180
 
125
181
  /**
126
- * Validates a vault slug.
127
- * @param {string} slug
128
- * @throws {CasError} INVALID_SLUG if the slug is invalid.
182
+ * Resolves the current vault commit and tree.
183
+ * @returns {Promise<{ commitOid: string, treeOid: string }|null>}
129
184
  */
130
- validateSlug(slug) {
131
- if (typeof slug !== 'string' || slug.length === 0) {
132
- throw new CasError('Slug must be a non-empty string', 'INVALID_SLUG', { slug });
185
+ async #resolveCurrentVaultTree() {
186
+ return await this.vaultPersistence.resolveHead();
187
+ }
188
+
189
+ /**
190
+ * Reads one persisted vault tree entry.
191
+ * @param {string} treeOid
192
+ * @param {string} treePath
193
+ * @returns {Promise<VaultTreeEntry|null>}
194
+ */
195
+ async #readTreeEntry(treeOid, treePath) {
196
+ const cached = this.stateCache.get(treeOid);
197
+ if (cached) {
198
+ return cached.rawEntries.find((entry) => entry.name === treePath) || null;
133
199
  }
134
- if (slug.startsWith('/') || slug.endsWith('/')) {
135
- throw new CasError('Slug must not start or end with "/"', 'INVALID_SLUG', { slug });
200
+ return await this.vaultPersistence.readEntry(treeOid, treePath);
201
+ }
202
+
203
+ /**
204
+ * Streams tree entries, falling back to readTree() for older adapters.
205
+ * @param {string} treeOid
206
+ * @returns {AsyncIterable<VaultTreeEntry>}
207
+ */
208
+ async *#iterateTreeEntries(treeOid) {
209
+ const cached = this.stateCache.get(treeOid);
210
+ if (cached) {
211
+ yield* cached.rawEntries;
212
+ return;
136
213
  }
137
- if (Buffer.byteLength(slug, 'utf8') > 1024) {
138
- throw new CasError('Slug exceeds 1024 bytes total', 'INVALID_SLUG', { slug });
214
+ yield* this.vaultPersistence.iterateEntries(treeOid);
215
+ }
216
+
217
+ /**
218
+ * Reads vault metadata without enumerating the whole vault tree.
219
+ * @param {string} treeOid
220
+ * @returns {Promise<VaultMetadata|null>}
221
+ */
222
+ async #readMetadataFromTree(treeOid) {
223
+ const cached = this.stateCache.get(treeOid);
224
+ if (cached) {
225
+ return cached.metadata;
139
226
  }
140
- for (const seg of slug.split('/')) {
141
- VaultService.#validateSegment(seg, slug);
227
+ const { metadata, snapshot } = await this.vaultPersistence.readMetadataSnapshot(treeOid);
228
+ if (snapshot) {
229
+ this.stateCache.rememberTree(treeOid, snapshot);
142
230
  }
231
+ return metadata;
143
232
  }
144
233
 
145
- // ---------------------------------------------------------------------------
146
- // Metadata validation
147
- // ---------------------------------------------------------------------------
234
+ /**
235
+ * Builds public vault state from a cached plain vault tree.
236
+ * @param {CachedVaultTree} cached
237
+ * @param {string} commitOid
238
+ * @returns {VaultState}
239
+ */
240
+ #plainStateFromCache(cached, commitOid) {
241
+ const entries = this.stateCache.plainEntries(
242
+ cached,
243
+ (rawEntries) => this.treeCodec.parseTreeEntries(rawEntries).entries,
244
+ );
245
+ return this.stateCache.toState({
246
+ entries,
247
+ parentCommitOid: commitOid,
248
+ metadata: cached.metadata,
249
+ });
250
+ }
148
251
 
149
252
  /**
150
- * Validates encryption-specific metadata fields.
151
- * @param {VaultEncryptionMeta} encryption - Encryption metadata.
152
- * @param {VaultMetadata} metadata - Full metadata (for error context).
253
+ * Resolves HMAC tree entry names to slugs using the encrypted privacy index.
254
+ * @param {VaultTreeEntry[]} rawEntries - Raw tree entries.
255
+ * @param {VaultMetadata} metadata - Vault metadata (must have privacy.indexMeta).
256
+ * @param {Uint8Array} encryptionKey - Vault encryption key.
257
+ * @returns {Promise<Map<string, string>>} Slug→treeOid map.
153
258
  */
154
- static #validateEncryption(encryption, metadata) {
155
- const { cipher, kdf } = encryption;
156
- if (!cipher || !kdf?.algorithm || !kdf?.salt || !kdf?.keyLength) {
259
+ async #resolvePrivacyEntries(rawEntries, metadata, encryptionKey) {
260
+ const parsed = this.treeCodec.parseTreeEntries(rawEntries, { privacyEnabled: true });
261
+
262
+ if (!parsed.privacyIndexBlobOid) {
157
263
  throw new CasError(
158
- 'Vault encryption metadata missing required fields',
159
- 'VAULT_METADATA_INVALID',
160
- { metadata },
264
+ 'Privacy mode is enabled but .privacy-index is missing',
265
+ ErrorCodes.VAULT_PRIVACY_INDEX_MISSING,
161
266
  );
162
267
  }
268
+
269
+ const indexMeta = requirePrivacyIndexMeta(metadata);
270
+ const indexBlob = await this.vaultPersistence.readBlob(parsed.privacyIndexBlobOid);
271
+ const slugToHmac = await this.privacyIndex.decryptIndex({
272
+ bytes: indexBlob,
273
+ encryptionKey,
274
+ meta: indexMeta,
275
+ });
276
+
277
+ // Reverse the index: hmacName → slug.
278
+ const hmacToSlug = new Map();
279
+ for (const [slug, hmac] of slugToHmac) {
280
+ hmacToSlug.set(hmac, slug);
281
+ }
282
+
283
+ const entries = new Map();
284
+ for (const [hmacName, oid] of parsed.entries) {
285
+ const slug = hmacToSlug.get(hmacName);
286
+ if (slug) {
287
+ entries.set(slug, oid);
288
+ }
289
+ }
290
+
291
+ assertPrivacyIndexCoverage({
292
+ treeEntryCount: parsed.entries.size,
293
+ resolvedCount: entries.size,
294
+ });
295
+
296
+ return entries;
163
297
  }
164
298
 
165
299
  /**
166
- * Validates vault metadata object structure.
167
- * @param {VaultMetadata} metadata - Metadata to validate.
300
+ * Builds a HMAC-name to slug map from the encrypted privacy index.
301
+ * @param {string} treeOid
302
+ * @param {VaultMetadata} metadata
303
+ * @param {Uint8Array} encryptionKey
304
+ * @returns {Promise<Map<string, string>>}
168
305
  */
169
- static #validateMetadata(metadata) {
170
- if (typeof metadata.version !== 'number' || metadata.version !== 1) {
306
+ async #readPrivacyHmacToSlug(treeOid, metadata, encryptionKey) {
307
+ const privacyIndexEntry = await this.#readTreeEntry(treeOid, VAULT_PRIVACY_INDEX_ENTRY);
308
+ if (!privacyIndexEntry) {
171
309
  throw new CasError(
172
- `Unsupported vault metadata version: ${metadata.version}`,
173
- 'VAULT_METADATA_INVALID',
174
- { metadata },
310
+ 'Privacy mode is enabled but .privacy-index is missing',
311
+ ErrorCodes.VAULT_PRIVACY_INDEX_MISSING,
175
312
  );
176
313
  }
177
- if (metadata.encryption) {
178
- VaultService.#validateEncryption(metadata.encryption, metadata);
314
+
315
+ const indexMeta = requirePrivacyIndexMeta(metadata);
316
+ const indexBlob = await this.vaultPersistence.readBlob(privacyIndexEntry.oid);
317
+ const slugToHmac = await this.privacyIndex.decryptIndex({
318
+ bytes: indexBlob,
319
+ encryptionKey,
320
+ meta: indexMeta,
321
+ });
322
+ const hmacToSlug = new Map();
323
+ for (const [slug, hmac] of slugToHmac) {
324
+ hmacToSlug.set(hmac, slug);
179
325
  }
326
+ return hmacToSlug;
180
327
  }
181
328
 
182
329
  /**
183
- * Reads and validates vault metadata from a blob OID.
184
- * @param {string} blobOid - Git blob OID of the .vault.json file.
185
- * @returns {Promise<VaultMetadata>}
330
+ * Builds public vault state from a cached privacy-enabled vault tree.
331
+ * @param {CachedVaultTree} cached
332
+ * @param {string} commitOid
333
+ * @param {Uint8Array|undefined} encryptionKey
334
+ * @returns {Promise<VaultState>}
186
335
  */
187
- async #readMetadataBlob(blobOid) {
188
- try {
189
- const blob = await this.persistence.readBlob(blobOid);
190
- const metadata = JSON.parse(blob.toString());
191
- VaultService.#validateMetadata(metadata);
192
- return metadata;
193
- } catch (err) {
194
- if (err instanceof CasError) { throw err; }
336
+ async #privacyStateFromCache(cached, commitOid, encryptionKey) {
337
+ if (!encryptionKey) {
195
338
  throw new CasError(
196
- `Failed to parse .vault.json: ${/** @type {Error} */ (err).message}`,
197
- 'VAULT_METADATA_INVALID',
198
- { originalError: err },
339
+ 'Privacy mode is enabled — encryption key is required to read vault state',
340
+ ErrorCodes.VAULT_PRIVACY_KEY_REQUIRED,
199
341
  );
200
342
  }
343
+ const entries = await this.stateCache.privacyEntries(
344
+ cached,
345
+ encryptionKey,
346
+ async (rawEntries, metadata) => await this.#resolvePrivacyEntries(
347
+ rawEntries,
348
+ /** @type {VaultMetadata} */ (metadata),
349
+ encryptionKey,
350
+ ),
351
+ );
352
+ return this.stateCache.toState({
353
+ entries,
354
+ parentCommitOid: commitOid,
355
+ metadata: cached.metadata,
356
+ });
201
357
  }
202
358
 
203
- // ---------------------------------------------------------------------------
204
- // State read / write
205
- // ---------------------------------------------------------------------------
206
-
207
359
  /**
208
- * Separates vault tree entries into slug→OID map and metadata blob OID.
209
- * @param {Array<{ mode: string, type: string, oid: string, name: string }>} treeEntries
210
- * @returns {{ entries: Map<string, string>, metadataBlobOid: string|null }}
360
+ * Builds public vault state from cached tree data.
361
+ * @param {CachedVaultTree} cached
362
+ * @param {string} commitOid
363
+ * @param {Uint8Array|undefined} encryptionKey
364
+ * @returns {Promise<VaultState>}
211
365
  */
212
- static #parseTreeEntries(treeEntries) {
213
- const entries = new Map();
214
- let metadataBlobOid = null;
215
- for (const entry of treeEntries) {
216
- if (entry.name === '.vault.json') {
217
- metadataBlobOid = entry.oid;
218
- } else {
219
- entries.set(decodeSlug(entry.name), entry.oid);
220
- }
366
+ async #stateForCachedTree(cached, commitOid, encryptionKey) {
367
+ if (cached.metadata?.encryption && encryptionKey) {
368
+ await this.#verifyCachedEncryptionKey(cached, encryptionKey);
221
369
  }
222
- return { entries, metadataBlobOid };
370
+ if (cached.metadata?.privacy?.enabled) {
371
+ return await this.#privacyStateFromCache(cached, commitOid, encryptionKey);
372
+ }
373
+ return this.#plainStateFromCache(cached, commitOid);
223
374
  }
224
375
 
225
376
  /**
226
- * Reads the current vault state from refs/cas/vault.
377
+ * Reads the current vault state from the current vault head.
378
+ * @param {Object} [options]
379
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy mode is enabled).
227
380
  * @returns {Promise<VaultState>}
228
381
  */
229
- async readState() {
230
- let commitOid;
231
- try {
232
- commitOid = await this.ref.resolveRef(VAULT_REF);
233
- } catch {
382
+ async readState({ encryptionKey } = {}) {
383
+ const current = await this.#resolveCurrentVaultTree();
384
+ if (!current) {
234
385
  return { entries: new Map(), parentCommitOid: null, metadata: null };
235
386
  }
236
387
 
237
- const treeOid = await this.ref.resolveTree(commitOid);
238
- const rawEntries = await this.persistence.readTree(treeOid);
239
- const { entries, metadataBlobOid } = VaultService.#parseTreeEntries(rawEntries);
240
- const metadata = metadataBlobOid
241
- ? await this.#readMetadataBlob(metadataBlobOid)
242
- : null;
243
-
244
- return { entries, parentCommitOid: commitOid, metadata };
388
+ const cached = await this.#readCachedVaultTree(current.treeOid);
389
+ return await this.#stateForCachedTree(cached, current.commitOid, encryptionKey);
245
390
  }
246
391
 
247
392
  /**
@@ -251,74 +396,170 @@ export default class VaultService {
251
396
  * @param {VaultMetadata} options.metadata - Vault metadata (.vault.json contents).
252
397
  * @param {string|null} options.parentCommitOid - Parent commit OID (null for first commit).
253
398
  * @param {string} options.message - Commit message.
399
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy is enabled).
400
+ * @param {boolean} [options.encryptionKeyVerified=false] - True when the current read already verified the key.
254
401
  * @returns {Promise<{ commitOid: string }>}
255
402
  */
256
- async writeCommit({ entries, metadata, parentCommitOid, message }) {
257
- const metadataBlob = await this.persistence.writeBlob(
258
- JSON.stringify(metadata, null, 2),
259
- );
260
-
261
- const treeLines = [`100644 blob ${metadataBlob}\t.vault.json`];
262
- for (const [slug, treeOid] of entries) {
263
- treeLines.push(`040000 tree ${treeOid}\t${encodeSlug(slug)}`);
403
+ async writeCommit({
404
+ entries,
405
+ metadata,
406
+ parentCommitOid,
407
+ message,
408
+ encryptionKey,
409
+ encryptionKeyVerified = false,
410
+ }) {
411
+ const privacyEnabled = Boolean(metadata?.privacy?.enabled);
412
+
413
+ if (privacyEnabled && !encryptionKey) {
414
+ throw new CasError(
415
+ 'Privacy mode is enabled — encryption key is required to write vault state',
416
+ ErrorCodes.VAULT_PRIVACY_KEY_REQUIRED,
417
+ );
264
418
  }
265
419
 
266
- const newTreeOid = await this.persistence.writeTree(treeLines);
420
+ const metaCopy = JSON.parse(JSON.stringify(metadata));
421
+ await this.#prepareVerifierMetadata(metaCopy, encryptionKey, encryptionKeyVerified);
267
422
 
268
- const commitOid = await this.ref.createCommit({
269
- treeOid: newTreeOid,
270
- parentOid: parentCommitOid,
423
+ const privateWrite = privacyEnabled
424
+ ? await this.#preparePrivacyWrite(entries, metaCopy, encryptionKey)
425
+ : {};
426
+
427
+ return await this.vaultPersistence.writeCommit({
428
+ entries,
429
+ metadata: metaCopy,
430
+ parentCommitOid,
271
431
  message,
432
+ ...privateWrite,
272
433
  });
273
- await this.#casUpdateRef(commitOid, parentCommitOid);
274
- return { commitOid };
275
434
  }
276
435
 
277
436
  /**
278
- * Atomically updates the vault ref with CAS semantics.
279
- * @param {string} newOid - New commit OID.
280
- * @param {string|null} expectedOldOid - Expected current commit OID.
437
+ * Verifies existing metadata or creates verifier metadata for legacy encrypted vaults.
438
+ * @param {VaultMetadata} metaCopy
439
+ * @param {Uint8Array|undefined} encryptionKey
440
+ * @param {boolean} encryptionKeyVerified
281
441
  */
282
- async #casUpdateRef(newOid, expectedOldOid) {
283
- try {
284
- await this.ref.updateRef({
285
- ref: VAULT_REF,
286
- newOid,
287
- expectedOldOid,
288
- });
289
- } catch (err) {
290
- throw new CasError(
291
- 'Concurrent vault update detected',
292
- 'VAULT_CONFLICT',
293
- { expectedParent: expectedOldOid, newCommit: newOid, originalError: err },
294
- );
442
+ async #prepareVerifierMetadata(metaCopy, encryptionKey, encryptionKeyVerified) {
443
+ if (!metaCopy.encryption || !encryptionKey) {
444
+ return;
445
+ }
446
+ if (!metaCopy.encryption.verifier) {
447
+ metaCopy.encryption.verifier = await this.keyVerifier.create(encryptionKey);
448
+ return;
295
449
  }
450
+ if (!encryptionKeyVerified) {
451
+ await this.keyVerifier.verify(metaCopy, encryptionKey);
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Builds HMAC-masked entry names and encrypted privacy index bytes.
457
+ * Mutates `metaCopy.privacy.indexMeta` with encryption metadata.
458
+ * @param {Map<string, string>} entries - Slug→treeOid map.
459
+ * @param {VaultMetadata} metaCopy - Mutable metadata clone.
460
+ * @param {Uint8Array} encryptionKey - Vault encryption key.
461
+ * @returns {Promise<{ persistedNameBySlug: Map<string, string>, privacyIndexBytes: Uint8Array }>}
462
+ */
463
+ async #preparePrivacyWrite(entries, metaCopy, encryptionKey) {
464
+ const { persistedNameBySlug, slugToHmac } = await this.privacyIndex.persistedNamesForEntries(
465
+ entries,
466
+ encryptionKey,
467
+ );
468
+ const encryptedIndex = await this.privacyIndex.encryptIndex({ slugToHmac, encryptionKey });
469
+ metaCopy.privacy.indexMeta = encryptedIndex.meta;
470
+ return {
471
+ persistedNameBySlug,
472
+ privacyIndexBytes: encryptedIndex.bytes,
473
+ };
474
+ }
475
+
476
+ /**
477
+ * Creates an isolated mutable draft for a vault mutation attempt.
478
+ * @param {VaultState} state
479
+ * @returns {{ entries: Map<string, string>, metadata: VaultMetadata }}
480
+ */
481
+ static #createMutationDraft(state) {
482
+ return {
483
+ entries: new Map(state.entries),
484
+ metadata: VaultService.#cloneMetadata(state.metadata || { version: 1 }),
485
+ };
486
+ }
487
+
488
+ /**
489
+ * Clones vault metadata so retry attempts mutate an isolated working copy.
490
+ * @param {VaultMetadata} metadata
491
+ * @returns {VaultMetadata}
492
+ */
493
+ static #cloneMetadata(metadata) {
494
+ return {
495
+ ...metadata,
496
+ encryption: metadata.encryption
497
+ ? {
498
+ ...metadata.encryption,
499
+ kdf: { ...metadata.encryption.kdf },
500
+ verifier: metadata.encryption.verifier
501
+ ? {
502
+ ...metadata.encryption.verifier,
503
+ meta: { ...metadata.encryption.verifier.meta },
504
+ }
505
+ : undefined,
506
+ }
507
+ : undefined,
508
+ privacy: metadata.privacy
509
+ ? {
510
+ ...metadata.privacy,
511
+ indexMeta: metadata.privacy.indexMeta ? { ...metadata.privacy.indexMeta } : undefined,
512
+ }
513
+ : undefined,
514
+ };
296
515
  }
297
516
 
298
517
  /**
299
518
  * Wraps a vault mutation with CAS retry logic.
300
- * @param {(state: VaultState) => { entries: Map<string, string>, metadata: VaultMetadata, message: string }|Promise<{ entries: Map<string, string>, metadata: VaultMetadata, message: string }>} mutationFn - Mutation function (sync or async).
301
- * @returns {Promise<{ commitOid: string }>}
519
+ *
520
+ * The mutation function may return an `encryptionKey` to override the one
521
+ * from options — this is needed by `initVault` where the key is derived
522
+ * inside the mutation.
523
+ *
524
+ * @param {(context: { state: VaultState, draft: { entries: Map<string, string>, metadata: VaultMetadata } }) => { message: string, result?: Record<string, unknown>, encryptionKey?: Uint8Array }|Promise<{ message: string, result?: Record<string, unknown>, encryptionKey?: Uint8Array }>} mutationFn
525
+ * @param {Object} [options]
526
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (threaded to readState/writeCommit for privacy mode).
527
+ * @returns {Promise<{ commitOid: string } & Record<string, unknown>>}
302
528
  */
303
- async #retryMutation(mutationFn) {
304
- for (let attempt = 0; attempt < MAX_CAS_RETRIES; attempt++) {
305
- const state = await this.readState();
306
- const { entries, metadata, message } = await mutationFn(state);
529
+ async #withVaultRetry(mutationFn, { encryptionKey } = {}) {
530
+ for (let attempt = 0; attempt < this.retryPolicy.maxAttempts; attempt++) {
531
+ const state = await this.readState({ encryptionKey });
532
+ const draft = VaultService.#createMutationDraft(state);
533
+ const { message, result, encryptionKey: mutationKey } = await mutationFn({ state, draft });
534
+ const effectiveKey = mutationKey || encryptionKey;
307
535
  try {
308
- return await this.writeCommit({
309
- entries, metadata, parentCommitOid: state.parentCommitOid, message,
536
+ const commit = await this.writeCommit({
537
+ entries: draft.entries,
538
+ metadata: draft.metadata,
539
+ parentCommitOid: state.parentCommitOid,
540
+ message,
541
+ encryptionKey: effectiveKey,
542
+ encryptionKeyVerified: VaultService.#wasEncryptionKeyVerifiedByRead(state, effectiveKey),
310
543
  });
544
+ return result ? { ...commit, ...result } : commit;
311
545
  } catch (err) {
312
- const isRetryable = err instanceof CasError && err.code === 'VAULT_CONFLICT';
313
- if (!isRetryable || attempt >= MAX_CAS_RETRIES - 1) {
546
+ if (!this.retryPolicy.isRetryable(err) || attempt >= this.retryPolicy.maxAttempts - 1) {
314
547
  throw err;
315
548
  }
316
- const delay = CAS_RETRY_BASE_MS * (2 ** attempt);
317
- await new Promise((r) => setTimeout(r, delay));
549
+ await this.retryPolicy.waitBeforeRetry(attempt);
318
550
  }
319
551
  }
320
552
  /* c8 ignore next 2 */
321
- throw new CasError('Vault CAS retries exhausted', 'VAULT_CONFLICT');
553
+ throw new CasError('Vault CAS retries exhausted', ErrorCodes.VAULT_CONFLICT);
554
+ }
555
+
556
+ /**
557
+ * @param {VaultState} state
558
+ * @param {Uint8Array|undefined} encryptionKey
559
+ * @returns {boolean}
560
+ */
561
+ static #wasEncryptionKeyVerifiedByRead(state, encryptionKey) {
562
+ return Boolean(encryptionKey && state.metadata?.encryption?.verifier);
322
563
  }
323
564
 
324
565
  // ---------------------------------------------------------------------------
@@ -327,7 +568,7 @@ export default class VaultService {
327
568
 
328
569
  /**
329
570
  * Builds vault encryption metadata from KDF result.
330
- * @param {Buffer} salt - KDF salt.
571
+ * @param {Uint8Array} salt - KDF salt.
331
572
  * @param {import('../../ports/CryptoPort.js').KdfParamSet} params - KDF parameters.
332
573
  * @returns {VaultEncryptionMeta}
333
574
  */
@@ -338,39 +579,88 @@ export default class VaultService {
338
579
  };
339
580
  }
340
581
 
582
+ /**
583
+ * Verifies and memoizes an encryption key for cached vault metadata.
584
+ * @param {CachedVaultTree} cached
585
+ * @param {Uint8Array} encryptionKey
586
+ * @returns {Promise<boolean>}
587
+ */
588
+ async #verifyCachedEncryptionKey(cached, encryptionKey) {
589
+ if (!cached.metadata?.encryption) {
590
+ return false;
591
+ }
592
+ if (this.stateCache.hasVerifiedEncryptionKey(cached, encryptionKey)) {
593
+ return true;
594
+ }
595
+ const verified = await this.keyVerifier.verify(cached.metadata, encryptionKey);
596
+ if (verified) {
597
+ this.stateCache.rememberVerifiedEncryptionKey(cached, encryptionKey);
598
+ }
599
+ return verified;
600
+ }
601
+
602
+ /**
603
+ * Verifies a key against tree metadata, reusing cached verifier state when available.
604
+ * @param {string} treeOid
605
+ * @param {VaultMetadata|null} metadata
606
+ * @param {Uint8Array} encryptionKey
607
+ * @returns {Promise<boolean>}
608
+ */
609
+ async #verifyEncryptionKeyForTree(treeOid, metadata, encryptionKey) {
610
+ if (!metadata?.encryption) {
611
+ return false;
612
+ }
613
+ const cached = this.stateCache.get(treeOid);
614
+ if (cached) {
615
+ return await this.#verifyCachedEncryptionKey(cached, encryptionKey);
616
+ }
617
+ return await this.keyVerifier.verify(metadata, encryptionKey);
618
+ }
619
+
341
620
  // ---------------------------------------------------------------------------
342
621
  // Public API
343
622
  // ---------------------------------------------------------------------------
344
623
 
345
624
  /**
346
- * Initializes the vault, optionally with encryption.
625
+ * Initializes the vault, optionally with encryption and privacy mode.
347
626
  * @param {Object} [options]
348
627
  * @param {string} [options.passphrase] - Passphrase for vault-level encryption.
349
628
  * @param {Object} [options.kdfOptions] - KDF options (algorithm, iterations, etc.).
629
+ * @param {boolean} [options.privacy=false] - Enable privacy mode (requires passphrase/encryption).
350
630
  * @returns {Promise<{ commitOid: string }>}
351
631
  */
352
- async initVault({ passphrase, kdfOptions } = {}) {
353
- const state = await this.readState();
354
-
355
- if (state.metadata?.encryption) {
632
+ async initVault({ passphrase, kdfOptions, privacy = false } = {}) {
633
+ if (privacy && !passphrase) {
356
634
  throw new CasError(
357
- 'Vault encryption is already configured',
358
- 'VAULT_ENCRYPTION_ALREADY_CONFIGURED',
635
+ 'Privacy mode requires vault encryption — provide a passphrase',
636
+ ErrorCodes.VAULT_PRIVACY_REQUIRES_ENCRYPTION,
359
637
  );
360
638
  }
361
639
 
362
- /** @type {VaultMetadata} */
363
- const metadata = { version: 1 };
364
- if (passphrase) {
365
- const { salt, params } = await this.crypto.deriveKey({ passphrase, ...kdfOptions });
366
- metadata.encryption = VaultService.#buildEncryptionMeta(salt, params);
367
- }
640
+ return await this.#withVaultRetry(async ({ state, draft }) => {
641
+ if (state.metadata?.encryption) {
642
+ throw new CasError(
643
+ 'Vault encryption is already configured',
644
+ ErrorCodes.VAULT_ENCRYPTION_ALREADY_CONFIGURED,
645
+ );
646
+ }
368
647
 
369
- return await this.writeCommit({
370
- entries: state.entries,
371
- metadata,
372
- parentCommitOid: state.parentCommitOid,
373
- message: 'vault: init',
648
+ draft.metadata = { version: 1 };
649
+ /** @type {Uint8Array|undefined} */
650
+ let derivedKey;
651
+ if (passphrase) {
652
+ const options = prepareKdfOptions(kdfOptions, { source: 'vault-init' });
653
+ const { key, salt, params } = await this.crypto.deriveKey({ passphrase, ...options });
654
+ draft.metadata.encryption = VaultService.#buildEncryptionMeta(salt, params);
655
+ draft.metadata.encryption.verifier = await this.keyVerifier.create(key);
656
+ derivedKey = key;
657
+ }
658
+
659
+ if (privacy) {
660
+ draft.metadata.privacy = { enabled: true };
661
+ }
662
+
663
+ return { message: 'vault: init', encryptionKey: derivedKey };
374
664
  });
375
665
  }
376
666
 
@@ -380,101 +670,241 @@ export default class VaultService {
380
670
  * @param {string} options.slug - Entry slug.
381
671
  * @param {string} options.treeOid - Git tree OID.
382
672
  * @param {boolean} [options.force=false] - Overwrite existing entry.
673
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy is enabled).
383
674
  * @returns {Promise<{ commitOid: string }>}
384
675
  */
385
- async addToVault({ slug, treeOid, force = false }) {
386
- this.validateSlug(slug);
676
+ async addToVault({ slug, treeOid, force = false, encryptionKey }) {
677
+ const vaultSlug = Slug.from(slug).toString();
387
678
 
388
- return await this.#retryMutation((state) => {
389
- if (state.entries.has(slug) && !force) {
679
+ return await this.#withVaultRetry(({ draft }) => {
680
+ if (draft.entries.has(vaultSlug) && !force) {
390
681
  throw new CasError(
391
- `Vault entry "${slug}" already exists (use force to overwrite)`,
392
- 'VAULT_ENTRY_EXISTS',
393
- { slug },
682
+ `Vault entry "${vaultSlug}" already exists (use force to overwrite)`,
683
+ ErrorCodes.VAULT_ENTRY_EXISTS,
684
+ { slug: vaultSlug },
394
685
  );
395
686
  }
396
- const isUpdate = state.entries.has(slug);
397
- state.entries.set(slug, treeOid);
398
- // Shallow copy to avoid mutating readState()'s object on CAS retries.
399
- const metadata = { ...(state.metadata || { version: 1 }) };
400
- if (metadata.encryption) {
687
+ const isUpdate = draft.entries.has(vaultSlug);
688
+ draft.entries.set(vaultSlug, treeOid);
689
+ if (draft.metadata.encryption) {
401
690
  // Tracks nonce-relevant operations: every addToVault on an encrypted
402
691
  // vault implies an encryption occurred at the store layer.
403
- metadata.encryptionCount = (metadata.encryptionCount || 0) + 1;
404
- if (metadata.encryptionCount >= VaultService.ENCRYPTION_COUNT_WARN) {
692
+ const currentCount = draft.metadata.encryptionCount || 0;
693
+ if (currentCount >= VaultService.ENCRYPTION_COUNT_MAX) {
694
+ throw new CasError(
695
+ `Vault encryption nonce budget exhausted (${currentCount}/${VaultService.ENCRYPTION_COUNT_MAX}); rotate your vault key before storing more encrypted assets`,
696
+ ErrorCodes.VAULT_NONCE_EXHAUSTED,
697
+ {
698
+ encryptionCount: currentCount,
699
+ maxEncryptionCount: VaultService.ENCRYPTION_COUNT_MAX,
700
+ },
701
+ );
702
+ }
703
+ draft.metadata.encryptionCount = currentCount + 1;
704
+ if (draft.metadata.encryptionCount >= VaultService.ENCRYPTION_COUNT_WARN) {
405
705
  this.observability.log(
406
706
  'warn',
407
- `Vault encryption count (${metadata.encryptionCount}) exceeds ` +
707
+ `Vault encryption count (${draft.metadata.encryptionCount}) exceeds ` +
408
708
  `${VaultService.ENCRYPTION_COUNT_WARN} — rotate your key`,
409
- { encryptionCount: metadata.encryptionCount },
709
+ { encryptionCount: draft.metadata.encryptionCount },
410
710
  );
411
711
  }
412
712
  }
413
713
  return {
414
- entries: state.entries,
415
- metadata,
416
- message: isUpdate ? `vault: update ${slug}` : `vault: add ${slug}`,
714
+ message: isUpdate ? `vault: update ${vaultSlug}` : `vault: add ${vaultSlug}`,
417
715
  };
418
- });
716
+ }, { encryptionKey });
717
+ }
718
+
719
+ /**
720
+ * Streams vault entries.
721
+ * @param {Object} [options]
722
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy is enabled).
723
+ * @returns {AsyncIterable<{ slug: string, treeOid: string }>}
724
+ */
725
+ async *iterateVault({ encryptionKey } = {}) {
726
+ const current = await this.#resolveCurrentVaultTree();
727
+ if (!current) {
728
+ return;
729
+ }
730
+ const metadata = await this.#readMetadataFromTree(current.treeOid);
731
+ if (metadata?.encryption && encryptionKey) {
732
+ await this.#verifyEncryptionKeyForTree(current.treeOid, metadata, encryptionKey);
733
+ }
734
+ if (metadata?.privacy?.enabled) {
735
+ yield* this.#iteratePrivateVaultEntries(current.treeOid, metadata, encryptionKey);
736
+ return;
737
+ }
738
+ yield* this.#iteratePlainVaultEntries(current.treeOid);
419
739
  }
420
740
 
421
741
  /**
422
742
  * Lists all vault entries.
743
+ * @param {Object} [options]
744
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy is enabled).
423
745
  * @returns {Promise<Array<{ slug: string, treeOid: string }>>}
424
746
  */
425
- async listVault() {
426
- const { entries } = await this.readState();
427
- return [...entries.entries()]
428
- .map(([slug, treeOid]) => ({ slug, treeOid }))
429
- .sort((a, b) => a.slug.localeCompare(b.slug));
747
+ async listVault({ encryptionKey } = {}) {
748
+ const entries = [];
749
+ for await (const entry of this.iterateVault({ encryptionKey })) {
750
+ entries.push(entry);
751
+ }
752
+ return entries.sort((a, b) => a.slug.localeCompare(b.slug));
753
+ }
754
+
755
+ /**
756
+ * @param {string} treeOid
757
+ * @returns {AsyncIterable<{ slug: string, treeOid: string }>}
758
+ */
759
+ async *#iteratePlainVaultEntries(treeOid) {
760
+ for await (const entry of this.#iterateTreeEntries(treeOid)) {
761
+ if (entry.name === VAULT_METADATA_ENTRY || entry.name === VAULT_PRIVACY_INDEX_ENTRY) {
762
+ continue;
763
+ }
764
+ yield {
765
+ slug: Slug.from(Slug.decode(entry.name)).toString(),
766
+ treeOid: entry.oid,
767
+ };
768
+ }
769
+ }
770
+
771
+ /**
772
+ * @param {string} treeOid
773
+ * @param {VaultMetadata} metadata
774
+ * @param {Uint8Array|undefined} encryptionKey
775
+ * @returns {AsyncIterable<{ slug: string, treeOid: string }>}
776
+ */
777
+ async *#iteratePrivateVaultEntries(treeOid, metadata, encryptionKey) {
778
+ if (!encryptionKey) {
779
+ throw new CasError(
780
+ 'Privacy mode is enabled — encryption key is required to read vault state',
781
+ ErrorCodes.VAULT_PRIVACY_KEY_REQUIRED,
782
+ );
783
+ }
784
+ const hmacToSlug = await this.#readPrivacyHmacToSlug(treeOid, metadata, encryptionKey);
785
+ const resolvedEntries = [];
786
+ let treeEntryCount = 0;
787
+ for await (const entry of this.#iterateTreeEntries(treeOid)) {
788
+ if (entry.name === VAULT_METADATA_ENTRY || entry.name === VAULT_PRIVACY_INDEX_ENTRY) {
789
+ continue;
790
+ }
791
+ treeEntryCount++;
792
+ const slug = hmacToSlug.get(entry.name);
793
+ if (slug) {
794
+ resolvedEntries.push({ slug, treeOid: entry.oid });
795
+ }
796
+ }
797
+ assertPrivacyIndexCoverage({ treeEntryCount, resolvedCount: resolvedEntries.length });
798
+ for (const entry of resolvedEntries) {
799
+ yield entry;
800
+ }
430
801
  }
431
802
 
432
803
  /**
433
804
  * Removes an entry from the vault.
434
805
  * @param {Object} options
435
806
  * @param {string} options.slug - Entry slug to remove.
807
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy is enabled).
436
808
  * @returns {Promise<{ commitOid: string, removedTreeOid: string }>}
437
809
  */
438
- async removeFromVault({ slug }) {
439
- /** @type {string|undefined} */
440
- let removedTreeOid;
441
-
442
- const result = await this.#retryMutation((state) => {
443
- if (!state.entries.has(slug)) {
810
+ async removeFromVault({ slug, encryptionKey }) {
811
+ const vaultSlug = Slug.from(slug).toString();
812
+ const result = await this.#withVaultRetry(({ draft }) => {
813
+ if (!draft.entries.has(vaultSlug)) {
444
814
  throw new CasError(
445
- `Vault entry "${slug}" not found`,
446
- 'VAULT_ENTRY_NOT_FOUND',
447
- { slug },
815
+ `Vault entry "${vaultSlug}" not found`,
816
+ ErrorCodes.VAULT_ENTRY_NOT_FOUND,
817
+ { slug: vaultSlug },
448
818
  );
449
819
  }
450
- removedTreeOid = state.entries.get(slug);
451
- state.entries.delete(slug);
820
+ const removedTreeOid = /** @type {string} */ (draft.entries.get(vaultSlug));
821
+ draft.entries.delete(vaultSlug);
452
822
  return {
453
- entries: state.entries,
454
- metadata: state.metadata || { version: 1 },
455
- message: `vault: remove ${slug}`,
823
+ message: `vault: remove ${vaultSlug}`,
824
+ result: { removedTreeOid },
456
825
  };
457
- });
826
+ }, { encryptionKey });
458
827
 
459
- return { commitOid: result.commitOid, removedTreeOid: /** @type {string} */ (removedTreeOid) };
828
+ return {
829
+ commitOid: result.commitOid,
830
+ removedTreeOid: /** @type {string} */ (result.removedTreeOid),
831
+ };
460
832
  }
461
833
 
462
834
  /**
463
835
  * Resolves a vault entry slug to its tree OID.
464
836
  * @param {Object} options
465
837
  * @param {string} options.slug - Entry slug.
838
+ * @param {Uint8Array} [options.encryptionKey] - Vault encryption key (required when privacy is enabled).
466
839
  * @returns {Promise<string>} The tree OID.
467
840
  */
468
- async resolveVaultEntry({ slug }) {
469
- const { entries } = await this.readState();
470
- if (!entries.has(slug)) {
841
+ async resolveVaultEntry({ slug, encryptionKey }) {
842
+ const vaultSlug = Slug.from(slug).toString();
843
+ const current = await this.#resolveCurrentVaultTree();
844
+ if (!current) {
471
845
  throw new CasError(
472
- `Vault entry "${slug}" not found`,
473
- 'VAULT_ENTRY_NOT_FOUND',
474
- { slug },
846
+ `Vault entry "${vaultSlug}" not found`,
847
+ ErrorCodes.VAULT_ENTRY_NOT_FOUND,
848
+ { slug: vaultSlug },
475
849
  );
476
850
  }
477
- return /** @type {string} */ (entries.get(slug));
851
+ const metadata = await this.#readMetadataFromTree(current.treeOid);
852
+ if (metadata?.encryption && encryptionKey) {
853
+ await this.#verifyEncryptionKeyForTree(current.treeOid, metadata, encryptionKey);
854
+ }
855
+ const treePath = await this.#treePathForVaultSlug({
856
+ metadata,
857
+ vaultSlug,
858
+ encryptionKey,
859
+ });
860
+ const entry = await this.#readTreeEntry(current.treeOid, treePath);
861
+ if (!entry) {
862
+ throw new CasError(
863
+ `Vault entry "${vaultSlug}" not found`,
864
+ ErrorCodes.VAULT_ENTRY_NOT_FOUND,
865
+ { slug: vaultSlug },
866
+ );
867
+ }
868
+ return entry.oid;
869
+ }
870
+
871
+ /**
872
+ * @param {Object} options
873
+ * @param {VaultMetadata|null} options.metadata
874
+ * @param {string} options.vaultSlug
875
+ * @param {Uint8Array|undefined} options.encryptionKey
876
+ * @returns {Promise<string>}
877
+ */
878
+ async #treePathForVaultSlug({ metadata, vaultSlug, encryptionKey }) {
879
+ if (!metadata?.privacy?.enabled) {
880
+ return Slug.from(vaultSlug).toTreePath();
881
+ }
882
+ if (!encryptionKey) {
883
+ throw new CasError(
884
+ 'Privacy mode is enabled — encryption key is required to read vault state',
885
+ ErrorCodes.VAULT_PRIVACY_KEY_REQUIRED,
886
+ );
887
+ }
888
+ requirePrivacyIndexMeta(metadata);
889
+ return await this.privacyIndex.persistedNameForSlug({ encryptionKey, slug: vaultSlug });
890
+ }
891
+
892
+ /**
893
+ * Verifies a vault encryption key against metadata when verifier data exists.
894
+ * @param {Object} options
895
+ * @param {Uint8Array} options.encryptionKey - Vault encryption key to verify.
896
+ * @returns {Promise<{ verified: boolean, requiresMigration: boolean }>}
897
+ */
898
+ async verifyVaultKey({ encryptionKey }) {
899
+ const state = await this.readState({ encryptionKey });
900
+ if (!state.metadata?.encryption) {
901
+ throw new CasError('Vault is not encrypted', ErrorCodes.VAULT_METADATA_INVALID);
902
+ }
903
+ const verified = Boolean(state.metadata.encryption.verifier);
904
+ return {
905
+ verified,
906
+ requiresMigration: !verified,
907
+ };
478
908
  }
479
909
 
480
910
  /**
@@ -482,7 +912,75 @@ export default class VaultService {
482
912
  * @returns {Promise<VaultMetadata|null>}
483
913
  */
484
914
  async getVaultMetadata() {
485
- const { metadata } = await this.readState();
486
- return metadata;
915
+ const current = await this.#resolveCurrentVaultTree();
916
+ if (!current) {
917
+ return null;
918
+ }
919
+ return await this.#readMetadataFromTree(current.treeOid);
920
+ }
921
+ }
922
+
923
+ /**
924
+ * @param {object} options
925
+ * @param {VaultPersistence} [options.vaultPersistence]
926
+ * @param {import('../../ports/GitPersistencePort.js').default} [options.persistence]
927
+ * @param {import('../../ports/GitRefPort.js').default} [options.ref]
928
+ */
929
+ function validateConstructorPersistenceDependencies({ vaultPersistence, persistence, ref }) {
930
+ const legacyProvided = persistence !== undefined || ref !== undefined;
931
+ if (vaultPersistence && legacyProvided) {
932
+ throw new CasError(
933
+ 'VaultService accepts either vaultPersistence or persistence/ref, not both',
934
+ ErrorCodes.VAULT_DEPENDENCY_INVALID,
935
+ { conflict: [VAULT_PERSISTENCE_OPTION, PERSISTENCE_OPTION, REF_OPTION] },
936
+ );
937
+ }
938
+ if (!vaultPersistence && (persistence === undefined || ref === undefined)) {
939
+ const missing = [];
940
+ if (persistence === undefined) {
941
+ missing.push(PERSISTENCE_OPTION);
942
+ }
943
+ if (ref === undefined) {
944
+ missing.push(REF_OPTION);
945
+ }
946
+ throw new CasError(
947
+ 'VaultService requires persistence and ref when vaultPersistence is not provided',
948
+ ErrorCodes.VAULT_DEPENDENCY_INVALID,
949
+ { missing },
950
+ );
951
+ }
952
+ }
953
+
954
+ /**
955
+ * @param {VaultMetadata} metadata
956
+ * @returns {object}
957
+ */
958
+ function requirePrivacyIndexMeta(metadata) {
959
+ const indexMeta = metadata?.privacy?.indexMeta;
960
+ if (typeof indexMeta === 'object' && indexMeta !== null) {
961
+ return indexMeta;
962
+ }
963
+ throw new CasError(
964
+ 'Privacy mode is enabled but privacy index metadata is missing',
965
+ ErrorCodes.VAULT_PRIVACY_INDEX_INVALID,
966
+ { field: PRIVACY_INDEX_META_FIELD },
967
+ );
968
+ }
969
+
970
+ /**
971
+ * @param {{ treeEntryCount: number, resolvedCount: number }} coverage
972
+ */
973
+ function assertPrivacyIndexCoverage({ treeEntryCount, resolvedCount }) {
974
+ if (resolvedCount === treeEntryCount) {
975
+ return;
487
976
  }
977
+ throw new CasError(
978
+ 'Privacy index does not cover all vault tree entries',
979
+ ErrorCodes.VAULT_PRIVACY_INDEX_INVALID,
980
+ {
981
+ unmatchedCount: treeEntryCount - resolvedCount,
982
+ treeEntryCount,
983
+ resolvedCount,
984
+ },
985
+ );
488
986
  }