@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,680 @@
1
+ #!/usr/bin/env node
2
+ /* eslint-disable no-console */
3
+ /**
4
+ * @fileoverview Migration script for git-cas v6.0.0 encryption scheme upgrade.
5
+ *
6
+ * Upgrades vault entries from legacy encryption scheme identifiers (v1/v2)
7
+ * to the simplified current scheme names. Two modes:
8
+ *
9
+ * - **Fast** (rename-only): v2 schemes and `convergent-v1` — scheme field is
10
+ * renamed in-place. No re-encryption needed.
11
+ * - **Full** (re-encrypt): v1 whole/framed — data must be decrypted without
12
+ * AAD and re-stored with AAD under the current scheme.
13
+ *
14
+ * Usage:
15
+ * node scripts/migrate-encryption.js [options]
16
+ * --cwd <dir> Git working directory (default: .)
17
+ * --execute Actually perform migration (default: dry-run)
18
+ * --passphrase-file <path> Passphrase file for v1 re-encryption (- for stdin)
19
+ * --passphrase <p> Inline passphrase for v1 re-encryption; warns
20
+ * --key-file <path> Raw 32-byte key file for re-encryption of v1 schemes
21
+ *
22
+ * @module
23
+ */
24
+
25
+ import { parseArgs } from 'node:util';
26
+ import { resolve } from 'node:path';
27
+ import { readFileSync } from 'node:fs';
28
+ import ContentAddressableStore from '../index.js';
29
+ import { createGitPlumbing } from '../src/infrastructure/createGitPlumbing.js';
30
+ import CasService from '../src/domain/services/CasService.js';
31
+ import {
32
+ isLegacyScheme, mapToCurrentScheme, isLegacyNoAad,
33
+ CURRENT_SCHEMES,
34
+ } from '../src/domain/encryption/schemes.js';
35
+
36
+ // ---------------------------------------------------------------------------
37
+ // CLI argument parsing
38
+ // ---------------------------------------------------------------------------
39
+
40
+ const ARGS_CONFIG = {
41
+ options: {
42
+ cwd: { type: 'string', default: '.' },
43
+ execute: { type: 'boolean', default: false },
44
+ passphrase: { type: 'string' },
45
+ 'passphrase-file': { type: 'string' },
46
+ 'key-file': { type: 'string' },
47
+ 'vault-passphrase': { type: 'string' },
48
+ 'vault-passphrase-file': { type: 'string' },
49
+ 'vault-key-file': { type: 'string' },
50
+ help: { type: 'boolean', default: false },
51
+ },
52
+ };
53
+
54
+ function printUsage() {
55
+ console.log('Usage: node scripts/migrate-encryption.js [options]');
56
+ console.log(' --cwd <dir> Git working directory (default: .)');
57
+ console.log(' --execute Perform migration (default: dry-run)');
58
+ console.log(' --passphrase-file <path> Read v1 re-encryption passphrase from file (- for stdin)');
59
+ console.log(' --passphrase <p> Inline v1 passphrase; warns, prefer --passphrase-file - or --key-file');
60
+ console.log(' --key-file <path> Raw 32-byte key file for v1 re-encryption');
61
+ console.log(' --vault-passphrase-file <path> Read privacy-vault passphrase from file (- for stdin)');
62
+ console.log(' --vault-passphrase <p> Inline privacy-vault passphrase; warns, prefer --vault-passphrase-file - or --vault-key-file');
63
+ console.log(' --vault-key-file <path> Raw 32-byte privacy-vault key file');
64
+ console.log(' --help Show this help');
65
+ }
66
+
67
+ /**
68
+ * Converts parseArgs hyphenated option names into the internal option shape.
69
+ * @param {Record<string, any>} values
70
+ * @returns {Record<string, any>}
71
+ */
72
+ function normalizeCliOptions(values) {
73
+ return {
74
+ cwd: values.cwd,
75
+ execute: values.execute,
76
+ passphrase: values.passphrase,
77
+ passphraseFile: values['passphrase-file'],
78
+ keyFile: values['key-file'],
79
+ vaultPassphrase: values['vault-passphrase'],
80
+ vaultPassphraseFile: values['vault-passphrase-file'],
81
+ vaultKeyFile: values['vault-key-file'],
82
+ help: values.help,
83
+ };
84
+ }
85
+
86
+ /**
87
+ * Creates warnings for inline secret sources that can leak through shell
88
+ * history and process listings.
89
+ * @param {{ passphrase?: string, vaultPassphrase?: string }} opts
90
+ * @returns {string[]}
91
+ */
92
+ function inlinePassphraseWarnings(opts) {
93
+ const warnings = [];
94
+ if (opts.passphrase) {
95
+ warnings.push(
96
+ 'warning: --passphrase exposes secrets through shell history and process listings; ' +
97
+ 'prefer --passphrase-file - or --key-file',
98
+ );
99
+ }
100
+ if (opts.vaultPassphrase) {
101
+ warnings.push(
102
+ 'warning: --vault-passphrase exposes secrets through shell history and process listings; ' +
103
+ 'prefer --vault-passphrase-file - or --vault-key-file',
104
+ );
105
+ }
106
+ return warnings;
107
+ }
108
+
109
+ /**
110
+ * Emits warnings for inline passphrase arguments.
111
+ * @param {{ passphrase?: string, vaultPassphrase?: string }} opts
112
+ * @param {(message: string) => void} write
113
+ */
114
+ function warnInlinePassphraseArgs(opts, write = process.stderr.write.bind(process.stderr)) {
115
+ for (const warning of inlinePassphraseWarnings(opts)) {
116
+ write(`${warning}\n`);
117
+ }
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Entry classification
122
+ // ---------------------------------------------------------------------------
123
+
124
+ /**
125
+ * Classifies a vault entry for migration.
126
+ * @param {Object} raw - Raw decoded manifest from readManifestRaw.
127
+ * @returns {{ mode: 'skip'|'fast'|'full', scheme: string|undefined, reason: string }}
128
+ */
129
+ function classifyEntry(raw) {
130
+ if (!raw.encryption) {
131
+ return { mode: 'skip', scheme: undefined, reason: 'unencrypted' };
132
+ }
133
+
134
+ const scheme = raw.encryption.scheme;
135
+
136
+ if (!scheme) {
137
+ return { mode: 'full', scheme, reason: 'schemeless legacy — re-encrypt' };
138
+ }
139
+ if (CURRENT_SCHEMES.has(scheme)) {
140
+ return { mode: 'skip', scheme, reason: 'already current' };
141
+ }
142
+ if (!isLegacyScheme(scheme)) {
143
+ return { mode: 'skip', scheme, reason: 'unknown scheme' };
144
+ }
145
+ if (scheme === 'convergent-v1') {
146
+ return { mode: 'fast', scheme, reason: 'convergent — rename only' };
147
+ }
148
+ if (isLegacyNoAad(scheme)) {
149
+ return { mode: 'full', scheme, reason: 'v1 (no AAD) — re-encrypt' };
150
+ }
151
+ return { mode: 'fast', scheme, reason: 'v2 — rename only' };
152
+ }
153
+
154
+ // ---------------------------------------------------------------------------
155
+ // Fast migration (rename scheme in manifest blob, rebuild tree)
156
+ // ---------------------------------------------------------------------------
157
+
158
+ /**
159
+ * Performs fast migration: renames the scheme in the manifest blob and
160
+ * rebuilds the tree with only the manifest entry replaced.
161
+ *
162
+ * This preserves the entire tree structure (sub-manifests, chunk entries)
163
+ * and only replaces the manifest blob, avoiding round-tripping through
164
+ * createTree() which would flatten Merkle manifests.
165
+ *
166
+ * @param {Object} ctx
167
+ * @param {CasService} ctx.service - CasService matching the entry's codec.
168
+ * @param {CasService} ctx.rawService - Legacy-mode CasService for hash verification.
169
+ * @param {string} ctx.treeOid - Original tree OID for hash verification context.
170
+ * @param {Object} ctx.raw - Raw manifest data.
171
+ * @param {Object} ctx.persistence - GitPersistenceAdapter instance.
172
+ * @param {{ encode: Function }} ctx.codec - Codec matching the entry's format.
173
+ * @returns {Promise<string>} New tree OID.
174
+ */
175
+ async function migrateFast({ service, rawService, raw, treeOid, persistence, codec }) {
176
+ await rawService._verifyManifestHash(raw, treeOid);
177
+
178
+ const currentScheme = mapToCurrentScheme(raw.encryption.scheme);
179
+ raw.encryption.scheme = currentScheme;
180
+
181
+ if (!raw.formatVersion) {
182
+ raw.formatVersion = service.formatVersion;
183
+ }
184
+
185
+ // Recompute manifest hash with the updated scheme
186
+ const hashable = { ...raw };
187
+ delete hashable.manifestHash;
188
+ for (const key of Object.keys(hashable)) {
189
+ if (hashable[key] === undefined) { delete hashable[key]; }
190
+ }
191
+ raw.manifestHash = await service.crypto.sha256(Buffer.from(codec.encode(hashable)));
192
+
193
+ // Encode the updated manifest and write as a new blob
194
+ const newManifestBlob = codec.encode(raw);
195
+ const newManifestOid = await persistence.writeBlob(newManifestBlob);
196
+
197
+ // Rebuild tree with only the manifest entry replaced
198
+ const entries = await persistence.readTree(treeOid);
199
+ const manifestEntry = entries.find((e) => e.name.startsWith('manifest.'));
200
+ const newEntries = entries.map((e) =>
201
+ e.name === manifestEntry.name
202
+ ? `${e.mode} ${e.type} ${newManifestOid}\t${e.name}`
203
+ : `${e.mode} ${e.type} ${e.oid}\t${e.name}`,
204
+ );
205
+ return await persistence.writeTree(newEntries);
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // Full migration (restore via legacy service, re-store via current)
210
+ // ---------------------------------------------------------------------------
211
+
212
+ /**
213
+ * Performs full migration: decrypt with legacy, re-encrypt with current.
214
+ * @param {Object} ctx
215
+ * @param {CasService} ctx.legacyService - Legacy-mode CasService.
216
+ * @param {CasService} ctx.service - CasService matching the entry's codec.
217
+ * @param {string} ctx.treeOid - Original tree OID.
218
+ * @param {Object} ctx.keyOpts - { passphrase } or { encryptionKey }.
219
+ * @param {Object} ctx.deps - Shared dependency bag for building services.
220
+ * @param {{ encode: Function, extension: string }} ctx.codec - Codec matching the entry's format.
221
+ * @returns {Promise<string>} New tree OID.
222
+ */
223
+ async function migrateFull({ legacyService, service, treeOid, keyOpts, deps, codec }) {
224
+ const manifest = await legacyService.readManifest({ treeOid });
225
+ if (manifest.encryption?.recipients?.length > 0) {
226
+ throw new Error(
227
+ 'Full migration for recipient-encrypted legacy manifests is not automatic. ' +
228
+ 'Re-store the asset with current recipients so recipient access is preserved.',
229
+ );
230
+ }
231
+ const source = legacyService.restoreStream({ manifest, ...keyOpts });
232
+
233
+ // If the manifest has non-default chunking, build a writer service with
234
+ // the matching chunker so re-stored data preserves chunk boundaries.
235
+ let writerService = service;
236
+ if (manifest.chunking) {
237
+ const { default: resolveChunker } = await import(
238
+ '../src/infrastructure/chunkers/resolveChunker.js'
239
+ );
240
+ const chunker = resolveChunker({
241
+ chunking: {
242
+ strategy: manifest.chunking.strategy,
243
+ ...manifest.chunking.params,
244
+ },
245
+ });
246
+ if (chunker) {
247
+ writerService = new CasService({ ...deps, codec, chunker });
248
+ }
249
+ }
250
+
251
+ const storeOpts = {
252
+ source,
253
+ slug: manifest.slug,
254
+ filename: manifest.filename,
255
+ ...keyOpts,
256
+ encryption: { scheme: manifest.encryption.scheme },
257
+ };
258
+
259
+ if (manifest.compression) {
260
+ storeOpts.compression = manifest.compression;
261
+ }
262
+
263
+ const newManifest = await writerService.store(storeOpts);
264
+
265
+ return await writerService.createTree({ manifest: newManifest });
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // Migration orchestrator
270
+ // ---------------------------------------------------------------------------
271
+
272
+ /**
273
+ * Runs migration for a single vault entry.
274
+ * @param {Object} ctx - Migration context with codec-keyed services.
275
+ * @param {{ slug: string, treeOid: string }} entry - Vault entry to migrate.
276
+ * @param {{ execute: boolean, passphrase?: string }} opts - Migration options.
277
+ * @returns {Promise<Object>} Result record.
278
+ */
279
+ async function migrateEntry(ctx, entry, opts) {
280
+ const codecExt = await detectCodec(ctx.persistence, entry.treeOid);
281
+ const rawService = ctx.rawServices[codecExt];
282
+ const raw = await rawService.readManifestRaw({ treeOid: entry.treeOid });
283
+ const classification = classifyEntry(raw);
284
+
285
+ const result = {
286
+ slug: entry.slug,
287
+ ...classification,
288
+ treeOid: entry.treeOid,
289
+ newTreeOid: null,
290
+ };
291
+
292
+ if (classification.mode === 'skip' || !opts.execute) {
293
+ return result;
294
+ }
295
+
296
+ if (classification.mode === 'fast') {
297
+ result.newTreeOid = await migrateFast({
298
+ service: ctx.services[codecExt],
299
+ rawService,
300
+ raw,
301
+ treeOid: entry.treeOid,
302
+ persistence: ctx.persistence,
303
+ codec: ctx.codecs[codecExt],
304
+ });
305
+ }
306
+
307
+ if (classification.mode === 'full') {
308
+ const keyOpts = buildKeyOpts(opts, classification);
309
+ result.newTreeOid = await migrateFull({
310
+ legacyService: ctx.legacyServices[codecExt],
311
+ service: ctx.services[codecExt],
312
+ treeOid: entry.treeOid,
313
+ keyOpts,
314
+ deps: ctx.deps,
315
+ codec: ctx.codecs[codecExt],
316
+ });
317
+ }
318
+
319
+ await updateVaultForMigration({ ctx, entry, result, opts });
320
+
321
+ return result;
322
+ }
323
+
324
+ /**
325
+ * @param {Object} args
326
+ * @param {Object} args.ctx
327
+ * @param {{ slug: string }} args.entry
328
+ * @param {{ newTreeOid: string|null }} args.result
329
+ * @param {{ vaultEncryptionKey?: Uint8Array }} args.opts
330
+ */
331
+ async function updateVaultForMigration({ ctx, entry, result, opts }) {
332
+ if (!result.newTreeOid) { return; }
333
+ await ctx.vault.addToVault({
334
+ slug: entry.slug,
335
+ treeOid: result.newTreeOid,
336
+ force: true,
337
+ encryptionKey: opts.vaultEncryptionKey,
338
+ });
339
+ }
340
+
341
+ /**
342
+ * Reads a 32-byte raw key file.
343
+ * @param {string} keyFilePath
344
+ * @returns {Uint8Array}
345
+ */
346
+ function readKeyFile(keyFilePath) {
347
+ const key = readFileSync(keyFilePath);
348
+ if (key.length !== 32) {
349
+ throw new Error(`Invalid key length: expected 32 bytes, got ${key.length} (${keyFilePath})`);
350
+ }
351
+ return key;
352
+ }
353
+
354
+ /**
355
+ * Reads a passphrase file and strips one trailing line ending.
356
+ * @param {string} filePath
357
+ * @returns {string}
358
+ */
359
+ function readPassphraseFile(filePath) {
360
+ const label = filePath === '-' ? 'stdin' : filePath;
361
+ const passphrase = readFileSync(filePath === '-' ? 0 : filePath, 'utf8').replace(/\r?\n$/u, '');
362
+ if (!passphrase.trim()) {
363
+ throw new Error(`Passphrase file is empty: ${label}`);
364
+ }
365
+ return passphrase;
366
+ }
367
+
368
+ /**
369
+ * Builds key options for full-mode migration.
370
+ * @param {{
371
+ * passphrase?: string,
372
+ * passphraseFile?: string,
373
+ * keyFile?: string,
374
+ * encryptionKey?: Uint8Array
375
+ * }} opts - CLI options containing key material.
376
+ * @param {{ scheme: string|undefined, mode: string, reason: string }} classification - Entry classification.
377
+ * @returns {{ passphrase: string }|{ encryptionKey: Uint8Array }} Key options for re-encryption.
378
+ */
379
+ function buildKeyOpts(opts, classification) {
380
+ const sourceCount = [
381
+ opts.passphrase,
382
+ opts.passphraseFile,
383
+ opts.keyFile,
384
+ opts.encryptionKey,
385
+ ].filter((value) => value !== undefined && value !== null && value !== '').length;
386
+
387
+ if (sourceCount > 1) {
388
+ throw new Error(
389
+ 'Provide exactly one full-migration credential source: ' +
390
+ '--passphrase, --passphrase-file, --key-file, or injected encryptionKey.',
391
+ );
392
+ }
393
+ if (opts.encryptionKey) {
394
+ return { encryptionKey: opts.encryptionKey };
395
+ }
396
+ if (opts.keyFile) {
397
+ return { encryptionKey: readKeyFile(opts.keyFile) };
398
+ }
399
+ if (opts.passphraseFile) {
400
+ return { passphrase: readPassphraseFile(opts.passphraseFile) };
401
+ }
402
+ if (!opts.passphrase) {
403
+ throw new Error(
404
+ `Entry requires re-encryption (${classification.scheme}) ` +
405
+ 'but no --passphrase, --passphrase-file, or --key-file was provided.',
406
+ );
407
+ }
408
+ return { passphrase: opts.passphrase };
409
+ }
410
+
411
+ // ---------------------------------------------------------------------------
412
+ // Service construction
413
+ // ---------------------------------------------------------------------------
414
+
415
+ /**
416
+ * Detects the codec type from a tree OID by inspecting manifest entry names.
417
+ * @param {Object} persistence - GitPersistenceAdapter instance.
418
+ * @param {string} treeOid - Git tree OID to inspect.
419
+ * @returns {Promise<'json'|'cbor'>} Detected codec extension.
420
+ */
421
+ async function detectCodec(persistence, treeOid) {
422
+ const entries = await persistence.readTree(treeOid);
423
+ const manifestEntry = entries.find((e) => e.name.startsWith('manifest.'));
424
+ if (!manifestEntry) { return 'json'; }
425
+ return manifestEntry.name.endsWith('.cbor') ? 'cbor' : 'json';
426
+ }
427
+
428
+ /**
429
+ * Creates services with proper legacy mode support.
430
+ * @param {Object} plumbing - Git plumbing instance.
431
+ * @returns {Promise<Object>} Migration context with codec-keyed legacy services.
432
+ */
433
+ async function createMigrationContext(plumbing) {
434
+ const cas = new ContentAddressableStore({ plumbing });
435
+ await cas.getService();
436
+ const vault = await cas.getVaultService();
437
+
438
+ const { default: JsonCodec } = await import(
439
+ '../src/infrastructure/codecs/JsonCodec.js'
440
+ );
441
+ const { default: CborCodec } = await import(
442
+ '../src/infrastructure/codecs/CborCodec.js'
443
+ );
444
+ const deps = await buildLegacyDeps(plumbing);
445
+
446
+ const codecs = {
447
+ json: new JsonCodec(),
448
+ cbor: new CborCodec(),
449
+ };
450
+
451
+ const services = {};
452
+ const legacyServices = {};
453
+ const rawServices = {};
454
+ for (const [ext, codec] of Object.entries(codecs)) {
455
+ services[ext] = new CasService({ ...deps, codec });
456
+ legacyServices[ext] = new CasService({
457
+ ...deps,
458
+ codec,
459
+ legacyMode: true,
460
+ });
461
+ rawServices[ext] = new CasService({
462
+ ...deps,
463
+ codec,
464
+ legacyMode: true,
465
+ });
466
+ }
467
+
468
+ return { cas, services, legacyServices, rawServices, codecs, deps, vault, persistence: deps.persistence };
469
+ }
470
+
471
+ /**
472
+ * Builds shared dependencies for legacy CasService instances.
473
+ * @param {Object} plumbing - Git plumbing instance.
474
+ * @returns {Promise<Object>} Shared dependency bag for CasService construction.
475
+ */
476
+ async function buildLegacyDeps(plumbing) {
477
+ const { default: GitPersistenceAdapter } = await import(
478
+ '../src/infrastructure/adapters/GitPersistenceAdapter.js'
479
+ );
480
+ const { default: createCryptoAdapter } = await import(
481
+ '../src/infrastructure/adapters/createCryptoAdapter.js'
482
+ );
483
+ const { default: SilentObserver } = await import(
484
+ '../src/infrastructure/adapters/SilentObserver.js'
485
+ );
486
+ const { default: FixedChunker } = await import(
487
+ '../src/infrastructure/chunkers/FixedChunker.js'
488
+ );
489
+ const { default: NodeCompressionAdapter } = await import(
490
+ '../src/infrastructure/adapters/NodeCompressionAdapter.js'
491
+ );
492
+ const { createRequire } = await import('node:module');
493
+ const require = createRequire(import.meta.url);
494
+ const { version } = require('../package.json');
495
+
496
+ return {
497
+ persistence: new GitPersistenceAdapter({ plumbing }),
498
+ crypto: await createCryptoAdapter(),
499
+ observability: new SilentObserver(),
500
+ chunker: new FixedChunker({ chunkSize: 256 * 1024 }),
501
+ compressionAdapter: new NodeCompressionAdapter(),
502
+ chunkSize: 256 * 1024,
503
+ formatVersion: version,
504
+ };
505
+ }
506
+
507
+ /**
508
+ * Derives the vault encryption key from vault metadata and passphrase.
509
+ * @param {ContentAddressableStore} cas
510
+ * @param {Object} metadata
511
+ * @param {string} passphrase
512
+ * @returns {Promise<Uint8Array>}
513
+ */
514
+ async function deriveVaultKey(cas, metadata, passphrase) {
515
+ const kdf = metadata.encryption?.kdf;
516
+ if (!kdf) {
517
+ throw new Error('Privacy vault metadata is missing KDF configuration.');
518
+ }
519
+ const { key } = await cas.deriveKey({
520
+ passphrase,
521
+ salt: Buffer.from(kdf.salt, 'base64'),
522
+ algorithm: kdf.algorithm,
523
+ iterations: kdf.iterations,
524
+ cost: kdf.cost,
525
+ blockSize: kdf.blockSize,
526
+ parallelization: kdf.parallelization,
527
+ keyLength: kdf.keyLength,
528
+ });
529
+ return key;
530
+ }
531
+
532
+ /**
533
+ * Resolves the key needed to enumerate/update privacy-enabled vaults.
534
+ * @param {Object} ctx - Migration context.
535
+ * @param {Record<string, any>} opts - Normalized migration options.
536
+ * @returns {Promise<Uint8Array|undefined>}
537
+ */
538
+ async function resolveVaultEncryptionKey(ctx, opts) {
539
+ const metadata = await ctx.vault.getVaultMetadata();
540
+ if (!metadata?.privacy?.enabled) {
541
+ return undefined;
542
+ }
543
+ if (opts.vaultKeyFile) {
544
+ return readKeyFile(opts.vaultKeyFile);
545
+ }
546
+
547
+ const passphrase = opts.vaultPassphraseFile
548
+ ? readPassphraseFile(opts.vaultPassphraseFile)
549
+ : opts.vaultPassphrase || resolveContentPassphraseFallback(opts);
550
+
551
+ if (!passphrase) {
552
+ throw new Error(
553
+ 'Privacy mode is enabled. Provide --vault-passphrase, ' +
554
+ '--vault-passphrase-file, --vault-key-file, --passphrase-file, or --passphrase if the ' +
555
+ 'content and vault passphrases are the same.',
556
+ );
557
+ }
558
+
559
+ return await deriveVaultKey(ctx.cas, metadata, passphrase);
560
+ }
561
+
562
+ /**
563
+ * Resolves the content passphrase as a fallback for vault migration when the
564
+ * same passphrase protects both content and the privacy vault.
565
+ * @param {{ passphrase?: string, passphraseFile?: string }} opts
566
+ * @returns {string|undefined}
567
+ */
568
+ function resolveContentPassphraseFallback(opts) {
569
+ const sourceCount = [opts.passphrase, opts.passphraseFile]
570
+ .filter((value) => value !== undefined && value !== null && value !== '').length;
571
+ if (sourceCount > 1) {
572
+ throw new Error(
573
+ 'Provide exactly one content passphrase fallback for privacy migration: ' +
574
+ '--passphrase or --passphrase-file.',
575
+ );
576
+ }
577
+ if (opts.passphraseFile) {
578
+ return readPassphraseFile(opts.passphraseFile);
579
+ }
580
+ return opts.passphrase;
581
+ }
582
+
583
+ // ---------------------------------------------------------------------------
584
+ // Reporting
585
+ // ---------------------------------------------------------------------------
586
+
587
+ /**
588
+ * Prints a migration report to stdout.
589
+ * @param {Object[]} results
590
+ * @param {boolean} execute
591
+ */
592
+ function printReport(results, execute) {
593
+ const prefix = execute ? 'MIGRATED' : 'DRY-RUN';
594
+ const counts = { skip: 0, fast: 0, full: 0 };
595
+
596
+ console.log('');
597
+ console.log(`${'Slug'.padEnd(40)} ${'Mode'.padEnd(6)} Scheme → Current Notes`);
598
+ console.log('-'.repeat(90));
599
+
600
+ for (const r of results) {
601
+ const mapped = mapToCurrentScheme(r.scheme) || r.scheme || '(none)';
602
+ const arrow = r.scheme ? `${r.scheme} → ${mapped}` : '(none)';
603
+ const note = r.newTreeOid ? `tree:${r.newTreeOid.slice(0, 8)}` : r.reason;
604
+ console.log(`${r.slug.padEnd(40)} ${r.mode.padEnd(6)} ${arrow.padEnd(24)} ${note}`);
605
+ counts[r.mode]++;
606
+ }
607
+
608
+ console.log('');
609
+ console.log(`[${prefix}] ${results.length} entries scanned:`);
610
+ console.log(` ${counts.skip} skipped, ${counts.fast} fast, ${counts.full} full`);
611
+ }
612
+
613
+ // ---------------------------------------------------------------------------
614
+ // Main
615
+ // ---------------------------------------------------------------------------
616
+
617
+ async function listVaultEntries(vault, { encryptionKey } = {}) {
618
+ return await vault.listVault({ encryptionKey });
619
+ }
620
+
621
+ async function main() {
622
+ const { values } = parseArgs(ARGS_CONFIG);
623
+ const opts = normalizeCliOptions(values);
624
+ warnInlinePassphraseArgs(opts);
625
+
626
+ if (opts.help) {
627
+ printUsage();
628
+ return;
629
+ }
630
+
631
+ const cwd = resolve(opts.cwd);
632
+ console.log(`git-cas upgrade — ${opts.execute ? 'EXECUTE' : 'DRY-RUN'} mode`);
633
+ console.log(`Working directory: ${cwd}`);
634
+
635
+ const plumbing = createGitPlumbing({ cwd });
636
+ const ctx = await createMigrationContext(plumbing);
637
+ opts.vaultEncryptionKey = await resolveVaultEncryptionKey(ctx, opts);
638
+
639
+ const entries = await listVaultEntries(ctx.vault, { encryptionKey: opts.vaultEncryptionKey });
640
+
641
+ if (entries.length === 0) {
642
+ const metadata = await ctx.vault.getVaultMetadata();
643
+ console.log(metadata === null
644
+ ? 'No vault found — nothing to migrate.'
645
+ : 'Vault is empty — nothing to migrate.');
646
+ return;
647
+ }
648
+
649
+ console.log(`Found ${entries.length} vault entries.`);
650
+
651
+ const results = [];
652
+ for (const entry of entries) {
653
+ const result = await migrateEntry(ctx, entry, opts);
654
+ results.push(result);
655
+ }
656
+
657
+ printReport(results, opts.execute);
658
+ }
659
+
660
+ export {
661
+ classifyEntry,
662
+ migrateFast,
663
+ migrateFull,
664
+ migrateEntry,
665
+ buildKeyOpts,
666
+ createMigrationContext,
667
+ detectCodec,
668
+ inlinePassphraseWarnings,
669
+ listVaultEntries,
670
+ normalizeCliOptions,
671
+ resolveVaultEncryptionKey,
672
+ warnInlinePassphraseArgs,
673
+ };
674
+
675
+ if (process.argv[1]?.endsWith('migrate-encryption.js')) {
676
+ main().catch((err) => {
677
+ console.error('Migration failed:', err.message);
678
+ process.exitCode = 1;
679
+ });
680
+ }