@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,230 @@
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 {AsyncIterable<Uint8Array>} source
42
+ * @param {{ chunks: Array, size: number }} manifestData
43
+ * @param {{ convergentKey?: Uint8Array }} [options]
44
+ */
45
+ async chunkAndStore(source, manifestData, { convergentKey } = {}) {
46
+ const pipeline = new StorePipeline({
47
+ chunker: this.#chunker,
48
+ concurrency: this.#concurrency,
49
+ observability: this.#observability,
50
+ storeChunk: (buf, index, key) => this.storeChunk(buf, index, key),
51
+ });
52
+ await pipeline.chunkAndStore(source, manifestData, { convergentKey });
53
+ }
54
+
55
+ /**
56
+ * @param {Uint8Array} buf
57
+ * @param {number} index
58
+ * @param {Uint8Array} [convergentKey]
59
+ * @returns {Promise<{ index: number, size: number, digest: string, blob: string }>}
60
+ */
61
+ async storeChunk(buf, index, convergentKey) {
62
+ const digest = await this.#hashBytes(buf);
63
+ const blobData = convergentKey
64
+ ? await this.#convergent.encryptChunk(buf, convergentKey, digest)
65
+ : buf;
66
+ const blob = await this.#persistence.writeBlob(blobData);
67
+ this.#observability.metric('chunk', { action: 'stored', index, size: buf.length, digest, blob });
68
+ return { index, size: buf.length, digest, blob };
69
+ }
70
+
71
+ /**
72
+ * @param {{ index: number, size: number, digest: string, blob: string }} chunk
73
+ * @param {{ maxBytes?: number, convergentKey?: Uint8Array }} [options]
74
+ * @returns {Promise<Uint8Array>}
75
+ */
76
+ async readAndVerifyChunk(chunk, { maxBytes, convergentKey } = {}) {
77
+ const rawBlob = await this.readChunkBlob(chunk.blob, { maxBytes });
78
+
79
+ if (convergentKey) {
80
+ return this.#convergent.decryptAndVerifyChunk({
81
+ blob: rawBlob,
82
+ masterKey: convergentKey,
83
+ expectedDigest: chunk.digest,
84
+ chunkIndex: chunk.index,
85
+ });
86
+ }
87
+
88
+ const digest = await this.#hashBytes(rawBlob);
89
+ if (digest !== chunk.digest) {
90
+ const err = createCasError(
91
+ `Chunk ${chunk.index} integrity check failed`,
92
+ ErrorCodes.INTEGRITY_ERROR,
93
+ { chunkIndex: chunk.index, expected: chunk.digest, actual: digest },
94
+ );
95
+ this.#observability.metric('error', { code: err.code, message: err.message });
96
+ throw err;
97
+ }
98
+ return rawBlob;
99
+ }
100
+
101
+ /**
102
+ * @param {string} oid
103
+ * @param {{ maxBytes?: number }} [options]
104
+ * @returns {Promise<Uint8Array>}
105
+ */
106
+ async readChunkBlob(oid, { maxBytes } = {}) {
107
+ const blobOid = Oid.from(oid).toString();
108
+ if (!this.supportsReadBlobStream()) {
109
+ if (maxBytes !== undefined) {
110
+ throw createCasError(
111
+ 'Buffered restore safety requires persistence.readBlobStream() so ' +
112
+ 'encrypted/compressed restore can enforce maxRestoreBufferSize with ' +
113
+ 'memory-safe chunk reads. Implement readBlobStream() on the adapter ' +
114
+ 'or use a GitPersistenceAdapter-backed facade. See docs/EXTENDING.md#persistence-adapter-requirements.',
115
+ ErrorCodes.PERSISTENCE_CAPABILITY_REQUIRED,
116
+ {
117
+ capability: 'readBlobStream',
118
+ mode: 'buffered-restore',
119
+ oid: blobOid,
120
+ docs: 'docs/EXTENDING.md#persistence-adapter-requirements',
121
+ },
122
+ );
123
+ }
124
+ return normalizeByteChunk(await this.#persistence.readBlob(blobOid));
125
+ }
126
+
127
+ let total = 0;
128
+ const chunks = [];
129
+ for await (const chunk of await this.#persistence.readBlobStream(blobOid)) {
130
+ const buf = normalizeByteChunk(chunk);
131
+ total += buf.length;
132
+ this.assertBufferedReadLimit({ size: total, limit: maxBytes, oid: blobOid });
133
+ chunks.push(buf);
134
+ }
135
+ return concatBytes(chunks);
136
+ }
137
+
138
+ /**
139
+ * @returns {boolean}
140
+ */
141
+ supportsReadBlobStream() {
142
+ return typeof this.#persistence.readBlobStream === 'function'
143
+ && this.#persistence.readBlobStream !== GitPersistencePort.prototype.readBlobStream;
144
+ }
145
+
146
+ /**
147
+ * @param {Array<{ index: number, size: number, digest: string, blob: string }>} chunks
148
+ * @param {{ totalLimit?: number }} [options]
149
+ * @returns {Promise<Uint8Array[]>}
150
+ */
151
+ async readAndVerifyChunks(chunks, { totalLimit } = {}) {
152
+ const buffers = [];
153
+ let totalRead = 0;
154
+ for (const chunk of chunks) {
155
+ const blob = await this.readAndVerifyChunk(chunk, {
156
+ maxBytes: this.bufferedChunkReadLimit({ totalLimit, totalRead, chunkSize: chunk.size }),
157
+ });
158
+ totalRead += blob.length;
159
+ buffers.push(blob);
160
+ this.#observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
161
+ }
162
+ return buffers;
163
+ }
164
+
165
+ /**
166
+ * @param {{ size: number, limit?: number, oid: string }} options
167
+ */
168
+ assertBufferedReadLimit({ size, limit, oid }) {
169
+ if (limit === undefined || size <= limit) {
170
+ return;
171
+ }
172
+ throw createCasError(
173
+ `Buffered restore read ${size} bytes from blob ${oid} (limit: ${limit})`,
174
+ ErrorCodes.RESTORE_TOO_LARGE,
175
+ { size, limit, oid, reason: 'chunk-blob-size' },
176
+ );
177
+ }
178
+
179
+ /**
180
+ * @param {{ totalLimit?: number, totalRead: number, chunkSize: number }} options
181
+ * @returns {number|undefined}
182
+ */
183
+ bufferedChunkReadLimit({ totalLimit, totalRead, chunkSize }) {
184
+ if (totalLimit === undefined) {
185
+ return chunkSize;
186
+ }
187
+ return Math.min(chunkSize, totalLimit - totalRead);
188
+ }
189
+
190
+ /**
191
+ * @param {Manifest} manifest
192
+ * @returns {AsyncIterable<Uint8Array>}
193
+ */
194
+ async *iterVerifiedChunkBlobs(manifest) {
195
+ const fetchFn = async (chunk) => {
196
+ const blob = await this.readAndVerifyChunk(chunk);
197
+ this.#observability.metric('chunk', { action: 'restored', index: chunk.index, size: blob.length, digest: chunk.digest });
198
+ return blob;
199
+ };
200
+
201
+ if (this.#concurrency > 1) {
202
+ yield* prefetchChunks(manifest.chunks, fetchFn, this.#concurrency);
203
+ return;
204
+ }
205
+ for (const chunk of manifest.chunks) {
206
+ yield await fetchFn(chunk);
207
+ }
208
+ }
209
+
210
+ /**
211
+ * @param {Manifest} manifest
212
+ * @param {Uint8Array} key
213
+ * @returns {AsyncIterable<Uint8Array>}
214
+ */
215
+ async *iterConvergentChunks(manifest, key) {
216
+ const fetchFn = async (chunk) => {
217
+ const plaintext = await this.readAndVerifyChunk(chunk, { convergentKey: key });
218
+ this.#observability.metric('chunk', { action: 'restored', index: chunk.index, size: plaintext.length, digest: chunk.digest });
219
+ return plaintext;
220
+ };
221
+
222
+ if (this.#concurrency > 1) {
223
+ yield* prefetchChunks(manifest.chunks, fetchFn, this.#concurrency);
224
+ return;
225
+ }
226
+ for (const chunk of manifest.chunks) {
227
+ yield await fetchFn(chunk);
228
+ }
229
+ }
230
+ }
@@ -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
+ }