@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
package/bin/git-cas.js CHANGED
@@ -1,53 +1,75 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { readFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
4
6
  import { program, Option } from 'commander';
5
- import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
6
7
  import ContentAddressableStore, { EventEmitterObserver, CborCodec } from '../index.js';
7
8
  import Manifest from '../src/domain/value-objects/Manifest.js';
9
+ import Slug from '../src/domain/value-objects/Slug.js';
10
+ import { createGitPlumbing } from '../src/infrastructure/createGitPlumbing.js';
8
11
  import { createStoreProgress, createRestoreProgress } from './ui/progress.js';
9
12
  import { renderEncryptionCard } from './ui/encryption-card.js';
10
13
  import { renderHistoryTimeline } from './ui/history-timeline.js';
11
14
  import { renderManifestView } from './ui/manifest-view.js';
12
15
  import { renderHeatmap } from './ui/heatmap.js';
16
+ import { surfaceToString } from '@flyingrobots/bijou';
17
+ import {
18
+ buildVaultStats,
19
+ inspectVaultHealth,
20
+ renderVaultStats,
21
+ } from './ui/vault-report.js';
22
+ import { renderHealthDashboard } from './ui/blocks/health-dashboard.js';
23
+ import { getCliContext } from './ui/context.js';
13
24
  import { runAction } from './actions.js';
25
+ import { runAgentCli } from './agent/cli.js';
26
+ import { flushStdioAndExit, installBrokenPipeHandlers } from './io.js';
14
27
  import { filterEntries, formatTable, formatTabSeparated } from './ui/vault-list.js';
15
- import { readPassphraseFile, promptPassphrase } from './ui/passphrase-prompt.js';
28
+ import { readPassphraseFile } from './ui/passphrase-prompt.js';
29
+ import {
30
+ hasExplicitPassphraseSource,
31
+ resolvePassphrase,
32
+ warnInlinePassphraseArgs,
33
+ } from './passphrase-source.js';
34
+ import {
35
+ readKeyFile,
36
+ resolveCliEncryptionKey as resolveEncryptionKey,
37
+ validateCliCredentialSources as validateCredentialSources,
38
+ } from './credentials.js';
16
39
  import { loadConfig, mergeConfig } from './config.js';
40
+ import { resolveRestoreOutputTarget } from './restore-output-target.js';
41
+
42
+ import { resolveVersionString } from './build-version.js';
43
+
44
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
45
+ const CLI_VERSION = resolveVersionString(
46
+ JSON.parse(readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')).version,
47
+ );
17
48
 
18
49
  const getJson = () => program.opts().json;
50
+ installBrokenPipeHandlers();
51
+
52
+ if (process.argv[2] === 'agent') {
53
+ await runAgentCli(process.argv.slice(3));
54
+ await flushStdioAndExit();
55
+ }
19
56
 
20
57
  program
21
58
  .name('git-cas')
22
59
  .description('Content Addressable Storage backed by Git')
23
- .version('5.2.2')
60
+ .version(CLI_VERSION)
24
61
  .option('-q, --quiet', 'Suppress progress output')
25
62
  .option('--json', 'Output results as JSON');
26
63
 
27
- /**
28
- * Read a 32-byte raw encryption key from a file.
29
- *
30
- * @param {string} keyFilePath
31
- * @returns {Buffer}
32
- */
33
- function readKeyFile(keyFilePath) {
34
- const buf = readFileSync(keyFilePath);
35
- if (buf.length !== 32) {
36
- throw new Error(`Invalid key length: expected 32 bytes, got ${buf.length} (${keyFilePath})`);
37
- }
38
- return buf;
39
- }
40
-
41
64
  /**
42
65
  * Create a CAS instance for the given working directory.
43
66
  *
44
67
  * @param {string} cwd
45
68
  * @param {Record<string, any>} [opts]
46
- * @returns {ContentAddressableStore}
69
+ * @returns {Promise<ContentAddressableStore>}
47
70
  */
48
- function createCas(cwd, opts = {}) {
49
- const runner = ShellRunnerFactory.create();
50
- const plumbing = new GitPlumbing({ runner, cwd });
71
+ async function createCas(cwd, opts = {}) {
72
+ const plumbing = await createGitPlumbing({ cwd });
51
73
  /** @type {Record<string, any>} */
52
74
  const casOpts = { plumbing, ...opts };
53
75
  if (casOpts.codec === 'cbor') {
@@ -56,96 +78,6 @@ function createCas(cwd, opts = {}) {
56
78
  return new ContentAddressableStore(casOpts);
57
79
  }
58
80
 
59
- /**
60
- * Derive the encryption key from vault metadata + passphrase.
61
- *
62
- * @param {ContentAddressableStore} cas
63
- * @param {import('../index.js').VaultMetadata} metadata
64
- * @param {string} passphrase
65
- * @returns {Promise<Buffer>}
66
- */
67
- async function deriveVaultKey(cas, metadata, passphrase) {
68
- if (!metadata.encryption?.kdf) {
69
- throw new Error('Missing or malformed encryption metadata');
70
- }
71
- const { kdf } = metadata.encryption;
72
- const { key } = await cas.deriveKey({
73
- passphrase,
74
- salt: Buffer.from(kdf.salt, 'base64'),
75
- algorithm: /** @type {"pbkdf2" | "scrypt"} */ (kdf.algorithm),
76
- iterations: kdf.iterations,
77
- cost: kdf.cost,
78
- blockSize: kdf.blockSize,
79
- parallelization: kdf.parallelization,
80
- });
81
- return key;
82
- }
83
-
84
- /**
85
- * Returns true when a non-interactive passphrase source exists (flag or env).
86
- * Does NOT trigger prompts or consume stdin.
87
- *
88
- * @param {Record<string, any>} opts
89
- * @returns {boolean}
90
- */
91
- function hasPassphraseSource(opts) {
92
- return Boolean(opts.vaultPassphraseFile || opts.vaultPassphrase || process.env.GIT_CAS_PASSPHRASE);
93
- }
94
-
95
- /**
96
- * Resolve passphrase from (in priority order):
97
- * 1. --vault-passphrase-file <path>
98
- * 2. --vault-passphrase <pass>
99
- * 3. GIT_CAS_PASSPHRASE env var
100
- * 4. Interactive TTY prompt (if stdin is a TTY)
101
- *
102
- * @param {Record<string, any>} opts
103
- * @param {{ confirm?: boolean }} [extra]
104
- * @returns {Promise<string | undefined>}
105
- */
106
- async function resolvePassphrase(opts, extra = {}) {
107
- if (opts.vaultPassphraseFile) {
108
- return await readPassphraseFile(opts.vaultPassphraseFile);
109
- }
110
- if (opts.vaultPassphrase) {
111
- if (!opts.vaultPassphrase.trim()) { throw new Error('Passphrase must not be empty'); }
112
- return opts.vaultPassphrase;
113
- }
114
- if (process.env.GIT_CAS_PASSPHRASE) {
115
- if (!process.env.GIT_CAS_PASSPHRASE.trim()) { throw new Error('Passphrase must not be empty'); }
116
- return process.env.GIT_CAS_PASSPHRASE;
117
- }
118
- if (process.stdin.isTTY) {
119
- return await promptPassphrase({ confirm: extra.confirm || false });
120
- }
121
- return undefined;
122
- }
123
-
124
- /**
125
- * Resolve encryption key from --key-file or --vault-passphrase / GIT_CAS_PASSPHRASE.
126
- *
127
- * @param {ContentAddressableStore} cas
128
- * @param {Record<string, any>} opts
129
- * @returns {Promise<Buffer | undefined>}
130
- */
131
- async function resolveEncryptionKey(cas, opts) {
132
- if (opts.keyFile) {
133
- return readKeyFile(opts.keyFile);
134
- }
135
- const metadata = await cas.getVaultMetadata();
136
- if (!metadata?.encryption) {
137
- if (hasPassphraseSource(opts)) {
138
- process.stderr.write('warning: passphrase ignored (vault is not encrypted)\n');
139
- }
140
- return undefined;
141
- }
142
- const passphrase = await resolvePassphrase(opts);
143
- if (!passphrase) {
144
- return undefined;
145
- }
146
- return deriveVaultKey(cas, metadata, passphrase);
147
- }
148
-
149
81
  /**
150
82
  * Validate --slug / --oid flags (exactly one required).
151
83
  *
@@ -158,6 +90,17 @@ function validateRestoreFlags(opts) {
158
90
  if (!opts.slug && !opts.oid) {
159
91
  throw new Error('Provide --slug <slug> or --oid <tree-oid>');
160
92
  }
93
+ if (opts.slug) {
94
+ Slug.validate(opts.slug);
95
+ }
96
+ }
97
+
98
+ /**
99
+ * @param {string} slug
100
+ * @returns {string}
101
+ */
102
+ function normalizeSlug(slug) {
103
+ return Slug.from(slug).toString();
161
104
  }
162
105
 
163
106
  // ---------------------------------------------------------------------------
@@ -168,8 +111,9 @@ function validateRestoreFlags(opts) {
168
111
  * @typedef {Object} StoreFileOpts
169
112
  * @property {string} filePath - Path to the file to store.
170
113
  * @property {string} slug - Asset slug identifier.
171
- * @property {Buffer} [encryptionKey] - 32-byte AES-256-GCM key.
172
- * @property {Array<{ label: string, key: Buffer }>} [recipients] - Envelope recipients.
114
+ * @property {Uint8Array} [encryptionKey] - 32-byte AES-256-GCM key.
115
+ * @property {Uint8Array} [vaultEncryptionKey] - Vault key derived from a vault passphrase source.
116
+ * @property {Array<{ label: string, key: Uint8Array }>} [recipients] - Envelope recipients.
173
117
  */
174
118
 
175
119
  /**
@@ -182,12 +126,17 @@ function validateRestoreFlags(opts) {
182
126
  */
183
127
  async function buildStoreOpts(cas, file, opts) {
184
128
  /** @type {StoreFileOpts} */
185
- const storeOpts = { filePath: file, slug: opts.slug };
129
+ const storeOpts = { filePath: file, slug: Slug.from(opts.slug).toString() };
186
130
  if (opts.recipient) {
187
131
  storeOpts.recipients = opts.recipient;
188
132
  } else {
189
133
  const encryptionKey = await resolveEncryptionKey(cas, opts);
190
- if (encryptionKey) { storeOpts.encryptionKey = encryptionKey; }
134
+ if (encryptionKey) {
135
+ storeOpts.encryptionKey = encryptionKey;
136
+ if (!opts.keyFile) {
137
+ storeOpts.vaultEncryptionKey = encryptionKey;
138
+ }
139
+ }
191
140
  }
192
141
  return storeOpts;
193
142
  }
@@ -197,8 +146,8 @@ async function buildStoreOpts(cas, file, opts) {
197
146
  * Format: label:keyfile
198
147
  *
199
148
  * @param {string} value
200
- * @param {Array<{ label: string, key: Buffer }>} [previous]
201
- * @returns {Array<{ label: string, key: Buffer }>}
149
+ * @param {Array<{ label: string, key: Uint8Array }>} [previous]
150
+ * @returns {Array<{ label: string, key: Uint8Array }>}
202
151
  */
203
152
  function parseRecipient(value, previous) {
204
153
  const sep = value.indexOf(':');
@@ -218,12 +167,21 @@ function parseRecipient(value, previous) {
218
167
 
219
168
  /** @param {string} v */
220
169
  const parseIntFlag = (v) => {
221
- if (!/^-?\d+$/.test(v)) { throw new Error(`Expected an integer, got "${v}"`); }
170
+ if (!/^-?\d+$/.test(v)) {
171
+ throw new Error(`Expected an integer, got "${v}"`);
172
+ }
222
173
  const n = Number(v);
223
- if (!Number.isSafeInteger(n)) { throw new Error(`Expected a safe integer, got "${v}"`); }
174
+ if (!Number.isSafeInteger(n)) {
175
+ throw new Error(`Expected a safe integer, got "${v}"`);
176
+ }
224
177
  return n;
225
178
  };
226
179
 
180
+ /** @param {boolean} json */
181
+ function shouldSuppressProgress(json) {
182
+ return Boolean(program.opts().quiet || json);
183
+ }
184
+
227
185
  program
228
186
  .command('store <file>')
229
187
  .description('Store a file into Git CAS')
@@ -232,8 +190,19 @@ program
232
190
  .option('--recipient <label:keyfile>', 'Envelope recipient (repeatable)', parseRecipient)
233
191
  .option('--tree', 'Also create a Git tree and print its OID')
234
192
  .option('--force', 'Overwrite existing vault entry')
235
- .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption (prefer GIT_CAS_PASSPHRASE env var)')
193
+ .option(
194
+ '--vault-passphrase <pass>',
195
+ 'Vault-level passphrase for encryption (warns; prefer --vault-passphrase-file -, GIT_CAS_PASSPHRASE, or --os-keychain-target)'
196
+ )
236
197
  .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
198
+ .option(
199
+ '--os-keychain-target <target>',
200
+ 'Read vault passphrase from OS keychain target via @git-stunts/vault'
201
+ )
202
+ .option(
203
+ '--os-keychain-account <account>',
204
+ 'OS keychain account namespace for --os-keychain-target (default: git-cas)'
205
+ )
237
206
  .option('--gzip', 'Enable gzip compression')
238
207
  .addOption(new Option('--strategy <type>', 'Chunking strategy').choices(['fixed', 'cdc']))
239
208
  .option('--chunk-size <n>', 'Chunk size in bytes', parseIntFlag)
@@ -244,37 +213,54 @@ program
244
213
  .option('--max-chunk-size <n>', 'CDC maximum chunk size', parseIntFlag)
245
214
  .option('--merkle-threshold <n>', 'Chunk count threshold for Merkle sub-manifests', parseIntFlag)
246
215
  .option('--cwd <dir>', 'Git working directory', '.')
247
- .action(runAction(async (/** @type {string} */ file, /** @type {Record<string, any>} */ opts) => {
248
- if (opts.recipient && (opts.keyFile || hasPassphraseSource(opts))) {
249
- throw new Error('Provide --key-file or a vault passphrase source (--vault-passphrase, --vault-passphrase-file, GIT_CAS_PASSPHRASE), or --recipient — not both');
250
- }
251
- if (opts.force && !opts.tree) {
252
- throw new Error('--force requires --tree');
253
- }
254
- const json = program.opts().json;
255
- const quiet = program.opts().quiet || json;
256
- const observer = new EventEmitterObserver();
257
-
258
- const config = loadConfig(opts.cwd);
259
- const { casConfig, storeExtras } = mergeConfig(opts, config);
260
- const cas = createCas(opts.cwd, { observability: observer, ...casConfig });
261
-
262
- const storeOpts = await buildStoreOpts(cas, file, opts);
263
- Object.assign(storeOpts, storeExtras);
264
- const progress = createStoreProgress({ filePath: file, chunkSize: cas.chunkSize, quiet });
265
- progress.attach(observer);
266
- let manifest;
267
- try { manifest = await cas.storeFile(storeOpts); } finally { progress.detach(); }
268
-
269
- if (opts.tree) {
270
- const treeOid = await cas.createTree({ manifest });
271
- await cas.addToVault({ slug: opts.slug, treeOid, force: !!opts.force });
272
- process.stdout.write(json ? `${JSON.stringify({ treeOid })}\n` : `${treeOid}\n`);
273
- } else {
274
- const output = json ? JSON.stringify({ manifest: manifest.toJSON() }) : JSON.stringify(manifest.toJSON(), null, 2);
275
- process.stdout.write(`${output}\n`);
276
- }
277
- }, getJson));
216
+ .action(
217
+ runAction(async (/** @type {string} */ file, /** @type {Record<string, any>} */ opts) => {
218
+ warnInlinePassphraseArgs(opts);
219
+ validateCredentialSources(opts);
220
+ if (opts.recipient && (opts.keyFile || hasExplicitPassphraseSource(opts))) {
221
+ throw new Error(
222
+ 'Provide --key-file or a vault passphrase source (--vault-passphrase, --vault-passphrase-file, --os-keychain-target, GIT_CAS_PASSPHRASE), or --recipient — not both'
223
+ );
224
+ }
225
+ if (opts.force && !opts.tree) {
226
+ throw new Error('--force requires --tree');
227
+ }
228
+ const json = program.opts().json;
229
+ const quiet = shouldSuppressProgress(json);
230
+ const observer = new EventEmitterObserver();
231
+
232
+ const config = loadConfig(opts.cwd);
233
+ const { casConfig, storeExtras } = mergeConfig(opts, config);
234
+ const cas = await createCas(opts.cwd, { observability: observer, ...casConfig });
235
+
236
+ const storeOpts = await buildStoreOpts(cas, file, opts);
237
+ Object.assign(storeOpts, storeExtras);
238
+ const progress = createStoreProgress({ filePath: file, chunkSize: cas.chunkSize, quiet });
239
+ progress.attach(observer);
240
+ let manifest;
241
+ try {
242
+ manifest = await cas.storeFile(storeOpts);
243
+ } finally {
244
+ progress.detach();
245
+ }
246
+
247
+ if (opts.tree) {
248
+ const treeOid = await cas.createTree({ manifest });
249
+ await cas.addToVault({
250
+ slug: storeOpts.slug,
251
+ treeOid,
252
+ force: !!opts.force,
253
+ ...(storeOpts.vaultEncryptionKey ? { encryptionKey: storeOpts.vaultEncryptionKey } : {}),
254
+ });
255
+ process.stdout.write(json ? `${JSON.stringify({ treeOid })}\n` : `${treeOid}\n`);
256
+ } else {
257
+ const output = json
258
+ ? JSON.stringify({ manifest: manifest.toJSON() })
259
+ : JSON.stringify(manifest.toJSON(), null, 2);
260
+ process.stdout.write(`${output}\n`);
261
+ }
262
+ }, getJson)
263
+ );
278
264
 
279
265
  // ---------------------------------------------------------------------------
280
266
  // tree
@@ -284,18 +270,20 @@ program
284
270
  .description('Create a Git tree from a manifest')
285
271
  .requiredOption('--manifest <path>', 'Path to manifest JSON file')
286
272
  .option('--cwd <dir>', 'Git working directory', '.')
287
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
288
- const cas = createCas(opts.cwd);
289
- const raw = readFileSync(opts.manifest, 'utf8');
290
- const manifest = new Manifest(JSON.parse(raw));
291
- const treeOid = await cas.createTree({ manifest });
292
- const json = program.opts().json;
293
- if (json) {
294
- process.stdout.write(`${JSON.stringify({ treeOid })}\n`);
295
- } else {
296
- process.stdout.write(`${treeOid}\n`);
297
- }
298
- }, getJson));
273
+ .action(
274
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
275
+ const cas = await createCas(opts.cwd);
276
+ const raw = readFileSync(opts.manifest, 'utf8');
277
+ const manifest = new Manifest(JSON.parse(raw));
278
+ const treeOid = await cas.createTree({ manifest });
279
+ const json = program.opts().json;
280
+ if (json) {
281
+ process.stdout.write(`${JSON.stringify({ treeOid })}\n`);
282
+ } else {
283
+ process.stdout.write(`${treeOid}\n`);
284
+ }
285
+ }, getJson)
286
+ );
299
287
 
300
288
  // ---------------------------------------------------------------------------
301
289
  // inspect
@@ -307,23 +295,25 @@ program
307
295
  .option('--oid <tree-oid>', 'Direct tree OID')
308
296
  .option('--heatmap', 'Show chunk heatmap visualization')
309
297
  .option('--cwd <dir>', 'Git working directory', '.')
310
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
311
- validateRestoreFlags(opts);
312
- const cas = createCas(opts.cwd);
313
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
314
- const manifest = await cas.readManifest({ treeOid });
315
- const json = program.opts().json;
316
-
317
- if (json) {
318
- process.stdout.write(`${JSON.stringify(manifest.toJSON())}\n`);
319
- } else if (opts.heatmap) {
320
- process.stdout.write(renderHeatmap({ manifest }));
321
- } else if (process.stdout.isTTY) {
322
- process.stdout.write(renderManifestView({ manifest }));
323
- } else {
324
- process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
325
- }
326
- }, getJson));
298
+ .action(
299
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
300
+ validateRestoreFlags(opts);
301
+ const cas = await createCas(opts.cwd);
302
+ const treeOid = opts.oid || (await cas.resolveVaultEntry({ slug: opts.slug }));
303
+ const manifest = await cas.readManifest({ treeOid });
304
+ const json = program.opts().json;
305
+
306
+ if (json) {
307
+ process.stdout.write(`${JSON.stringify(manifest.toJSON())}\n`);
308
+ } else if (opts.heatmap) {
309
+ process.stdout.write(renderHeatmap({ manifest: manifest.toJSON() }));
310
+ } else if (process.stdout.isTTY) {
311
+ process.stdout.write(renderManifestView({ manifest: manifest.toJSON() }));
312
+ } else {
313
+ process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
314
+ }
315
+ }, getJson)
316
+ );
327
317
 
328
318
  // ---------------------------------------------------------------------------
329
319
  // restore
@@ -335,51 +325,77 @@ program
335
325
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
336
326
  .option('--oid <tree-oid>', 'Direct tree OID')
337
327
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
338
- .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption (prefer GIT_CAS_PASSPHRASE env var)')
328
+ .option(
329
+ '--vault-passphrase <pass>',
330
+ 'Vault-level passphrase for decryption (warns; prefer --vault-passphrase-file -, GIT_CAS_PASSPHRASE, or --os-keychain-target)'
331
+ )
339
332
  .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
333
+ .option(
334
+ '--os-keychain-target <target>',
335
+ 'Read vault passphrase from OS keychain target via @git-stunts/vault'
336
+ )
337
+ .option(
338
+ '--os-keychain-account <account>',
339
+ 'OS keychain account namespace for --os-keychain-target (default: git-cas)'
340
+ )
340
341
  .option('--concurrency <n>', 'Parallel chunk I/O operations', parseIntFlag)
341
- .option('--max-restore-buffer <n>', 'Max bytes for buffered encrypted/compressed restore', parseIntFlag)
342
+ .option(
343
+ '--max-restore-buffer <n>',
344
+ 'Max bytes for buffered encrypted/compressed restore',
345
+ parseIntFlag
346
+ )
342
347
  .option('--cwd <dir>', 'Git working directory', '.')
343
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
344
- validateRestoreFlags(opts);
345
- const quiet = program.opts().quiet || program.opts().json;
346
- const observer = new EventEmitterObserver();
347
-
348
- const config = loadConfig(opts.cwd);
349
- /** @type {Record<string, any>} */
350
- const casConfig = {};
351
- const concurrency = opts.concurrency ?? config.concurrency;
352
- const maxRestoreBufferSize = opts.maxRestoreBuffer ?? config.maxRestoreBufferSize;
353
- if (concurrency !== undefined) { casConfig.concurrency = concurrency; }
354
- if (maxRestoreBufferSize !== undefined) { casConfig.maxRestoreBufferSize = maxRestoreBufferSize; }
355
-
356
- const cas = createCas(opts.cwd, { observability: observer, ...casConfig });
357
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
358
- const manifest = await cas.readManifest({ treeOid });
359
-
360
- const encryptionKey = await resolveEncryptionKey(cas, opts);
348
+ .action(
349
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
350
+ warnInlinePassphraseArgs(opts);
351
+ validateCredentialSources(opts);
352
+ validateRestoreFlags(opts);
353
+ const quiet = program.opts().quiet || program.opts().json;
354
+ const observer = new EventEmitterObserver();
355
+
356
+ const config = loadConfig(opts.cwd);
357
+ /** @type {Record<string, any>} */
358
+ const casConfig = {};
359
+ const concurrency = opts.concurrency ?? config.concurrency;
360
+ const maxRestoreBufferSize = opts.maxRestoreBuffer ?? config.maxRestoreBufferSize;
361
+ if (concurrency !== undefined) {
362
+ casConfig.concurrency = concurrency;
363
+ }
364
+ if (maxRestoreBufferSize !== undefined) {
365
+ casConfig.maxRestoreBufferSize = maxRestoreBufferSize;
366
+ }
361
367
 
362
- const progress = createRestoreProgress({
363
- totalChunks: manifest.chunks.length, quiet,
364
- });
365
- progress.attach(observer);
366
- let bytesWritten;
367
- try {
368
- ({ bytesWritten } = await cas.restoreFile({
369
- manifest,
370
- ...(encryptionKey ? { encryptionKey } : {}),
371
- outputPath: opts.out,
372
- }));
373
- } finally {
374
- progress.detach();
375
- }
376
- const json = program.opts().json;
377
- if (json) {
378
- process.stdout.write(`${JSON.stringify({ bytesWritten })}\n`);
379
- } else {
380
- process.stdout.write(`${bytesWritten}\n`);
381
- }
382
- }, getJson));
368
+ const cas = await createCas(opts.cwd, { observability: observer, ...casConfig });
369
+ const treeOid = opts.oid || (await cas.resolveVaultEntry({ slug: opts.slug }));
370
+ const manifest = await cas.readManifest({ treeOid });
371
+
372
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
373
+
374
+ const progress = createRestoreProgress({
375
+ totalChunks: manifest.chunks.length,
376
+ quiet,
377
+ });
378
+ progress.attach(observer);
379
+ let bytesWritten;
380
+ const restoreTarget = resolveRestoreOutputTarget(opts.out);
381
+ try {
382
+ ({ bytesWritten } = await cas.restoreFile({
383
+ manifest,
384
+ ...(encryptionKey ? { encryptionKey } : {}),
385
+ outputPath: restoreTarget.outputPath,
386
+ baseDirectory: restoreTarget.baseDirectory,
387
+ }));
388
+ } finally {
389
+ progress.detach();
390
+ }
391
+ const json = program.opts().json;
392
+ if (json) {
393
+ process.stdout.write(`${JSON.stringify({ bytesWritten })}\n`);
394
+ } else {
395
+ process.stdout.write(`${bytesWritten}\n`);
396
+ }
397
+ }, getJson)
398
+ );
383
399
 
384
400
  // ---------------------------------------------------------------------------
385
401
  // verify
@@ -390,54 +406,121 @@ program
390
406
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
391
407
  .option('--oid <tree-oid>', 'Direct tree OID')
392
408
  .option('--cwd <dir>', 'Git working directory', '.')
393
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
394
- validateRestoreFlags(opts);
395
- const cas = createCas(opts.cwd);
396
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
397
- const manifest = await cas.readManifest({ treeOid });
398
- const ok = await cas.verifyIntegrity(manifest);
399
- const json = program.opts().json;
400
- if (json) {
401
- process.stdout.write(`${JSON.stringify({ ok, slug: manifest.slug, chunks: manifest.chunks.length })}\n`);
402
- } else {
403
- process.stdout.write(ok ? 'ok\n' : `fail: ${manifest.slug}\n`);
404
- }
405
- if (!ok) {
406
- process.exitCode = 1;
407
- }
408
- }, getJson));
409
+ .action(
410
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
411
+ validateRestoreFlags(opts);
412
+ const cas = await createCas(opts.cwd);
413
+ const treeOid = opts.oid || (await cas.resolveVaultEntry({ slug: opts.slug }));
414
+ const manifest = await cas.readManifest({ treeOid });
415
+ const ok = await cas.verifyIntegrity(manifest);
416
+ const json = program.opts().json;
417
+ if (json) {
418
+ process.stdout.write(
419
+ `${JSON.stringify({ ok, slug: manifest.slug, chunks: manifest.chunks.length })}\n`
420
+ );
421
+ } else {
422
+ process.stdout.write(ok ? 'ok\n' : `fail: ${manifest.slug}\n`);
423
+ }
424
+ if (!ok) {
425
+ process.exitCode = 1;
426
+ }
427
+ }, getJson)
428
+ );
429
+
430
+ // ---------------------------------------------------------------------------
431
+ // doctor
432
+ // ---------------------------------------------------------------------------
433
+ program
434
+ .command('doctor')
435
+ .description('Inspect vault health and surface integrity issues')
436
+ .option('--cwd <dir>', 'Git working directory', '.')
437
+ .option('--key-file <path>', 'Read raw 32-byte vault encryption key from file')
438
+ .option(
439
+ '--vault-passphrase <pass>',
440
+ 'Vault-level passphrase for privacy vault diagnostics (warns; prefer --vault-passphrase-file -, GIT_CAS_PASSPHRASE, or --os-keychain-target)'
441
+ )
442
+ .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
443
+ .option(
444
+ '--os-keychain-target <target>',
445
+ 'Read vault passphrase from OS keychain target via @git-stunts/vault'
446
+ )
447
+ .option(
448
+ '--os-keychain-account <account>',
449
+ 'OS keychain account namespace for --os-keychain-target (default: git-cas)'
450
+ )
451
+ .action(
452
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
453
+ warnInlinePassphraseArgs(opts);
454
+ validateCredentialSources(opts);
455
+ const cas = await createCas(opts.cwd);
456
+ const encryptionKey = await resolveEncryptionKey(cas, opts);
457
+ const report = await inspectVaultHealth(cas, { encryptionKey });
458
+ const json = program.opts().json;
459
+
460
+ if (json) {
461
+ process.stdout.write(`${JSON.stringify(report)}\n`);
462
+ } else {
463
+ const ctx = getCliContext();
464
+ process.stdout.write(`${renderHealthDashboard(report, ctx)}\n`);
465
+ }
466
+
467
+ if (report.status !== 'ok') {
468
+ process.exitCode = 1;
469
+ }
470
+ }, getJson)
471
+ );
409
472
 
410
473
  // ---------------------------------------------------------------------------
411
474
  // vault init
412
475
  // ---------------------------------------------------------------------------
413
- const vault = program
414
- .command('vault')
415
- .description('Manage the CAS vault');
476
+ const vault = program.command('vault').description('Manage the CAS vault');
416
477
 
417
478
  vault
418
479
  .command('init')
419
480
  .description('Initialize the vault')
420
- .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption (prefer GIT_CAS_PASSPHRASE env var)')
481
+ .option(
482
+ '--vault-passphrase <pass>',
483
+ 'Passphrase for vault-level encryption (warns; prefer --vault-passphrase-file -, GIT_CAS_PASSPHRASE, or --os-keychain-target)'
484
+ )
421
485
  .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
422
- .addOption(new Option('--algorithm <alg>', 'KDF algorithm').choices(['pbkdf2', 'scrypt']).default('pbkdf2'))
486
+ .option(
487
+ '--os-keychain-target <target>',
488
+ 'Read vault passphrase from OS keychain target via @git-stunts/vault'
489
+ )
490
+ .option(
491
+ '--os-keychain-account <account>',
492
+ 'OS keychain account namespace for --os-keychain-target (default: git-cas)'
493
+ )
494
+ .addOption(new Option('--algorithm <alg>', 'KDF algorithm').choices(['pbkdf2', 'scrypt']))
423
495
  .option('--cwd <dir>', 'Git working directory', '.')
424
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
425
- const cas = createCas(opts.cwd);
426
- /** @type {{ passphrase?: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
427
- const initOpts = {};
428
- const passphrase = await resolvePassphrase(opts, { confirm: true });
429
- if (passphrase) {
430
- initOpts.passphrase = passphrase;
431
- initOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
432
- }
433
- const { commitOid } = await cas.initVault(initOpts);
434
- const json = program.opts().json;
435
- if (json) {
436
- process.stdout.write(`${JSON.stringify({ commitOid })}\n`);
437
- } else {
438
- process.stdout.write(`${commitOid}\n`);
439
- }
440
- }, getJson));
496
+ .action(
497
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
498
+ warnInlinePassphraseArgs(opts);
499
+ validateCredentialSources(opts);
500
+ const cas = await createCas(opts.cwd);
501
+ /** @type {{ passphrase?: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
502
+ const initOpts = {};
503
+ const passphrase = await resolvePassphrase(opts, { confirm: true });
504
+ if (!passphrase && opts.algorithm !== undefined) {
505
+ throw new Error(
506
+ 'Provide --vault-passphrase, --vault-passphrase-file, or --os-keychain-target when using --algorithm'
507
+ );
508
+ }
509
+ if (passphrase) {
510
+ initOpts.passphrase = passphrase;
511
+ initOpts.kdfOptions = {
512
+ algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm || 'pbkdf2'),
513
+ };
514
+ }
515
+ const { commitOid } = await cas.initVault(initOpts);
516
+ const json = program.opts().json;
517
+ if (json) {
518
+ process.stdout.write(`${JSON.stringify({ commitOid })}\n`);
519
+ } else {
520
+ process.stdout.write(`${commitOid}\n`);
521
+ }
522
+ }, getJson)
523
+ );
441
524
 
442
525
  // ---------------------------------------------------------------------------
443
526
  // vault list
@@ -447,19 +530,49 @@ vault
447
530
  .description('List vault entries')
448
531
  .option('--filter <pattern>', 'Filter entries by glob pattern')
449
532
  .option('--cwd <dir>', 'Git working directory', '.')
450
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
451
- const cas = createCas(opts.cwd);
452
- const all = await cas.listVault();
453
- const entries = filterEntries(all, opts.filter);
454
- const json = program.opts().json;
455
- if (json) {
456
- process.stdout.write(`${JSON.stringify(entries)}\n`);
457
- } else if (process.stdout.isTTY) {
458
- process.stdout.write(formatTable(entries));
459
- } else {
460
- process.stdout.write(formatTabSeparated(entries));
461
- }
462
- }, getJson));
533
+ .action(
534
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
535
+ const cas = await createCas(opts.cwd);
536
+ const all = await cas.listVault();
537
+ const entries = filterEntries(all, opts.filter);
538
+ const json = program.opts().json;
539
+ if (json) {
540
+ process.stdout.write(`${JSON.stringify(entries)}\n`);
541
+ } else if (process.stdout.isTTY) {
542
+ process.stdout.write(formatTable(entries));
543
+ } else {
544
+ process.stdout.write(formatTabSeparated(entries));
545
+ }
546
+ }, getJson)
547
+ );
548
+
549
+ // ---------------------------------------------------------------------------
550
+ // vault stats
551
+ // ---------------------------------------------------------------------------
552
+ vault
553
+ .command('stats')
554
+ .description('Summarize vault size, dedupe, and encryption coverage')
555
+ .option('--filter <pattern>', 'Filter entries by glob pattern')
556
+ .option('--cwd <dir>', 'Git working directory', '.')
557
+ .action(
558
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
559
+ const cas = await createCas(opts.cwd);
560
+ const all = await cas.listVault();
561
+ const entries = filterEntries(all, opts.filter);
562
+ const records = [];
563
+ for (const entry of entries) {
564
+ const manifest = await cas.readManifest({ treeOid: entry.treeOid });
565
+ records.push({ ...entry, manifest });
566
+ }
567
+ const stats = buildVaultStats(records);
568
+ const json = program.opts().json;
569
+ if (json) {
570
+ process.stdout.write(`${JSON.stringify(stats)}\n`);
571
+ } else {
572
+ process.stdout.write(renderVaultStats(stats));
573
+ }
574
+ }, getJson)
575
+ );
463
576
 
464
577
  // ---------------------------------------------------------------------------
465
578
  // vault remove
@@ -468,16 +581,19 @@ vault
468
581
  .command('remove <slug>')
469
582
  .description('Remove an entry from the vault')
470
583
  .option('--cwd <dir>', 'Git working directory', '.')
471
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
472
- const cas = createCas(opts.cwd);
473
- const { commitOid, removedTreeOid } = await cas.removeFromVault({ slug });
474
- const json = program.opts().json;
475
- if (json) {
476
- process.stdout.write(`${JSON.stringify({ commitOid, removedTreeOid })}\n`);
477
- } else {
478
- process.stdout.write(`${removedTreeOid}\n`);
479
- }
480
- }, getJson));
584
+ .action(
585
+ runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
586
+ const cas = await createCas(opts.cwd);
587
+ const vaultSlug = normalizeSlug(slug);
588
+ const { commitOid, removedTreeOid } = await cas.removeFromVault({ slug: vaultSlug });
589
+ const json = program.opts().json;
590
+ if (json) {
591
+ process.stdout.write(`${JSON.stringify({ commitOid, removedTreeOid })}\n`);
592
+ } else {
593
+ process.stdout.write(`${removedTreeOid}\n`);
594
+ }
595
+ }, getJson)
596
+ );
481
597
 
482
598
  // ---------------------------------------------------------------------------
483
599
  // vault info
@@ -487,29 +603,32 @@ vault
487
603
  .description('Show info for a vault entry')
488
604
  .option('--encryption', 'Show vault encryption details')
489
605
  .option('--cwd <dir>', 'Git working directory', '.')
490
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
491
- const cas = createCas(opts.cwd);
492
- const treeOid = await cas.resolveVaultEntry({ slug });
493
- const json = program.opts().json;
494
- if (json) {
495
- /** @type {Record<string, any>} */
496
- const result = { slug, treeOid };
497
- if (opts.encryption) {
498
- const metadata = await cas.getVaultMetadata();
499
- if (metadata?.encryption) {
500
- result.encryption = metadata.encryption;
606
+ .action(
607
+ runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
608
+ const cas = await createCas(opts.cwd);
609
+ const vaultSlug = normalizeSlug(slug);
610
+ const treeOid = await cas.resolveVaultEntry({ slug: vaultSlug });
611
+ const json = program.opts().json;
612
+ if (json) {
613
+ /** @type {Record<string, any>} */
614
+ const result = { slug: vaultSlug, treeOid };
615
+ if (opts.encryption) {
616
+ const metadata = await cas.getVaultMetadata();
617
+ if (metadata?.encryption) {
618
+ result.encryption = metadata.encryption;
619
+ }
620
+ }
621
+ process.stdout.write(`${JSON.stringify(result)}\n`);
622
+ } else {
623
+ process.stdout.write(`slug\t${vaultSlug}\n`);
624
+ process.stdout.write(`tree\t${treeOid}\n`);
625
+ if (opts.encryption) {
626
+ const metadata = await cas.getVaultMetadata();
627
+ process.stdout.write(`\n${surfaceToString(renderEncryptionCard({ metadata }), getCliContext().style)}\n`);
501
628
  }
502
629
  }
503
- process.stdout.write(`${JSON.stringify(result)}\n`);
504
- } else {
505
- process.stdout.write(`slug\t${slug}\n`);
506
- process.stdout.write(`tree\t${treeOid}\n`);
507
- if (opts.encryption) {
508
- const metadata = await cas.getVaultMetadata();
509
- process.stdout.write(`\n${renderEncryptionCard({ metadata })}\n`);
510
- }
511
- }
512
- }, getJson));
630
+ }, getJson)
631
+ );
513
632
 
514
633
  // ---------------------------------------------------------------------------
515
634
  // vault history
@@ -520,34 +639,35 @@ vault
520
639
  .option('--cwd <dir>', 'Git working directory', '.')
521
640
  .option('-n, --max-count <n>', 'Limit number of commits')
522
641
  .option('--pretty', 'Render as color-coded timeline')
523
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
524
- const runner = ShellRunnerFactory.create();
525
- const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
526
- const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
527
- if (opts.maxCount) {
528
- const n = parseInt(opts.maxCount, 10);
529
- if (Number.isNaN(n) || n <= 0) {
530
- throw new Error('--max-count must be a positive integer');
531
- }
532
- args.push(`-${n}`);
533
- }
534
- const output = await plumbing.execute({ args });
535
- const json = program.opts().json;
536
- if (json) {
537
- const history = output
538
- .split('\n')
539
- .filter(Boolean)
540
- .map((/** @type {string} */ line) => {
541
- const [commitOid, ...messageParts] = line.trim().split(/\s+/);
542
- return { commitOid, message: messageParts.join(' ') };
543
- });
544
- process.stdout.write(`${JSON.stringify(history)}\n`);
545
- } else if (opts.pretty && process.stdout.isTTY) {
546
- process.stdout.write(`${renderHistoryTimeline(output)}\n`);
547
- } else {
548
- process.stdout.write(`${output}\n`);
549
- }
550
- }, getJson));
642
+ .action(
643
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
644
+ const plumbing = await createGitPlumbing({ cwd: opts.cwd || '.' });
645
+ const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
646
+ if (opts.maxCount) {
647
+ const n = parseInt(opts.maxCount, 10);
648
+ if (Number.isNaN(n) || n <= 0) {
649
+ throw new Error('--max-count must be a positive integer');
650
+ }
651
+ args.push(`-${n}`);
652
+ }
653
+ const output = await plumbing.execute({ args });
654
+ const json = program.opts().json;
655
+ if (json) {
656
+ const history = output
657
+ .split('\n')
658
+ .filter(Boolean)
659
+ .map((/** @type {string} */ line) => {
660
+ const [commitOid, ...messageParts] = line.trim().split(/\s+/);
661
+ return { commitOid, message: messageParts.join(' ') };
662
+ });
663
+ process.stdout.write(`${JSON.stringify(history)}\n`);
664
+ } else if (opts.pretty && process.stdout.isTTY) {
665
+ process.stdout.write(`${renderHistoryTimeline(output)}\n`);
666
+ } else {
667
+ process.stdout.write(`${output}\n`);
668
+ }
669
+ }, getJson)
670
+ );
551
671
 
552
672
  // ---------------------------------------------------------------------------
553
673
  // vault rotate
@@ -568,58 +688,80 @@ async function resolveRotatePassphrases(opts) {
568
688
  const newPassphrase = opts.newPassphraseFile
569
689
  ? await readPassphraseFile(opts.newPassphraseFile)
570
690
  : opts.newPassphrase;
571
- if (!oldPassphrase) { throw new Error('Old passphrase required (--old-passphrase or --old-passphrase-file)'); }
572
- if (!newPassphrase) { throw new Error('New passphrase required (--new-passphrase or --new-passphrase-file)'); }
691
+ if (!oldPassphrase || !oldPassphrase.trim()) {
692
+ throw new Error('Old passphrase required (--old-passphrase or --old-passphrase-file)');
693
+ }
694
+ if (!newPassphrase || !newPassphrase.trim()) {
695
+ throw new Error('New passphrase required (--new-passphrase or --new-passphrase-file)');
696
+ }
573
697
  return { oldPassphrase, newPassphrase };
574
698
  }
575
699
 
576
700
  vault
577
701
  .command('rotate')
578
702
  .description('Rotate vault-level encryption passphrase')
579
- .option('--old-passphrase <pass>', 'Current vault passphrase')
580
- .option('--new-passphrase <pass>', 'New vault passphrase')
703
+ .option('--old-passphrase <pass>', 'Current vault passphrase (warns; prefer --old-passphrase-file -)')
704
+ .option('--new-passphrase <pass>', 'New vault passphrase (warns; prefer --new-passphrase-file -)')
581
705
  .option('--old-passphrase-file <path>', 'Read old passphrase from file (- for stdin)')
582
706
  .option('--new-passphrase-file <path>', 'Read new passphrase from file (- for stdin)')
583
707
  .addOption(new Option('--algorithm <alg>', 'KDF algorithm').choices(['pbkdf2', 'scrypt']))
584
708
  .option('--cwd <dir>', 'Git working directory', '.')
585
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
586
- const { oldPassphrase, newPassphrase } = await resolveRotatePassphrases(opts);
587
- const cas = createCas(opts.cwd);
588
- /** @type {{ oldPassphrase: string, newPassphrase: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
589
- const rotateOpts = {
590
- oldPassphrase,
591
- newPassphrase,
592
- };
593
- if (opts.algorithm) {
594
- rotateOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
595
- }
596
- const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase(rotateOpts);
597
- const json = program.opts().json;
598
- if (json) {
599
- process.stdout.write(`${JSON.stringify({ commitOid, rotatedSlugs, skippedSlugs })}\n`);
600
- } else {
601
- process.stdout.write(`${commitOid}\n`);
602
- if (rotatedSlugs.length) {
603
- process.stderr.write(`rotated: ${rotatedSlugs.join(', ')}\n`);
604
- }
605
- if (skippedSlugs.length) {
606
- process.stderr.write(`skipped: ${skippedSlugs.join(', ')}\n`);
709
+ .action(
710
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
711
+ warnInlinePassphraseArgs(opts);
712
+ const { oldPassphrase, newPassphrase } = await resolveRotatePassphrases(opts);
713
+ const cas = await createCas(opts.cwd);
714
+ /** @type {{ oldPassphrase: string, newPassphrase: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
715
+ const rotateOpts = {
716
+ oldPassphrase,
717
+ newPassphrase,
718
+ };
719
+ if (opts.algorithm) {
720
+ rotateOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
607
721
  }
608
- }
609
- }, getJson));
722
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase(rotateOpts);
723
+ const json = program.opts().json;
724
+ if (json) {
725
+ process.stdout.write(`${JSON.stringify({ commitOid, rotatedSlugs, skippedSlugs })}\n`);
726
+ } else {
727
+ process.stdout.write(`${commitOid}\n`);
728
+ if (rotatedSlugs.length) {
729
+ process.stderr.write(`rotated: ${rotatedSlugs.join(', ')}\n`);
730
+ }
731
+ if (skippedSlugs.length) {
732
+ process.stderr.write(`skipped: ${skippedSlugs.join(', ')}\n`);
733
+ }
734
+ }
735
+ }, getJson)
736
+ );
610
737
 
611
738
  // ---------------------------------------------------------------------------
612
739
  // vault dashboard
613
740
  // ---------------------------------------------------------------------------
614
741
  vault
615
742
  .command('dashboard')
616
- .description('Interactive vault explorer')
743
+ .description('Interactive CAS explorer')
617
744
  .option('--cwd <dir>', 'Git working directory', '.')
618
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
619
- const cas = createCas(opts.cwd);
620
- const { launchDashboard } = await import('./ui/dashboard.js');
621
- await launchDashboard(cas);
622
- }, getJson));
745
+ .option(
746
+ '--ref <gitRef>',
747
+ 'Inspect a git ref that points to a CAS tree, CAS index blob, or commit with a manifest hint'
748
+ )
749
+ .option('--oid <treeOid>', 'Inspect a direct CAS tree OID')
750
+ .action(
751
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
752
+ if (opts.ref && opts.oid) {
753
+ throw new Error('Choose either --ref or --oid, not both');
754
+ }
755
+ const cas = await createCas(opts.cwd);
756
+ const { launchDashboard } = await import('./ui/dashboard.js');
757
+ const source = opts.ref
758
+ ? { type: 'ref', ref: opts.ref }
759
+ : opts.oid
760
+ ? { type: 'oid', treeOid: opts.oid }
761
+ : { type: 'vault' };
762
+ await launchDashboard(cas, { cwd: path.resolve(opts.cwd), source });
763
+ }, getJson)
764
+ );
623
765
 
624
766
  // ---------------------------------------------------------------------------
625
767
  // rotate
@@ -633,43 +775,47 @@ program
633
775
  .requiredOption('--new-key-file <path>', 'Path to new 32-byte key file')
634
776
  .option('--label <label>', 'Rotate only the named recipient')
635
777
  .option('--cwd <dir>', 'Git working directory', '.')
636
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
637
- validateRestoreFlags(opts);
638
- const cas = createCas(opts.cwd);
639
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
640
- const manifest = await cas.readManifest({ treeOid });
641
-
642
- const oldKey = readKeyFile(opts.oldKeyFile);
643
- const newKey = readKeyFile(opts.newKeyFile);
644
-
645
- /** @type {{ manifest: Manifest, oldKey: Buffer, newKey: Buffer, label?: string }} */
646
- const rotateOpts = { manifest, oldKey, newKey };
647
- if (opts.label) { rotateOpts.label = opts.label; }
648
-
649
- const updated = await cas.rotateKey(rotateOpts);
650
- const json = program.opts().json;
778
+ .action(
779
+ runAction(async (/** @type {Record<string, any>} */ opts) => {
780
+ validateRestoreFlags(opts);
781
+ const cas = await createCas(opts.cwd);
782
+ const treeOid = opts.oid || (await cas.resolveVaultEntry({ slug: opts.slug }));
783
+ const manifest = await cas.readManifest({ treeOid });
784
+
785
+ const oldKey = readKeyFile(opts.oldKeyFile);
786
+ const newKey = readKeyFile(opts.newKeyFile);
787
+
788
+ /** @type {{ manifest: Manifest, oldKey: Uint8Array, newKey: Uint8Array, label?: string }} */
789
+ const rotateOpts = { manifest, oldKey, newKey };
790
+ if (opts.label) {
791
+ rotateOpts.label = opts.label;
792
+ }
651
793
 
652
- if (opts.slug) {
653
- const newTreeOid = await cas.createTree({ manifest: updated });
654
- await cas.addToVault({ slug: opts.slug, treeOid: newTreeOid, force: true });
655
- if (json) {
656
- process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid, keyVersion: updated.encryption?.keyVersion })}\n`);
794
+ const updated = await cas.rotateKey(rotateOpts);
795
+ const json = program.opts().json;
796
+
797
+ if (opts.slug) {
798
+ const newTreeOid = await cas.createTree({ manifest: updated });
799
+ await cas.addToVault({ slug: normalizeSlug(opts.slug), treeOid: newTreeOid, force: true });
800
+ if (json) {
801
+ process.stdout.write(
802
+ `${JSON.stringify({ treeOid: newTreeOid, keyVersion: updated.encryption?.keyVersion })}\n`
803
+ );
804
+ } else {
805
+ process.stdout.write(`${newTreeOid}\n`);
806
+ }
807
+ } else if (json) {
808
+ process.stdout.write(`${JSON.stringify(updated.toJSON())}\n`);
657
809
  } else {
658
- process.stdout.write(`${newTreeOid}\n`);
810
+ process.stdout.write(`${JSON.stringify(updated.toJSON(), null, 2)}\n`);
659
811
  }
660
- } else if (json) {
661
- process.stdout.write(`${JSON.stringify(updated.toJSON())}\n`);
662
- } else {
663
- process.stdout.write(`${JSON.stringify(updated.toJSON(), null, 2)}\n`);
664
- }
665
- }, getJson));
812
+ }, getJson)
813
+ );
666
814
 
667
815
  // ---------------------------------------------------------------------------
668
816
  // recipient add / remove / list
669
817
  // ---------------------------------------------------------------------------
670
- const recipient = program
671
- .command('recipient')
672
- .description('Manage envelope encryption recipients');
818
+ const recipient = program.command('recipient').description('Manage envelope encryption recipients');
673
819
 
674
820
  recipient
675
821
  .command('add <slug>')
@@ -678,78 +824,86 @@ recipient
678
824
  .requiredOption('--key-file <path>', 'Path to 32-byte key file for the new recipient')
679
825
  .requiredOption('--existing-key-file <path>', 'Path to key file of an existing recipient')
680
826
  .option('--cwd <dir>', 'Git working directory', '.')
681
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
682
- const cas = createCas(opts.cwd);
683
- const treeOid = await cas.resolveVaultEntry({ slug });
684
- const manifest = await cas.readManifest({ treeOid });
685
-
686
- const existingKey = readKeyFile(opts.existingKeyFile);
687
- const newRecipientKey = readKeyFile(opts.keyFile);
688
-
689
- const updated = await cas.addRecipient({
690
- manifest,
691
- existingKey,
692
- newRecipientKey,
693
- label: opts.label,
694
- });
695
-
696
- const newTreeOid = await cas.createTree({ manifest: updated });
697
- await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
698
-
699
- const json = program.opts().json;
700
- if (json) {
701
- process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
702
- } else {
703
- process.stdout.write(`${newTreeOid}\n`);
704
- }
705
- }, getJson));
827
+ .action(
828
+ runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
829
+ const cas = await createCas(opts.cwd);
830
+ const vaultSlug = normalizeSlug(slug);
831
+ const treeOid = await cas.resolveVaultEntry({ slug: vaultSlug });
832
+ const manifest = await cas.readManifest({ treeOid });
833
+
834
+ const existingKey = readKeyFile(opts.existingKeyFile);
835
+ const newRecipientKey = readKeyFile(opts.keyFile);
836
+
837
+ const updated = await cas.addRecipient({
838
+ manifest,
839
+ existingKey,
840
+ newRecipientKey,
841
+ label: opts.label,
842
+ });
843
+
844
+ const newTreeOid = await cas.createTree({ manifest: updated });
845
+ await cas.addToVault({ slug: vaultSlug, treeOid: newTreeOid, force: true });
846
+
847
+ const json = program.opts().json;
848
+ if (json) {
849
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
850
+ } else {
851
+ process.stdout.write(`${newTreeOid}\n`);
852
+ }
853
+ }, getJson)
854
+ );
706
855
 
707
856
  recipient
708
857
  .command('remove <slug>')
709
858
  .description('Remove a recipient from an envelope-encrypted asset')
710
859
  .requiredOption('--label <label>', 'Label of the recipient to remove')
711
860
  .option('--cwd <dir>', 'Git working directory', '.')
712
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
713
- const cas = createCas(opts.cwd);
714
- const treeOid = await cas.resolveVaultEntry({ slug });
715
- const manifest = await cas.readManifest({ treeOid });
861
+ .action(
862
+ runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
863
+ const cas = await createCas(opts.cwd);
864
+ const vaultSlug = normalizeSlug(slug);
865
+ const treeOid = await cas.resolveVaultEntry({ slug: vaultSlug });
866
+ const manifest = await cas.readManifest({ treeOid });
716
867
 
717
- const updated = await cas.removeRecipient({ manifest, label: opts.label });
868
+ const updated = await cas.removeRecipient({ manifest, label: opts.label });
718
869
 
719
- const newTreeOid = await cas.createTree({ manifest: updated });
720
- await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
870
+ const newTreeOid = await cas.createTree({ manifest: updated });
871
+ await cas.addToVault({ slug: vaultSlug, treeOid: newTreeOid, force: true });
721
872
 
722
- const json = program.opts().json;
723
- if (json) {
724
- process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
725
- } else {
726
- process.stdout.write(`${newTreeOid}\n`);
727
- }
728
- }, getJson));
873
+ const json = program.opts().json;
874
+ if (json) {
875
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
876
+ } else {
877
+ process.stdout.write(`${newTreeOid}\n`);
878
+ }
879
+ }, getJson)
880
+ );
729
881
 
730
882
  recipient
731
883
  .command('list <slug>')
732
884
  .description('List recipients of an envelope-encrypted asset')
733
885
  .option('--cwd <dir>', 'Git working directory', '.')
734
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
735
- const cas = createCas(opts.cwd);
736
- const treeOid = await cas.resolveVaultEntry({ slug });
737
- const manifest = await cas.readManifest({ treeOid });
738
-
739
- const labels = await cas.listRecipients(manifest);
740
- const json = program.opts().json;
741
- if (json) {
742
- process.stdout.write(`${JSON.stringify(labels)}\n`);
743
- } else {
744
- for (const label of labels) {
745
- process.stdout.write(`${label}\n`);
886
+ .action(
887
+ runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
888
+ const cas = await createCas(opts.cwd);
889
+ const vaultSlug = normalizeSlug(slug);
890
+ const treeOid = await cas.resolveVaultEntry({ slug: vaultSlug });
891
+ const manifest = await cas.readManifest({ treeOid });
892
+
893
+ const labels = await cas.listRecipients(manifest);
894
+ const json = program.opts().json;
895
+ if (json) {
896
+ process.stdout.write(`${JSON.stringify(labels)}\n`);
897
+ } else {
898
+ for (const label of labels) {
899
+ process.stdout.write(`${label}\n`);
900
+ }
746
901
  }
747
- }
748
- }, getJson));
902
+ }, getJson)
903
+ );
749
904
 
750
905
  await program.parseAsync();
751
906
 
752
907
  // Flush stdout/stderr before exiting — spawned git child processes leave
753
908
  // libuv handles that prevent natural exit in containerized environments.
754
- const code = process.exitCode || 0;
755
- process.stdout.write('', () => process.stderr.write('', () => process.exit(code)));
909
+ await flushStdioAndExit();