@git-stunts/git-cas 5.3.1 → 6.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +401 -4
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +872 -0
  6. package/README.md +219 -325
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +72 -20
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +604 -450
  20. package/bin/io.js +86 -0
  21. package/bin/passphrase-source.js +266 -0
  22. package/bin/restore-output-target.js +28 -0
  23. package/bin/ui/blocks/asset-card.js +109 -0
  24. package/bin/ui/blocks/health-dashboard.js +149 -0
  25. package/bin/ui/blocks/heatmap-block.js +67 -0
  26. package/bin/ui/blocks/merkle-explorer.js +163 -0
  27. package/bin/ui/blocks/operation-feed.js +176 -0
  28. package/bin/ui/blocks/wizard-block.js +168 -0
  29. package/bin/ui/components/short-sha.js +36 -0
  30. package/bin/ui/context.js +56 -1
  31. package/bin/ui/dashboard-cmds.js +1578 -13
  32. package/bin/ui/dashboard-view.js +612 -145
  33. package/bin/ui/dashboard.js +998 -214
  34. package/bin/ui/encryption-card.js +69 -26
  35. package/bin/ui/heatmap.js +26 -54
  36. package/bin/ui/history-timeline.js +51 -19
  37. package/bin/ui/manifest-view.js +115 -60
  38. package/bin/ui/merkle-dag.js +83 -0
  39. package/bin/ui/progress.js +15 -9
  40. package/bin/ui/repo-treemap.js +328 -0
  41. package/bin/ui/shaders/bak-sneppen.js +180 -0
  42. package/bin/ui/shaders/fractal-zoom.js +99 -0
  43. package/bin/ui/shaders/merkle-tree.js +142 -0
  44. package/bin/ui/shaders/organic-flow.js +96 -0
  45. package/bin/ui/shaders/phase-portrait.js +93 -0
  46. package/bin/ui/store-wizard.js +296 -0
  47. package/bin/ui/theme.js +155 -0
  48. package/bin/ui/vault-report.js +495 -0
  49. package/build-info.json +4 -0
  50. package/docs/API.md +2224 -0
  51. package/docs/ENCRYPTION_MODES.md +33 -0
  52. package/docs/EXTENDING.md +174 -0
  53. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  54. package/docs/THREAT_MODEL.md +269 -0
  55. package/docs/VAULT_INTERNALS.md +251 -0
  56. package/docs/WALKTHROUGH.md +1868 -0
  57. package/docs/demo.gif +0 -0
  58. package/docs/releases/v6.0.0.md +104 -0
  59. package/examples/README.md +260 -0
  60. package/index.d.ts +208 -65
  61. package/index.js +163 -54
  62. package/package.json +35 -6
  63. package/scripts/migrate-encryption.js +680 -0
  64. package/src/domain/bytes/ByteLayout.js +96 -0
  65. package/src/domain/encoding/base64.js +91 -0
  66. package/src/domain/encoding/hex.js +14 -0
  67. package/src/domain/encoding/utf8.js +123 -0
  68. package/src/domain/encryption/schemes.js +132 -0
  69. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  70. package/src/domain/errors/CasError.d.ts +28 -0
  71. package/src/domain/errors/CasError.js +43 -6
  72. package/src/domain/errors/Codes.js +54 -0
  73. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  74. package/src/domain/errors/GitError.js +10 -0
  75. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  76. package/src/domain/errors/IntegrityError.js +10 -0
  77. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  78. package/src/domain/errors/InvalidOidError.js +10 -0
  79. package/src/domain/errors/InvalidOptionsError.js +10 -0
  80. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  81. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  82. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  83. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  84. package/src/domain/errors/PortNotImplementedError.js +10 -0
  85. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  86. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  87. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  88. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  89. package/src/domain/errors/createCasError.js +68 -0
  90. package/src/domain/errors/index.js +20 -0
  91. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  92. package/src/domain/helpers/codecBytes.js +34 -0
  93. package/src/domain/helpers/gitRefErrors.js +84 -0
  94. package/src/domain/helpers/scryptMaxmem.js +22 -0
  95. package/src/domain/outcomes/RestoreFailure.js +15 -0
  96. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  97. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  98. package/src/domain/outcomes/StoreFailure.js +15 -0
  99. package/src/domain/outcomes/StoreOutcome.js +11 -0
  100. package/src/domain/outcomes/StoreSuccess.js +17 -0
  101. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  102. package/src/domain/schemas/ManifestSchema.js +67 -13
  103. package/src/domain/services/CasService.d.ts +123 -38
  104. package/src/domain/services/CasService.js +298 -834
  105. package/src/domain/services/ChunkRepository.js +230 -0
  106. package/src/domain/services/CompressionStreams.js +72 -0
  107. package/src/domain/services/ConvergentEncryption.js +128 -0
  108. package/src/domain/services/GitTreeBuilder.js +86 -0
  109. package/src/domain/services/IntegrityVerifier.js +199 -0
  110. package/src/domain/services/KeyResolver.js +49 -42
  111. package/src/domain/services/ManifestDiff.js +56 -0
  112. package/src/domain/services/ManifestRepository.js +286 -0
  113. package/src/domain/services/PrefetchWindow.js +48 -0
  114. package/src/domain/services/RecipientService.js +157 -0
  115. package/src/domain/services/RedactingObservability.js +169 -0
  116. package/src/domain/services/RestorePipeline.js +68 -0
  117. package/src/domain/services/StorePipeline.js +201 -0
  118. package/src/domain/services/VaultKeyVerifier.js +101 -0
  119. package/src/domain/services/VaultMetadataCodec.js +206 -0
  120. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  121. package/src/domain/services/VaultPersistence.js +410 -0
  122. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  123. package/src/domain/services/VaultService.js +749 -251
  124. package/src/domain/services/VaultStateCache.js +225 -0
  125. package/src/domain/services/VaultTreeCodec.js +121 -0
  126. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  127. package/src/domain/strategies/Aad.js +39 -0
  128. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  129. package/src/domain/strategies/RestoreCompressed.js +40 -0
  130. package/src/domain/strategies/RestoreConvergent.js +44 -0
  131. package/src/domain/strategies/RestoreFramed.js +55 -0
  132. package/src/domain/strategies/RestorePlain.js +37 -0
  133. package/src/domain/strategies/RestoreStrategy.js +35 -0
  134. package/src/domain/strategies/RestoreWhole.js +135 -0
  135. package/src/domain/strategies/StoreConvergent.js +28 -0
  136. package/src/domain/strategies/StoreFramed.js +39 -0
  137. package/src/domain/strategies/StorePlain.js +20 -0
  138. package/src/domain/strategies/StoreStrategy.js +61 -0
  139. package/src/domain/strategies/StoreWhole.js +34 -0
  140. package/src/domain/value-objects/Chunk.js +1 -2
  141. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  142. package/src/domain/value-objects/Manifest.d.ts +40 -4
  143. package/src/domain/value-objects/Manifest.js +61 -20
  144. package/src/domain/value-objects/Oid.js +45 -0
  145. package/src/domain/value-objects/Slug.js +124 -0
  146. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  147. package/src/helpers/aesGcmMeta.js +55 -0
  148. package/src/helpers/canonicalBase64.js +1 -0
  149. package/src/helpers/kdfPolicy.js +194 -0
  150. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  151. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  152. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  153. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  154. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  155. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  156. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  157. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  158. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  159. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  160. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  161. package/src/infrastructure/codecs/CborCodec.js +3 -3
  162. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  163. package/src/infrastructure/createGitPlumbing.js +22 -0
  164. package/src/package-version.js +1 -0
  165. package/src/ports/ChunkingPort.js +3 -3
  166. package/src/ports/CodecPort.js +4 -4
  167. package/src/ports/CompressionPort.js +57 -0
  168. package/src/ports/CryptoPort.js +138 -50
  169. package/src/ports/GitPersistencePort.js +32 -2
  170. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  171. package/src/ports/GitRefPort.js +1 -1
  172. package/src/types/ambient.d.ts +10 -5
  173. package/test/CONVENTIONS.md +94 -0
  174. package/test/cycles/README.md +13 -0
@@ -0,0 +1,199 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import { concatBytes } from '../bytes/ByteLayout.js';
3
+ import { buildFramedAad, buildWholeAad } from '../strategies/Aad.js';
4
+ import { SCHEME_CONVERGENT, SCHEME_FRAMED } from '../encryption/schemes.js';
5
+ import { ErrorCodes } from '../errors/index.js';
6
+
7
+ /** @typedef {import('../value-objects/Manifest.js').default} Manifest */
8
+
9
+ /**
10
+ * Stored content integrity verification boundary.
11
+ */
12
+ export default class IntegrityVerifier {
13
+ #chunks;
14
+ #crypto;
15
+ #framed;
16
+ #isLegacyNoAad;
17
+ #keyResolver;
18
+ #observability;
19
+ #validateEncryptionMeta;
20
+
21
+ /**
22
+ * @param {Object} options
23
+ * @param {import('./ChunkRepository.js').default} options.chunks
24
+ * @param {import('../../ports/CryptoPort.js').default} options.crypto
25
+ * @param {import('../strategies/FramedRecordCodec.js').default} options.framed
26
+ * @param {(manifest: Manifest) => boolean} options.isLegacyNoAad
27
+ * @param {import('./KeyResolver.js').default} options.keyResolver
28
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
29
+ * @param {(manifest: Manifest) => object|undefined} options.validateEncryptionMeta
30
+ */
31
+ constructor({ chunks, crypto, framed, isLegacyNoAad, keyResolver, observability, validateEncryptionMeta }) {
32
+ this.#chunks = chunks;
33
+ this.#crypto = crypto;
34
+ this.#framed = framed;
35
+ this.#isLegacyNoAad = isLegacyNoAad;
36
+ this.#keyResolver = keyResolver;
37
+ this.#observability = observability;
38
+ this.#validateEncryptionMeta = validateEncryptionMeta;
39
+ }
40
+
41
+ /**
42
+ * @param {Manifest} manifest
43
+ * @param {{ encryptionKey?: Uint8Array, passphrase?: string }} [options]
44
+ * @returns {Promise<boolean>}
45
+ */
46
+ async verify(manifest, options = {}) {
47
+ const encryptionMeta = this.#getVerifyEncryptionMeta(manifest);
48
+ if (encryptionMeta === false) {
49
+ return false;
50
+ }
51
+ if (encryptionMeta?.scheme === SCHEME_CONVERGENT) {
52
+ return this.#verifyConvergentIntegrity(manifest, options);
53
+ }
54
+ return this.#verifyNonConvergentIntegrity(manifest, encryptionMeta, options);
55
+ }
56
+
57
+ #getVerifyEncryptionMeta(manifest) {
58
+ try {
59
+ return this.#validateEncryptionMeta(manifest);
60
+ } catch (err) {
61
+ if (err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
62
+ this.#emitIntegrityFail(manifest, err.meta);
63
+ return false;
64
+ }
65
+ throw err;
66
+ }
67
+ }
68
+
69
+ async #verifyNonConvergentIntegrity(manifest, encryptionMeta, options) {
70
+ const buffers = await this.#verifyChunkDigests(manifest);
71
+ if (buffers === false) {
72
+ return false;
73
+ }
74
+
75
+ if (encryptionMeta) {
76
+ const key = await this.#resolveVerifyKey(manifest, options);
77
+ if (key === false) {
78
+ return false;
79
+ }
80
+ const authOk = encryptionMeta.scheme === SCHEME_FRAMED
81
+ ? await this.#verifyFramedAuth({ manifest, encryptionMeta, key, buffers })
82
+ : await this.#verifyEncryptedAuth({ manifest, encryptionMeta, key, buffers });
83
+ if (!authOk) {
84
+ return false;
85
+ }
86
+ }
87
+
88
+ this.#observability.metric('integrity', { action: 'pass', slug: manifest.slug });
89
+ return true;
90
+ }
91
+
92
+ async #verifyConvergentIntegrity(manifest, options) {
93
+ const key = await this.#resolveVerifyKey(manifest, options);
94
+ if (key === false) {
95
+ return false;
96
+ }
97
+
98
+ try {
99
+ for (const chunk of manifest.chunks) {
100
+ await this.#chunks.readAndVerifyChunk(chunk, { convergentKey: key });
101
+ }
102
+ } catch (err) {
103
+ if (err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
104
+ this.#emitIntegrityFail(manifest, err.meta);
105
+ return false;
106
+ }
107
+ throw err;
108
+ }
109
+
110
+ this.#observability.metric('integrity', { action: 'pass', slug: manifest.slug });
111
+ return true;
112
+ }
113
+
114
+ async #verifyChunkDigests(manifest) {
115
+ const buffers = [];
116
+ for (const chunk of manifest.chunks) {
117
+ const blob = await this.#chunks.readChunkBlob(chunk.blob);
118
+ const digest = await this.#crypto.sha256(blob);
119
+ if (digest !== chunk.digest) {
120
+ this.#emitIntegrityFail(manifest, {
121
+ chunkIndex: chunk.index,
122
+ expected: chunk.digest,
123
+ actual: digest,
124
+ });
125
+ return false;
126
+ }
127
+ buffers.push(blob);
128
+ }
129
+ return buffers;
130
+ }
131
+
132
+ async #resolveVerifyKey(manifest, options) {
133
+ try {
134
+ return await this.#keyResolver.resolveForDecryption(
135
+ manifest,
136
+ options.encryptionKey,
137
+ options.passphrase,
138
+ );
139
+ } catch (err) {
140
+ if (err instanceof CasError && [ErrorCodes.MISSING_KEY, ErrorCodes.NO_MATCHING_RECIPIENT, ErrorCodes.DEK_UNWRAP_FAILED].includes(err.code)) {
141
+ this.#emitIntegrityFail(manifest, { reason: 'auth', code: err.code });
142
+ return false;
143
+ }
144
+ throw err;
145
+ }
146
+ }
147
+
148
+ async #verifyEncryptedAuth({ manifest, encryptionMeta, key, buffers }) {
149
+ try {
150
+ const aad = this.#isLegacyNoAad(manifest) ? undefined : buildWholeAad(manifest.slug);
151
+ await this.#crypto.decryptBuffer(concatBytes(buffers), key, encryptionMeta, aad);
152
+ return true;
153
+ } catch (err) {
154
+ if (err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
155
+ this.#emitIntegrityFail(manifest, { reason: 'auth', code: err.code });
156
+ return false;
157
+ }
158
+ throw err;
159
+ }
160
+ }
161
+
162
+ async #verifyFramedAuth({ manifest, encryptionMeta, key, buffers }) {
163
+ try {
164
+ const source = (async function* framedSource() {
165
+ for (const buffer of buffers) {
166
+ yield buffer;
167
+ }
168
+ })();
169
+
170
+ const legacyNoAad = this.#isLegacyNoAad(manifest);
171
+ let frameIndex = 0;
172
+ for await (const record of this.#framed.parse(source, encryptionMeta.frameBytes)) {
173
+ const aad = legacyNoAad ? undefined : buildFramedAad(manifest.slug, frameIndex);
174
+ await this.#framed.decryptRecord({ record, key, aad });
175
+ frameIndex++;
176
+ }
177
+
178
+ return true;
179
+ } catch (err) {
180
+ if (err instanceof CasError && err.code === ErrorCodes.INTEGRITY_ERROR) {
181
+ this.#emitIntegrityFail(manifest, {
182
+ reason: err.meta?.reason === 'framed-record-parse' ? 'framing' : 'auth',
183
+ code: err.code,
184
+ ...err.meta,
185
+ });
186
+ return false;
187
+ }
188
+ throw err;
189
+ }
190
+ }
191
+
192
+ #emitIntegrityFail(manifest, extra = {}) {
193
+ this.#observability.metric('integrity', {
194
+ action: 'fail',
195
+ slug: manifest.slug,
196
+ ...extra,
197
+ });
198
+ }
199
+ }
@@ -1,3 +1,6 @@
1
+ import { ErrorCodes } from '../errors/index.js';
2
+
3
+ /** @typedef {import('../value-objects/Manifest.js').default} Manifest */
1
4
  /**
2
5
  * @fileoverview Key resolution service extracted from CasService.
3
6
  *
@@ -5,6 +8,8 @@
5
8
  * resolving encryption keys from passphrases, and envelope recipient management.
6
9
  */
7
10
  import CasError from '../errors/CasError.js';
11
+ import { prepareKdfOptions, prepareStoredKdfOptions } from '../../helpers/kdfPolicy.js';
12
+ import { decodeBase64, encodeBase64 } from '../encoding/base64.js';
8
13
 
9
14
  /**
10
15
  * Resolves encryption keys for store and restore operations.
@@ -31,7 +36,7 @@ export default class KeyResolver {
31
36
 
32
37
  /**
33
38
  * Validates that passphrase and encryptionKey are not both provided.
34
- * @param {Buffer} [encryptionKey]
39
+ * @param {Uint8Array} [encryptionKey]
35
40
  * @param {string} [passphrase]
36
41
  * @throws {CasError} INVALID_OPTIONS if both are provided.
37
42
  */
@@ -39,21 +44,21 @@ export default class KeyResolver {
39
44
  if (passphrase && encryptionKey) {
40
45
  throw new CasError(
41
46
  'Provide either encryptionKey or passphrase, not both',
42
- 'INVALID_OPTIONS',
47
+ ErrorCodes.INVALID_OPTIONS,
43
48
  );
44
49
  }
45
50
  }
46
51
 
47
52
  /**
48
53
  * Wraps a DEK with a KEK using AES-256-GCM.
49
- * @param {Buffer} dek - 32-byte data encryption key.
50
- * @param {Buffer} kek - 32-byte key encryption key.
54
+ * @param {Uint8Array} dek - 32-byte data encryption key.
55
+ * @param {Uint8Array} kek - 32-byte key encryption key.
51
56
  * @returns {Promise<{ wrappedDek: string, nonce: string, tag: string }>}
52
57
  */
53
58
  async wrapDek(dek, kek) {
54
59
  const { buf, meta } = await this.#crypto.encryptBuffer(dek, kek);
55
60
  return {
56
- wrappedDek: buf.toString('base64'),
61
+ wrappedDek: encodeBase64(buf),
57
62
  nonce: meta.nonce,
58
63
  tag: meta.tag,
59
64
  };
@@ -62,13 +67,13 @@ export default class KeyResolver {
62
67
  /**
63
68
  * Unwraps a DEK from a recipient entry using the given KEK.
64
69
  * @param {{ wrappedDek: string, nonce: string, tag: string }} recipientEntry
65
- * @param {Buffer} kek - 32-byte key encryption key.
66
- * @returns {Promise<Buffer>} The unwrapped DEK.
70
+ * @param {Uint8Array} kek - 32-byte key encryption key.
71
+ * @returns {Promise<Uint8Array>} The unwrapped DEK.
67
72
  * @throws {CasError} DEK_UNWRAP_FAILED if decryption fails.
68
73
  */
69
74
  async unwrapDek(recipientEntry, kek) {
70
75
  try {
71
- const ciphertext = Buffer.from(recipientEntry.wrappedDek, 'base64');
76
+ const ciphertext = decodeBase64(recipientEntry.wrappedDek);
72
77
  const meta = {
73
78
  algorithm: 'aes-256-gcm',
74
79
  nonce: recipientEntry.nonce,
@@ -77,10 +82,10 @@ export default class KeyResolver {
77
82
  };
78
83
  return await this.#crypto.decryptBuffer(ciphertext, kek, meta);
79
84
  } catch (err) {
80
- if (err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED') { throw err; }
85
+ if (err instanceof CasError && err.code === ErrorCodes.DEK_UNWRAP_FAILED) { throw err; }
81
86
  throw new CasError(
82
87
  'Failed to unwrap DEK: authentication failed',
83
- 'DEK_UNWRAP_FAILED',
88
+ ErrorCodes.DEK_UNWRAP_FAILED,
84
89
  { originalError: err },
85
90
  );
86
91
  }
@@ -89,10 +94,10 @@ export default class KeyResolver {
89
94
  /**
90
95
  * Resolves the decryption key from a manifest, handling both legacy and
91
96
  * envelope (multi-recipient) encrypted manifests.
92
- * @param {import('../value-objects/Manifest.js').default} manifest
93
- * @param {Buffer} [encryptionKey]
97
+ * @param {Manifest} manifest
98
+ * @param {Uint8Array} [encryptionKey]
94
99
  * @param {string} [passphrase]
95
- * @returns {Promise<Buffer|undefined>}
100
+ * @returns {Promise<Uint8Array|undefined>}
96
101
  */
97
102
  async resolveForDecryption(manifest, encryptionKey, passphrase) {
98
103
  KeyResolver.validateKeySourceExclusive(encryptionKey, passphrase);
@@ -103,7 +108,7 @@ export default class KeyResolver {
103
108
 
104
109
  if (!key) {
105
110
  if (manifest.encryption?.encrypted) {
106
- throw new CasError('Encryption key required to restore encrypted content', 'MISSING_KEY');
111
+ throw new CasError('Encryption key required to restore encrypted content', ErrorCodes.MISSING_KEY);
107
112
  }
108
113
  return undefined;
109
114
  }
@@ -114,15 +119,16 @@ export default class KeyResolver {
114
119
 
115
120
  /**
116
121
  * Resolves encryptionKey/passphrase into a key and optional KDF params for store().
117
- * @param {Buffer} [encryptionKey]
122
+ * @param {Uint8Array} [encryptionKey]
118
123
  * @param {string} [passphrase]
119
124
  * @param {Object} [kdfOptions] - KDF options when using passphrase.
120
- * @returns {Promise<{ key: Buffer|undefined, encExtra: Object }>}
125
+ * @returns {Promise<{ key: Uint8Array|undefined, encExtra: Object }>}
121
126
  */
122
127
  async resolveForStore(encryptionKey, passphrase, kdfOptions) {
123
128
  let kdfParams;
124
129
  if (passphrase) {
125
- const derived = await this.#crypto.deriveKey({ passphrase, ...kdfOptions });
130
+ const options = prepareKdfOptions(kdfOptions, { source: 'store' });
131
+ const derived = await this.#crypto.deriveKey({ passphrase, ...options });
126
132
  encryptionKey = derived.key;
127
133
  kdfParams = derived.params;
128
134
  }
@@ -132,17 +138,17 @@ export default class KeyResolver {
132
138
 
133
139
  /**
134
140
  * Resolves envelope recipients into a DEK and wrapped entries for store().
135
- * @param {Array<{label: string, key: Buffer}>} recipients
136
- * @returns {Promise<{ key: Buffer, encExtra: { recipients: Array } }>}
141
+ * @param {Array<{label: string, key: Uint8Array}>} recipients
142
+ * @returns {Promise<{ key: Uint8Array, encExtra: { recipients: Array } }>}
137
143
  * @throws {CasError} INVALID_OPTIONS if recipients is empty, non-array, or has duplicate labels.
138
144
  */
139
145
  async resolveRecipients(recipients) {
140
146
  if (!Array.isArray(recipients) || recipients.length === 0) {
141
- throw new CasError('At least one recipient is required', 'INVALID_OPTIONS');
147
+ throw new CasError('At least one recipient is required', ErrorCodes.INVALID_OPTIONS);
142
148
  }
143
149
  const labels = recipients.map((r) => r.label);
144
150
  if (new Set(labels).size !== labels.length) {
145
- throw new CasError('Duplicate recipient labels are not allowed', 'INVALID_OPTIONS');
151
+ throw new CasError('Duplicate recipient labels are not allowed', ErrorCodes.INVALID_OPTIONS);
146
152
  }
147
153
  const dek = this.#crypto.randomBytes(32);
148
154
  const entries = [];
@@ -155,9 +161,9 @@ export default class KeyResolver {
155
161
 
156
162
  /**
157
163
  * If manifest uses envelope encryption, unwraps the DEK. Otherwise returns key directly.
158
- * @param {import('../value-objects/Manifest.js').default} manifest
159
- * @param {Buffer} key
160
- * @returns {Promise<Buffer>}
164
+ * @param {Manifest} manifest
165
+ * @param {Uint8Array} key
166
+ * @returns {Promise<Uint8Array>}
161
167
  * @throws {CasError} NO_MATCHING_RECIPIENT if no recipient entry can be unwrapped.
162
168
  */
163
169
  async resolveKeyForRecipients(manifest, key) {
@@ -166,33 +172,38 @@ export default class KeyResolver {
166
172
  return key;
167
173
  }
168
174
 
175
+ // Iterate all recipients to avoid leaking which index matched via timing.
176
+ let result = null;
169
177
  for (const entry of recipients) {
170
178
  try {
171
- return await this.unwrapDek(entry, key);
179
+ const dek = await this.unwrapDek(entry, key);
180
+ if (!result) { result = dek; }
172
181
  } catch (err) {
173
- if (!(err instanceof CasError && err.code === 'DEK_UNWRAP_FAILED')) { throw err; }
174
- // Not this recipient's KEK, try next
182
+ if (!(err instanceof CasError && err.code === ErrorCodes.DEK_UNWRAP_FAILED)) { throw err; }
175
183
  }
176
184
  }
177
185
 
178
- throw new CasError(
179
- 'No recipient entry could be unwrapped with the provided key',
180
- 'NO_MATCHING_RECIPIENT',
181
- );
186
+ if (!result) {
187
+ throw new CasError(
188
+ 'No recipient entry could be unwrapped with the provided key',
189
+ ErrorCodes.NO_MATCHING_RECIPIENT,
190
+ );
191
+ }
192
+ return result;
182
193
  }
183
194
 
184
195
  /**
185
196
  * Resolves passphrase to a key for decryption.
186
- * @param {import('../value-objects/Manifest.js').default} manifest
197
+ * @param {Manifest} manifest
187
198
  * @param {string} passphrase
188
- * @returns {Promise<Buffer>}
199
+ * @returns {Promise<Uint8Array>}
189
200
  * @throws {CasError} MISSING_KEY if manifest has no KDF params.
190
201
  */
191
202
  async #resolvePassphraseForDecryption(manifest, passphrase) {
192
203
  if (!manifest.encryption?.kdf) {
193
204
  throw new CasError(
194
205
  'Manifest was not stored with passphrase-based encryption; provide encryptionKey instead',
195
- 'MISSING_KEY',
206
+ ErrorCodes.MISSING_KEY,
196
207
  );
197
208
  }
198
209
  return this.#resolveKeyFromPassphrase(passphrase, manifest.encryption.kdf);
@@ -202,18 +213,14 @@ export default class KeyResolver {
202
213
  * Derives a key from a passphrase using stored KDF params.
203
214
  * @param {string} passphrase
204
215
  * @param {Object} kdf - KDF params from manifest.encryption.kdf.
205
- * @returns {Promise<Buffer>}
216
+ * @returns {Promise<Uint8Array>}
206
217
  */
207
218
  async #resolveKeyFromPassphrase(passphrase, kdf) {
219
+ const params = prepareStoredKdfOptions(kdf, { source: 'manifest' });
208
220
  const { key } = await this.#crypto.deriveKey({
209
221
  passphrase,
210
- salt: Buffer.from(kdf.salt, 'base64'),
211
- algorithm: kdf.algorithm,
212
- iterations: kdf.iterations,
213
- cost: kdf.cost,
214
- blockSize: kdf.blockSize,
215
- parallelization: kdf.parallelization,
216
- keyLength: kdf.keyLength,
222
+ salt: decodeBase64(kdf.salt),
223
+ ...params,
217
224
  });
218
225
  return key;
219
226
  }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * @fileoverview Manifest diffing — pure domain function.
3
+ *
4
+ * Compares two manifests by chunk digest to find added, removed, and
5
+ * unchanged chunks. No I/O, no ports, no state — just set algebra.
6
+ */
7
+
8
+ /** @typedef {import('../value-objects/Manifest.js').default} Manifest */
9
+
10
+ /**
11
+ * @typedef {Object} ManifestDiffResult
12
+ * @property {import('../value-objects/Chunk.js').default[]} added - Chunks in `newManifest` not in `oldManifest`.
13
+ * @property {import('../value-objects/Chunk.js').default[]} removed - Chunks in `oldManifest` not in `newManifest`.
14
+ * @property {import('../value-objects/Chunk.js').default[]} unchanged - Chunks in both (by digest), from `newManifest`.
15
+ * @property {{ addedCount: number, removedCount: number, unchangedCount: number, addedBytes: number, removedBytes: number, unchangedBytes: number }} summary
16
+ */
17
+
18
+ /**
19
+ * Compares two manifests by chunk digest.
20
+ *
21
+ * @param {Manifest} oldManifest
22
+ * @param {Manifest} newManifest
23
+ * @returns {ManifestDiffResult}
24
+ */
25
+ export default function diffManifests(oldManifest, newManifest) {
26
+ const oldDigests = new Set(oldManifest.chunks.map((c) => c.digest));
27
+ const newDigests = new Set(newManifest.chunks.map((c) => c.digest));
28
+
29
+ const added = [];
30
+ const unchanged = [];
31
+ for (const chunk of newManifest.chunks) {
32
+ if (oldDigests.has(chunk.digest)) {
33
+ unchanged.push(chunk);
34
+ } else {
35
+ added.push(chunk);
36
+ }
37
+ }
38
+
39
+ const removed = oldManifest.chunks.filter((c) => !newDigests.has(c.digest));
40
+
41
+ const sum = (arr) => arr.reduce((acc, c) => acc + c.size, 0);
42
+
43
+ return {
44
+ added,
45
+ removed,
46
+ unchanged,
47
+ summary: {
48
+ addedCount: added.length,
49
+ removedCount: removed.length,
50
+ unchangedCount: unchanged.length,
51
+ addedBytes: sum(added),
52
+ removedBytes: sum(removed),
53
+ unchangedBytes: sum(unchanged),
54
+ },
55
+ };
56
+ }