@git-stunts/git-cas 5.3.2 → 6.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/ADVANCED_GUIDE.md +1027 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +449 -5
  4. package/CODE_OF_CONDUCT.md +33 -0
  5. package/GUIDE.md +926 -0
  6. package/README.md +106 -366
  7. package/SECURITY.md +993 -0
  8. package/SUPPORT.md +54 -0
  9. package/UPGRADING.md +299 -0
  10. package/bin/actions.js +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +1255 -212
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +367 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2254 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +273 -80
  60. package/index.js +220 -59
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +153 -53
  103. package/src/domain/services/CasService.js +322 -837
  104. package/src/domain/services/ChunkRepository.js +268 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +180 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +10 -6
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
@@ -0,0 +1,268 @@
1
+ import createCasError from '../errors/createCasError.js';
2
+ import GitPersistencePort from '../../ports/GitPersistencePort.js';
3
+ import StorePipeline from './StorePipeline.js';
4
+ import prefetchChunks from './PrefetchWindow.js';
5
+ import { concatBytes, normalizeByteChunk } from '../bytes/ByteLayout.js';
6
+ import Oid from '../value-objects/Oid.js';
7
+ import { ErrorCodes } from '../errors/index.js';
8
+
9
+ /** @typedef {import('../value-objects/Manifest.js').default} Manifest */
10
+
11
+ /**
12
+ * Domain chunk I/O and digest verification boundary.
13
+ */
14
+ export default class ChunkRepository {
15
+ #chunker;
16
+ #concurrency;
17
+ #convergent;
18
+ #hashBytes;
19
+ #observability;
20
+ #persistence;
21
+
22
+ /**
23
+ * @param {Object} options
24
+ * @param {import('../../ports/ChunkingPort.js').default} options.chunker
25
+ * @param {number} options.concurrency
26
+ * @param {import('./ConvergentEncryption.js').default} options.convergent
27
+ * @param {(buf: Uint8Array) => Promise<string>} options.hashBytes
28
+ * @param {import('../../ports/ObservabilityPort.js').default} options.observability
29
+ * @param {import('../../ports/GitPersistencePort.js').default} options.persistence
30
+ */
31
+ constructor({ chunker, concurrency, convergent, hashBytes, observability, persistence }) {
32
+ this.#chunker = chunker;
33
+ this.#concurrency = concurrency;
34
+ this.#convergent = convergent;
35
+ this.#hashBytes = hashBytes;
36
+ this.#observability = observability;
37
+ this.#persistence = persistence;
38
+ }
39
+
40
+ /**
41
+ * @param {import('../../ports/ChunkingPort.js').default} chunker
42
+ * @returns {ChunkRepository}
43
+ */
44
+ withChunker(chunker) {
45
+ return new ChunkRepository({
46
+ chunker,
47
+ concurrency: this.#concurrency,
48
+ convergent: this.#convergent,
49
+ hashBytes: this.#hashBytes,
50
+ observability: this.#observability,
51
+ persistence: this.#persistence,
52
+ });
53
+ }
54
+
55
+ /**
56
+ * @param {AsyncIterable<Uint8Array>} source
57
+ * @param {{ chunks: Array, size: number }} manifestData
58
+ * @param {{ convergentKey?: Uint8Array }} [options]
59
+ */
60
+ async chunkAndStore(source, manifestData, { convergentKey } = {}) {
61
+ const pipeline = new StorePipeline({
62
+ chunker: this.#chunker,
63
+ concurrency: this.#concurrency,
64
+ observability: this.#observability,
65
+ storeChunk: (buf, index, key) => this.storeChunk(buf, index, key),
66
+ });
67
+ await pipeline.chunkAndStore(source, manifestData, { convergentKey });
68
+ }
69
+
70
+ /**
71
+ * @param {Uint8Array} buf
72
+ * @param {number} index
73
+ * @param {Uint8Array} [convergentKey]
74
+ * @returns {Promise<{ index: number, size: number, digest: string, blob: string }>}
75
+ */
76
+ async storeChunk(buf, index, convergentKey) {
77
+ const digest = await this.#hashBytes(buf);
78
+ const blobData = convergentKey
79
+ ? await this.#convergent.encryptChunk(buf, convergentKey, digest)
80
+ : buf;
81
+ const blob = await this.#persistence.writeBlob(blobData);
82
+ this.#observability.metric('chunk', {
83
+ action: 'stored',
84
+ index,
85
+ size: buf.length,
86
+ digest,
87
+ blob,
88
+ });
89
+ return { index, size: buf.length, digest, blob };
90
+ }
91
+
92
+ /**
93
+ * @param {{ index: number, size: number, digest: string, blob: string }} chunk
94
+ * @param {{ maxBytes?: number, convergentKey?: Uint8Array }} [options]
95
+ * @returns {Promise<Uint8Array>}
96
+ */
97
+ async readAndVerifyChunk(chunk, { maxBytes, convergentKey } = {}) {
98
+ const rawBlob = await this.readChunkBlob(chunk.blob, { maxBytes });
99
+
100
+ if (convergentKey) {
101
+ return this.#convergent.decryptAndVerifyChunk({
102
+ blob: rawBlob,
103
+ masterKey: convergentKey,
104
+ expectedDigest: chunk.digest,
105
+ chunkIndex: chunk.index,
106
+ });
107
+ }
108
+
109
+ const digest = await this.#hashBytes(rawBlob);
110
+ if (digest !== chunk.digest) {
111
+ const err = createCasError(
112
+ `Chunk ${chunk.index} integrity check failed`,
113
+ ErrorCodes.INTEGRITY_ERROR,
114
+ { chunkIndex: chunk.index, expected: chunk.digest, actual: digest }
115
+ );
116
+ this.#observability.metric('error', { code: err.code, message: err.message });
117
+ throw err;
118
+ }
119
+ return rawBlob;
120
+ }
121
+
122
+ /**
123
+ * @param {string} oid
124
+ * @param {{ maxBytes?: number }} [options]
125
+ * @returns {Promise<Uint8Array>}
126
+ */
127
+ async readChunkBlob(oid, { maxBytes } = {}) {
128
+ const blobOid = Oid.from(oid).toString();
129
+ if (!this.supportsReadBlobStream()) {
130
+ if (maxBytes !== undefined) {
131
+ throw createCasError(
132
+ 'Buffered restore safety requires persistence.readBlobStream() so ' +
133
+ 'encrypted/compressed restore can enforce maxRestoreBufferSize with ' +
134
+ 'memory-safe chunk reads. Implement readBlobStream() on the adapter ' +
135
+ 'or use a GitPersistenceAdapter-backed facade. See docs/EXTENDING.md#persistence-adapter-requirements.',
136
+ ErrorCodes.PERSISTENCE_CAPABILITY_REQUIRED,
137
+ {
138
+ capability: 'readBlobStream',
139
+ mode: 'buffered-restore',
140
+ oid: blobOid,
141
+ docs: 'docs/EXTENDING.md#persistence-adapter-requirements',
142
+ }
143
+ );
144
+ }
145
+ return normalizeByteChunk(await this.#persistence.readBlob(blobOid));
146
+ }
147
+
148
+ let total = 0;
149
+ const chunks = [];
150
+ for await (const chunk of await this.#persistence.readBlobStream(blobOid)) {
151
+ const buf = normalizeByteChunk(chunk);
152
+ total += buf.length;
153
+ this.assertBufferedReadLimit({ size: total, limit: maxBytes, oid: blobOid });
154
+ chunks.push(buf);
155
+ }
156
+ return concatBytes(chunks);
157
+ }
158
+
159
+ /**
160
+ * @returns {boolean}
161
+ */
162
+ supportsReadBlobStream() {
163
+ return (
164
+ typeof this.#persistence.readBlobStream === 'function' &&
165
+ this.#persistence.readBlobStream !== GitPersistencePort.prototype.readBlobStream
166
+ );
167
+ }
168
+
169
+ /**
170
+ * @param {Array<{ index: number, size: number, digest: string, blob: string }>} chunks
171
+ * @param {{ totalLimit?: number }} [options]
172
+ * @returns {Promise<Uint8Array[]>}
173
+ */
174
+ async readAndVerifyChunks(chunks, { totalLimit } = {}) {
175
+ const buffers = [];
176
+ let totalRead = 0;
177
+ for (const chunk of chunks) {
178
+ const blob = await this.readAndVerifyChunk(chunk, {
179
+ maxBytes: this.bufferedChunkReadLimit({ totalLimit, totalRead, chunkSize: chunk.size }),
180
+ });
181
+ totalRead += blob.length;
182
+ buffers.push(blob);
183
+ this.#observability.metric('chunk', {
184
+ action: 'restored',
185
+ index: chunk.index,
186
+ size: blob.length,
187
+ digest: chunk.digest,
188
+ });
189
+ }
190
+ return buffers;
191
+ }
192
+
193
+ /**
194
+ * @param {{ size: number, limit?: number, oid: string }} options
195
+ */
196
+ assertBufferedReadLimit({ size, limit, oid }) {
197
+ if (limit === undefined || size <= limit) {
198
+ return;
199
+ }
200
+ throw createCasError(
201
+ `Buffered restore read ${size} bytes from blob ${oid} (limit: ${limit})`,
202
+ ErrorCodes.RESTORE_TOO_LARGE,
203
+ { size, limit, oid, reason: 'chunk-blob-size' }
204
+ );
205
+ }
206
+
207
+ /**
208
+ * @param {{ totalLimit?: number, totalRead: number, chunkSize: number }} options
209
+ * @returns {number|undefined}
210
+ */
211
+ bufferedChunkReadLimit({ totalLimit, totalRead, chunkSize }) {
212
+ if (totalLimit === undefined) {
213
+ return chunkSize;
214
+ }
215
+ return Math.min(chunkSize, totalLimit - totalRead);
216
+ }
217
+
218
+ /**
219
+ * @param {Manifest} manifest
220
+ * @returns {AsyncIterable<Uint8Array>}
221
+ */
222
+ async *iterVerifiedChunkBlobs(manifest) {
223
+ const fetchFn = async (chunk) => {
224
+ const blob = await this.readAndVerifyChunk(chunk);
225
+ this.#observability.metric('chunk', {
226
+ action: 'restored',
227
+ index: chunk.index,
228
+ size: blob.length,
229
+ digest: chunk.digest,
230
+ });
231
+ return blob;
232
+ };
233
+
234
+ if (this.#concurrency > 1) {
235
+ yield* prefetchChunks(manifest.chunks, fetchFn, this.#concurrency);
236
+ return;
237
+ }
238
+ for (const chunk of manifest.chunks) {
239
+ yield await fetchFn(chunk);
240
+ }
241
+ }
242
+
243
+ /**
244
+ * @param {Manifest} manifest
245
+ * @param {Uint8Array} key
246
+ * @returns {AsyncIterable<Uint8Array>}
247
+ */
248
+ async *iterConvergentChunks(manifest, key) {
249
+ const fetchFn = async (chunk) => {
250
+ const plaintext = await this.readAndVerifyChunk(chunk, { convergentKey: key });
251
+ this.#observability.metric('chunk', {
252
+ action: 'restored',
253
+ index: chunk.index,
254
+ size: plaintext.length,
255
+ digest: chunk.digest,
256
+ });
257
+ return plaintext;
258
+ };
259
+
260
+ if (this.#concurrency > 1) {
261
+ yield* prefetchChunks(manifest.chunks, fetchFn, this.#concurrency);
262
+ return;
263
+ }
264
+ for (const chunk of manifest.chunks) {
265
+ yield await fetchFn(chunk);
266
+ }
267
+ }
268
+ }
@@ -0,0 +1,72 @@
1
+ import CasError from '../errors/CasError.js';
2
+ import createCasError from '../errors/createCasError.js';
3
+ import { concatBytes } from '../bytes/ByteLayout.js';
4
+ import { ErrorCodes } from '../errors/index.js';
5
+
6
+ /**
7
+ * Domain compression stream boundary.
8
+ */
9
+ export default class CompressionStreams {
10
+ #adapter;
11
+
12
+ /**
13
+ * @param {import('../../ports/CompressionPort.js').default} adapter
14
+ */
15
+ constructor(adapter) {
16
+ this.#adapter = adapter;
17
+ }
18
+
19
+ /**
20
+ * @param {AsyncIterable<Uint8Array>} source
21
+ * @returns {AsyncIterable<Uint8Array>}
22
+ */
23
+ async *compress(source) {
24
+ yield* this.#adapter.compressStream(source);
25
+ }
26
+
27
+ /**
28
+ * @param {AsyncIterable<Uint8Array>} source
29
+ * @returns {AsyncIterable<Uint8Array>}
30
+ */
31
+ async *decompress(source) {
32
+ try {
33
+ for await (const chunk of this.#adapter.decompressStream(source)) {
34
+ yield chunk;
35
+ }
36
+ } catch (err) {
37
+ if (err instanceof CasError) {
38
+ throw err;
39
+ }
40
+ const message = err instanceof Error ? err.message : String(err);
41
+ throw createCasError(`Decompression failed: ${message}`, ErrorCodes.INTEGRITY_ERROR, { originalError: err });
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {Uint8Array} buffer
47
+ * @param {number} limit
48
+ * @returns {Promise<Uint8Array>}
49
+ */
50
+ async decompressBufferedWithLimit(buffer, limit) {
51
+ const chunks = [];
52
+ let total = 0;
53
+
54
+ async function* source() {
55
+ yield buffer;
56
+ }
57
+
58
+ for await (const chunk of this.decompress(source())) {
59
+ total += chunk.length;
60
+ if (total > limit) {
61
+ throw createCasError(
62
+ `Decompressed restore is ${total} bytes (limit: ${limit})`,
63
+ ErrorCodes.RESTORE_TOO_LARGE,
64
+ { size: total, limit },
65
+ );
66
+ }
67
+ chunks.push(chunk);
68
+ }
69
+
70
+ return concatBytes(chunks);
71
+ }
72
+ }
@@ -0,0 +1,128 @@
1
+ import { ErrorCodes } from '../errors/index.js';
2
+ /**
3
+ * @fileoverview Convergent encryption service.
4
+ *
5
+ * Encapsulates per-chunk deterministic encryption where the key and nonce are
6
+ * derived from the plaintext content hash. Identical plaintext chunks produce
7
+ * identical ciphertext, preserving deduplication even with encryption enabled.
8
+ *
9
+ * Receives a CryptoPort via constructor injection — no platform dependencies.
10
+ */
11
+ import CasError from '../errors/CasError.js';
12
+ import { concatBytes } from '../bytes/ByteLayout.js';
13
+ import { utf8Encode } from '../encoding/utf8.js';
14
+
15
+ const GCM_TAG_BYTES = 16;
16
+
17
+ /**
18
+ * Per-chunk convergent encryption and decryption.
19
+ *
20
+ * Key derivation:
21
+ * chunkKey = HMAC-SHA256(masterKey, "git-cas-convergent-key:<digest>")[0..31]
22
+ * chunkNonce = HMAC-SHA256(masterKey, "git-cas-convergent-nonce:<digest>")[0..11]
23
+ *
24
+ * Blob format: ciphertext || 16-byte GCM auth tag
25
+ */
26
+ export default class ConvergentEncryption {
27
+ /** @type {import('../../ports/CryptoPort.js').default} */
28
+ #crypto;
29
+
30
+ /**
31
+ * @param {import('../../ports/CryptoPort.js').default} crypto - CryptoPort adapter.
32
+ */
33
+ constructor(crypto) {
34
+ this.#crypto = crypto;
35
+ }
36
+
37
+ /**
38
+ * Derives the per-chunk AES-256 key from the master key and chunk digest.
39
+ * @param {Uint8Array} masterKey
40
+ * @param {string} digest - 64-char hex SHA-256 of the plaintext chunk.
41
+ * @returns {Promise<Uint8Array>} 32-byte derived key.
42
+ */
43
+ async deriveChunkKey(masterKey, digest) {
44
+ const digestBytes = await Promise.resolve(
45
+ this.#crypto.hmacSha256(masterKey, utf8Encode(`git-cas-convergent-key:${digest}`)),
46
+ );
47
+ return digestBytes.subarray(0, 32);
48
+ }
49
+
50
+ /**
51
+ * Derives the per-chunk 12-byte nonce from the master key and chunk digest.
52
+ * @param {Uint8Array} masterKey
53
+ * @param {string} digest - 64-char hex SHA-256 of the plaintext chunk.
54
+ * @returns {Promise<Uint8Array>} 12-byte derived nonce.
55
+ */
56
+ async deriveChunkNonce(masterKey, digest) {
57
+ const digestBytes = await Promise.resolve(
58
+ this.#crypto.hmacSha256(masterKey, utf8Encode(`git-cas-convergent-nonce:${digest}`)),
59
+ );
60
+ return digestBytes.subarray(0, 12);
61
+ }
62
+
63
+ /**
64
+ * Encrypts a plaintext chunk for convergent storage.
65
+ *
66
+ * @param {Uint8Array} plaintext - Chunk data.
67
+ * @param {Uint8Array} masterKey - Convergent master key.
68
+ * @param {string} digest - SHA-256 hex digest of plaintext.
69
+ * @returns {Promise<Uint8Array>} Blob data: ciphertext || 16-byte GCM tag.
70
+ */
71
+ async encryptChunk(plaintext, masterKey, digest) {
72
+ const key = await this.deriveChunkKey(masterKey, digest);
73
+ const nonce = await this.deriveChunkNonce(masterKey, digest);
74
+ const { buf, tag } = await Promise.resolve(
75
+ this.#crypto.encryptBufferWithNonce(plaintext, key, nonce),
76
+ );
77
+ return concatBytes([buf, tag]);
78
+ }
79
+
80
+ /**
81
+ * Decrypts a convergent-encrypted chunk and verifies its plaintext digest.
82
+ *
83
+ * @param {Object} options
84
+ * @param {Uint8Array} options.blob - Encrypted blob (ciphertext || 16-byte tag).
85
+ * @param {Uint8Array} options.masterKey - Convergent master key.
86
+ * @param {string} options.expectedDigest - Expected SHA-256 hex digest of plaintext.
87
+ * @param {number} options.chunkIndex - Chunk index (for error context).
88
+ * @returns {Promise<Uint8Array>} Verified plaintext.
89
+ * @throws {CasError} INTEGRITY_ERROR on decryption failure or digest mismatch.
90
+ */
91
+ async decryptAndVerifyChunk({ blob, masterKey, expectedDigest, chunkIndex }) {
92
+ if (blob.length < GCM_TAG_BYTES) {
93
+ throw new CasError(
94
+ `Convergent blob too short (${blob.length} bytes) — must contain at least ${GCM_TAG_BYTES}-byte GCM tag`,
95
+ ErrorCodes.INTEGRITY_ERROR,
96
+ { chunkIndex, blobLength: blob.length, minLength: GCM_TAG_BYTES },
97
+ );
98
+ }
99
+ const ciphertext = blob.subarray(0, -GCM_TAG_BYTES);
100
+ const tag = blob.subarray(-GCM_TAG_BYTES);
101
+ const key = await this.deriveChunkKey(masterKey, expectedDigest);
102
+ const nonce = await this.deriveChunkNonce(masterKey, expectedDigest);
103
+
104
+ let plaintext;
105
+ try {
106
+ plaintext = await Promise.resolve(
107
+ this.#crypto.decryptBufferWithNonceTag(ciphertext, key, nonce, tag),
108
+ );
109
+ } catch (err) {
110
+ if (err instanceof CasError) { throw err; }
111
+ throw new CasError(
112
+ `Chunk ${chunkIndex} convergent decryption failed`,
113
+ ErrorCodes.INTEGRITY_ERROR,
114
+ { chunkIndex, expected: expectedDigest, originalError: err },
115
+ );
116
+ }
117
+
118
+ const digest = await this.#crypto.sha256(plaintext);
119
+ if (digest !== expectedDigest) {
120
+ throw new CasError(
121
+ `Chunk ${chunkIndex} integrity check failed after convergent decryption`,
122
+ ErrorCodes.INTEGRITY_ERROR,
123
+ { chunkIndex, expected: expectedDigest, actual: digest },
124
+ );
125
+ }
126
+ return plaintext;
127
+ }
128
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * @fileoverview Git tree-entry formatting helpers for CAS manifest publication.
3
+ */
4
+
5
+ const BLOB_FILE_MODE = '100644';
6
+ const BLOB_TYPE = 'blob';
7
+
8
+ /**
9
+ * Format one Git tree entry for a blob.
10
+ *
11
+ * @param {{ oid: string, name: string }} options
12
+ * @returns {string}
13
+ */
14
+ export function formatBlobTreeEntry({ oid, name }) {
15
+ return `${BLOB_FILE_MODE} ${BLOB_TYPE} ${oid}\t${name}`;
16
+ }
17
+
18
+ /**
19
+ * Build the manifest blob entry.
20
+ *
21
+ * @param {{ oid: string, extension: string }} options
22
+ * @returns {string}
23
+ */
24
+ export function buildManifestTreeEntry({ oid, extension }) {
25
+ return formatBlobTreeEntry({ oid, name: `manifest.${extension}` });
26
+ }
27
+
28
+ /**
29
+ * Build one entry per unique chunk digest, preserving first-seen order.
30
+ *
31
+ * @param {Array<{ digest: string, blob: string }>} chunks
32
+ * @returns {string[]}
33
+ */
34
+ export function buildChunkTreeEntries(chunks) {
35
+ const treeEntries = [];
36
+ const seenDigests = new Set();
37
+
38
+ for (const chunk of chunks) {
39
+ if (seenDigests.has(chunk.digest)) {
40
+ continue;
41
+ }
42
+ seenDigests.add(chunk.digest);
43
+ treeEntries.push(formatBlobTreeEntry({ oid: chunk.blob, name: chunk.digest }));
44
+ }
45
+
46
+ return treeEntries;
47
+ }
48
+
49
+ /**
50
+ * Build entries for sub-manifest blobs.
51
+ *
52
+ * @param {{ subManifests: Array<{ oid: string }>, extension: string }} options
53
+ * @returns {string[]}
54
+ */
55
+ export function buildSubManifestTreeEntries({ subManifests, extension }) {
56
+ return subManifests.map((ref, index) =>
57
+ formatBlobTreeEntry({ oid: ref.oid, name: `sub-manifest-${index}.${extension}` })
58
+ );
59
+ }
60
+
61
+ /**
62
+ * Build a flat manifest tree layout.
63
+ *
64
+ * @param {{ manifestOid: string, chunks: Array<{ digest: string, blob: string }>, extension: string }} options
65
+ * @returns {string[]}
66
+ */
67
+ export function buildFlatManifestTreeEntries({ manifestOid, chunks, extension }) {
68
+ return [
69
+ buildManifestTreeEntry({ oid: manifestOid, extension }),
70
+ ...buildChunkTreeEntries(chunks),
71
+ ];
72
+ }
73
+
74
+ /**
75
+ * Build a Merkle manifest tree layout.
76
+ *
77
+ * @param {{ rootManifestOid: string, subManifests: Array<{ oid: string }>, chunks: Array<{ digest: string, blob: string }>, extension: string }} options
78
+ * @returns {string[]}
79
+ */
80
+ export function buildMerkleTreeEntries({ rootManifestOid, subManifests, chunks, extension }) {
81
+ return [
82
+ buildManifestTreeEntry({ oid: rootManifestOid, extension }),
83
+ ...buildSubManifestTreeEntries({ subManifests, extension }),
84
+ ...buildChunkTreeEntries(chunks),
85
+ ];
86
+ }