@git-stunts/git-cas 5.3.2 → 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 (173) hide show
  1. package/ADVANCED_GUIDE.md +1006 -0
  2. package/ARCHITECTURE.md +514 -0
  3. package/CHANGELOG.md +393 -5
  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 +70 -21
  11. package/bin/agent/cli.js +51 -0
  12. package/bin/agent/commands/doctor.js +99 -0
  13. package/bin/agent/commands/index.js +1489 -0
  14. package/bin/agent/input.js +619 -0
  15. package/bin/agent/passphrase-source.js +123 -0
  16. package/bin/agent/protocol.js +193 -0
  17. package/bin/build-version.js +64 -0
  18. package/bin/credentials.js +425 -0
  19. package/bin/git-cas.js +595 -449
  20. package/bin/passphrase-source.js +266 -0
  21. package/bin/restore-output-target.js +28 -0
  22. package/bin/ui/blocks/asset-card.js +109 -0
  23. package/bin/ui/blocks/health-dashboard.js +149 -0
  24. package/bin/ui/blocks/heatmap-block.js +67 -0
  25. package/bin/ui/blocks/merkle-explorer.js +163 -0
  26. package/bin/ui/blocks/operation-feed.js +176 -0
  27. package/bin/ui/blocks/wizard-block.js +168 -0
  28. package/bin/ui/components/short-sha.js +36 -0
  29. package/bin/ui/context.js +56 -1
  30. package/bin/ui/dashboard-cmds.js +1578 -13
  31. package/bin/ui/dashboard-view.js +612 -145
  32. package/bin/ui/dashboard.js +998 -214
  33. package/bin/ui/encryption-card.js +69 -26
  34. package/bin/ui/heatmap.js +26 -54
  35. package/bin/ui/history-timeline.js +51 -19
  36. package/bin/ui/manifest-view.js +115 -60
  37. package/bin/ui/merkle-dag.js +83 -0
  38. package/bin/ui/progress.js +15 -9
  39. package/bin/ui/repo-treemap.js +328 -0
  40. package/bin/ui/shaders/bak-sneppen.js +180 -0
  41. package/bin/ui/shaders/fractal-zoom.js +99 -0
  42. package/bin/ui/shaders/merkle-tree.js +142 -0
  43. package/bin/ui/shaders/organic-flow.js +96 -0
  44. package/bin/ui/shaders/phase-portrait.js +93 -0
  45. package/bin/ui/store-wizard.js +296 -0
  46. package/bin/ui/theme.js +155 -0
  47. package/bin/ui/vault-report.js +495 -0
  48. package/build-info.json +4 -0
  49. package/docs/API.md +2224 -0
  50. package/docs/ENCRYPTION_MODES.md +33 -0
  51. package/docs/EXTENDING.md +174 -0
  52. package/docs/STORE_RESTORE_PIPELINE.md +199 -0
  53. package/docs/THREAT_MODEL.md +269 -0
  54. package/docs/VAULT_INTERNALS.md +251 -0
  55. package/docs/WALKTHROUGH.md +1868 -0
  56. package/docs/demo.gif +0 -0
  57. package/docs/releases/v6.0.0.md +104 -0
  58. package/examples/README.md +260 -0
  59. package/index.d.ts +208 -65
  60. package/index.js +163 -54
  61. package/package.json +35 -6
  62. package/scripts/migrate-encryption.js +680 -0
  63. package/src/domain/bytes/ByteLayout.js +96 -0
  64. package/src/domain/encoding/base64.js +91 -0
  65. package/src/domain/encoding/hex.js +14 -0
  66. package/src/domain/encoding/utf8.js +123 -0
  67. package/src/domain/encryption/schemes.js +132 -0
  68. package/src/domain/errors/CannotRemoveLastRecipientError.js +10 -0
  69. package/src/domain/errors/CasError.d.ts +28 -0
  70. package/src/domain/errors/CasError.js +43 -6
  71. package/src/domain/errors/Codes.js +54 -0
  72. package/src/domain/errors/DekUnwrapFailedError.js +10 -0
  73. package/src/domain/errors/GitError.js +10 -0
  74. package/src/domain/errors/GitPlumbingInitializationError.js +10 -0
  75. package/src/domain/errors/IntegrityError.js +10 -0
  76. package/src/domain/errors/InvalidChunkingStrategyError.js +10 -0
  77. package/src/domain/errors/InvalidOidError.js +10 -0
  78. package/src/domain/errors/InvalidOptionsError.js +10 -0
  79. package/src/domain/errors/ManifestIntegrityError.js +10 -0
  80. package/src/domain/errors/ManifestNotFoundError.js +10 -0
  81. package/src/domain/errors/NoMatchingRecipientError.js +10 -0
  82. package/src/domain/errors/PersistenceCapabilityRequiredError.js +10 -0
  83. package/src/domain/errors/PortNotImplementedError.js +10 -0
  84. package/src/domain/errors/RecipientAlreadyExistsError.js +10 -0
  85. package/src/domain/errors/RecipientNotFoundError.js +10 -0
  86. package/src/domain/errors/RestoreTooLargeError.js +10 -0
  87. package/src/domain/errors/RotationNotSupportedError.js +10 -0
  88. package/src/domain/errors/createCasError.js +68 -0
  89. package/src/domain/errors/index.js +20 -0
  90. package/src/domain/helpers/buildKdfMetadata.js +4 -2
  91. package/src/domain/helpers/codecBytes.js +34 -0
  92. package/src/domain/helpers/gitRefErrors.js +84 -0
  93. package/src/domain/helpers/scryptMaxmem.js +22 -0
  94. package/src/domain/outcomes/RestoreFailure.js +15 -0
  95. package/src/domain/outcomes/RestoreOutcome.js +11 -0
  96. package/src/domain/outcomes/RestoreSuccess.js +34 -0
  97. package/src/domain/outcomes/StoreFailure.js +15 -0
  98. package/src/domain/outcomes/StoreOutcome.js +11 -0
  99. package/src/domain/outcomes/StoreSuccess.js +17 -0
  100. package/src/domain/schemas/ManifestSchema.d.ts +40 -9
  101. package/src/domain/schemas/ManifestSchema.js +67 -13
  102. package/src/domain/services/CasService.d.ts +123 -38
  103. package/src/domain/services/CasService.js +298 -834
  104. package/src/domain/services/ChunkRepository.js +230 -0
  105. package/src/domain/services/CompressionStreams.js +72 -0
  106. package/src/domain/services/ConvergentEncryption.js +128 -0
  107. package/src/domain/services/GitTreeBuilder.js +86 -0
  108. package/src/domain/services/IntegrityVerifier.js +199 -0
  109. package/src/domain/services/KeyResolver.js +49 -42
  110. package/src/domain/services/ManifestDiff.js +56 -0
  111. package/src/domain/services/ManifestRepository.js +286 -0
  112. package/src/domain/services/PrefetchWindow.js +48 -0
  113. package/src/domain/services/RecipientService.js +157 -0
  114. package/src/domain/services/RedactingObservability.js +169 -0
  115. package/src/domain/services/RestorePipeline.js +68 -0
  116. package/src/domain/services/StorePipeline.js +201 -0
  117. package/src/domain/services/VaultKeyVerifier.js +101 -0
  118. package/src/domain/services/VaultMetadataCodec.js +206 -0
  119. package/src/domain/services/VaultMutationRetryPolicy.js +105 -0
  120. package/src/domain/services/VaultPersistence.js +410 -0
  121. package/src/domain/services/VaultPrivacyIndex.js +191 -0
  122. package/src/domain/services/VaultService.js +749 -251
  123. package/src/domain/services/VaultStateCache.js +225 -0
  124. package/src/domain/services/VaultTreeCodec.js +121 -0
  125. package/src/domain/services/rotateVaultPassphrase.js +37 -20
  126. package/src/domain/strategies/Aad.js +39 -0
  127. package/src/domain/strategies/FramedRecordCodec.js +204 -0
  128. package/src/domain/strategies/RestoreCompressed.js +40 -0
  129. package/src/domain/strategies/RestoreConvergent.js +44 -0
  130. package/src/domain/strategies/RestoreFramed.js +55 -0
  131. package/src/domain/strategies/RestorePlain.js +37 -0
  132. package/src/domain/strategies/RestoreStrategy.js +35 -0
  133. package/src/domain/strategies/RestoreWhole.js +135 -0
  134. package/src/domain/strategies/StoreConvergent.js +28 -0
  135. package/src/domain/strategies/StoreFramed.js +39 -0
  136. package/src/domain/strategies/StorePlain.js +20 -0
  137. package/src/domain/strategies/StoreStrategy.js +61 -0
  138. package/src/domain/strategies/StoreWhole.js +34 -0
  139. package/src/domain/value-objects/Chunk.js +1 -2
  140. package/src/domain/value-objects/EncryptionMetadata.js +87 -0
  141. package/src/domain/value-objects/Manifest.d.ts +40 -4
  142. package/src/domain/value-objects/Manifest.js +61 -20
  143. package/src/domain/value-objects/Oid.js +45 -0
  144. package/src/domain/value-objects/Slug.js +124 -0
  145. package/src/domain/value-objects/StoreEncryptionConfig.js +114 -0
  146. package/src/helpers/aesGcmMeta.js +55 -0
  147. package/src/helpers/canonicalBase64.js +1 -0
  148. package/src/helpers/kdfPolicy.js +194 -0
  149. package/src/infrastructure/adapters/BunCryptoAdapter.js +124 -8
  150. package/src/infrastructure/adapters/FileIOHelper.js +178 -13
  151. package/src/infrastructure/adapters/GitPersistenceAdapter.js +235 -42
  152. package/src/infrastructure/adapters/GitPlumbingFactoryAdapter.js +62 -0
  153. package/src/infrastructure/adapters/GitRefAdapter.js +19 -6
  154. package/src/infrastructure/adapters/NodeCompressionAdapter.js +64 -0
  155. package/src/infrastructure/adapters/NodeCryptoAdapter.js +130 -10
  156. package/src/infrastructure/adapters/WebCryptoAdapter.js +187 -77
  157. package/src/infrastructure/chunkers/CdcChunker.js +53 -19
  158. package/src/infrastructure/chunkers/FixedChunker.js +15 -7
  159. package/src/infrastructure/chunkers/resolveChunker.js +3 -1
  160. package/src/infrastructure/codecs/CborCodec.js +3 -3
  161. package/src/infrastructure/codecs/JsonCodec.js +5 -5
  162. package/src/infrastructure/createGitPlumbing.js +22 -0
  163. package/src/package-version.js +1 -0
  164. package/src/ports/ChunkingPort.js +3 -3
  165. package/src/ports/CodecPort.js +4 -4
  166. package/src/ports/CompressionPort.js +57 -0
  167. package/src/ports/CryptoPort.js +138 -50
  168. package/src/ports/GitPersistencePort.js +32 -2
  169. package/src/ports/GitPlumbingFactoryPort.js +16 -0
  170. package/src/ports/GitRefPort.js +1 -1
  171. package/src/types/ambient.d.ts +10 -5
  172. package/test/CONVENTIONS.md +94 -0
  173. package/test/cycles/README.md +13 -0
package/bin/git-cas.js CHANGED
@@ -4,28 +4,56 @@ import { readFileSync } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import { program, Option } from 'commander';
7
- import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
8
7
  import ContentAddressableStore, { EventEmitterObserver, CborCodec } from '../index.js';
9
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';
10
11
  import { createStoreProgress, createRestoreProgress } from './ui/progress.js';
11
12
  import { renderEncryptionCard } from './ui/encryption-card.js';
12
13
  import { renderHistoryTimeline } from './ui/history-timeline.js';
13
14
  import { renderManifestView } from './ui/manifest-view.js';
14
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';
15
24
  import { runAction } from './actions.js';
25
+ import { runAgentCli } from './agent/cli.js';
16
26
  import { flushStdioAndExit, installBrokenPipeHandlers } from './io.js';
17
27
  import { filterEntries, formatTable, formatTabSeparated } from './ui/vault-list.js';
18
- 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';
19
39
  import { loadConfig, mergeConfig } from './config.js';
40
+ import { resolveRestoreOutputTarget } from './restore-output-target.js';
41
+
42
+ import { resolveVersionString } from './build-version.js';
20
43
 
21
44
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
22
- const { version: CLI_VERSION } = JSON.parse(
23
- readFileSync(path.resolve(__dirname, '../package.json'), 'utf8'),
45
+ const CLI_VERSION = resolveVersionString(
46
+ JSON.parse(readFileSync(path.resolve(__dirname, '../package.json'), 'utf8')).version,
24
47
  );
25
48
 
26
49
  const getJson = () => program.opts().json;
27
50
  installBrokenPipeHandlers();
28
51
 
52
+ if (process.argv[2] === 'agent') {
53
+ await runAgentCli(process.argv.slice(3));
54
+ await flushStdioAndExit();
55
+ }
56
+
29
57
  program
30
58
  .name('git-cas')
31
59
  .description('Content Addressable Storage backed by Git')
@@ -33,30 +61,15 @@ program
33
61
  .option('-q, --quiet', 'Suppress progress output')
34
62
  .option('--json', 'Output results as JSON');
35
63
 
36
- /**
37
- * Read a 32-byte raw encryption key from a file.
38
- *
39
- * @param {string} keyFilePath
40
- * @returns {Buffer}
41
- */
42
- function readKeyFile(keyFilePath) {
43
- const buf = readFileSync(keyFilePath);
44
- if (buf.length !== 32) {
45
- throw new Error(`Invalid key length: expected 32 bytes, got ${buf.length} (${keyFilePath})`);
46
- }
47
- return buf;
48
- }
49
-
50
64
  /**
51
65
  * Create a CAS instance for the given working directory.
52
66
  *
53
67
  * @param {string} cwd
54
68
  * @param {Record<string, any>} [opts]
55
- * @returns {ContentAddressableStore}
69
+ * @returns {Promise<ContentAddressableStore>}
56
70
  */
57
- function createCas(cwd, opts = {}) {
58
- const runner = ShellRunnerFactory.create();
59
- const plumbing = new GitPlumbing({ runner, cwd });
71
+ async function createCas(cwd, opts = {}) {
72
+ const plumbing = await createGitPlumbing({ cwd });
60
73
  /** @type {Record<string, any>} */
61
74
  const casOpts = { plumbing, ...opts };
62
75
  if (casOpts.codec === 'cbor') {
@@ -65,96 +78,6 @@ function createCas(cwd, opts = {}) {
65
78
  return new ContentAddressableStore(casOpts);
66
79
  }
67
80
 
68
- /**
69
- * Derive the encryption key from vault metadata + passphrase.
70
- *
71
- * @param {ContentAddressableStore} cas
72
- * @param {import('../index.js').VaultMetadata} metadata
73
- * @param {string} passphrase
74
- * @returns {Promise<Buffer>}
75
- */
76
- async function deriveVaultKey(cas, metadata, passphrase) {
77
- if (!metadata.encryption?.kdf) {
78
- throw new Error('Missing or malformed encryption metadata');
79
- }
80
- const { kdf } = metadata.encryption;
81
- const { key } = await cas.deriveKey({
82
- passphrase,
83
- salt: Buffer.from(kdf.salt, 'base64'),
84
- algorithm: /** @type {"pbkdf2" | "scrypt"} */ (kdf.algorithm),
85
- iterations: kdf.iterations,
86
- cost: kdf.cost,
87
- blockSize: kdf.blockSize,
88
- parallelization: kdf.parallelization,
89
- });
90
- return key;
91
- }
92
-
93
- /**
94
- * Returns true when a non-interactive passphrase source exists (flag or env).
95
- * Does NOT trigger prompts or consume stdin.
96
- *
97
- * @param {Record<string, any>} opts
98
- * @returns {boolean}
99
- */
100
- function hasPassphraseSource(opts) {
101
- return Boolean(opts.vaultPassphraseFile || opts.vaultPassphrase || process.env.GIT_CAS_PASSPHRASE);
102
- }
103
-
104
- /**
105
- * Resolve passphrase from (in priority order):
106
- * 1. --vault-passphrase-file <path>
107
- * 2. --vault-passphrase <pass>
108
- * 3. GIT_CAS_PASSPHRASE env var
109
- * 4. Interactive TTY prompt (if stdin is a TTY)
110
- *
111
- * @param {Record<string, any>} opts
112
- * @param {{ confirm?: boolean }} [extra]
113
- * @returns {Promise<string | undefined>}
114
- */
115
- async function resolvePassphrase(opts, extra = {}) {
116
- if (opts.vaultPassphraseFile) {
117
- return await readPassphraseFile(opts.vaultPassphraseFile);
118
- }
119
- if (opts.vaultPassphrase) {
120
- if (!opts.vaultPassphrase.trim()) { throw new Error('Passphrase must not be empty'); }
121
- return opts.vaultPassphrase;
122
- }
123
- if (process.env.GIT_CAS_PASSPHRASE) {
124
- if (!process.env.GIT_CAS_PASSPHRASE.trim()) { throw new Error('Passphrase must not be empty'); }
125
- return process.env.GIT_CAS_PASSPHRASE;
126
- }
127
- if (process.stdin.isTTY) {
128
- return await promptPassphrase({ confirm: extra.confirm || false });
129
- }
130
- return undefined;
131
- }
132
-
133
- /**
134
- * Resolve encryption key from --key-file or --vault-passphrase / GIT_CAS_PASSPHRASE.
135
- *
136
- * @param {ContentAddressableStore} cas
137
- * @param {Record<string, any>} opts
138
- * @returns {Promise<Buffer | undefined>}
139
- */
140
- async function resolveEncryptionKey(cas, opts) {
141
- if (opts.keyFile) {
142
- return readKeyFile(opts.keyFile);
143
- }
144
- const metadata = await cas.getVaultMetadata();
145
- if (!metadata?.encryption) {
146
- if (hasPassphraseSource(opts)) {
147
- process.stderr.write('warning: passphrase ignored (vault is not encrypted)\n');
148
- }
149
- return undefined;
150
- }
151
- const passphrase = await resolvePassphrase(opts);
152
- if (!passphrase) {
153
- return undefined;
154
- }
155
- return deriveVaultKey(cas, metadata, passphrase);
156
- }
157
-
158
81
  /**
159
82
  * Validate --slug / --oid flags (exactly one required).
160
83
  *
@@ -167,6 +90,17 @@ function validateRestoreFlags(opts) {
167
90
  if (!opts.slug && !opts.oid) {
168
91
  throw new Error('Provide --slug <slug> or --oid <tree-oid>');
169
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();
170
104
  }
171
105
 
172
106
  // ---------------------------------------------------------------------------
@@ -177,8 +111,9 @@ function validateRestoreFlags(opts) {
177
111
  * @typedef {Object} StoreFileOpts
178
112
  * @property {string} filePath - Path to the file to store.
179
113
  * @property {string} slug - Asset slug identifier.
180
- * @property {Buffer} [encryptionKey] - 32-byte AES-256-GCM key.
181
- * @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.
182
117
  */
183
118
 
184
119
  /**
@@ -191,12 +126,17 @@ function validateRestoreFlags(opts) {
191
126
  */
192
127
  async function buildStoreOpts(cas, file, opts) {
193
128
  /** @type {StoreFileOpts} */
194
- const storeOpts = { filePath: file, slug: opts.slug };
129
+ const storeOpts = { filePath: file, slug: Slug.from(opts.slug).toString() };
195
130
  if (opts.recipient) {
196
131
  storeOpts.recipients = opts.recipient;
197
132
  } else {
198
133
  const encryptionKey = await resolveEncryptionKey(cas, opts);
199
- if (encryptionKey) { storeOpts.encryptionKey = encryptionKey; }
134
+ if (encryptionKey) {
135
+ storeOpts.encryptionKey = encryptionKey;
136
+ if (!opts.keyFile) {
137
+ storeOpts.vaultEncryptionKey = encryptionKey;
138
+ }
139
+ }
200
140
  }
201
141
  return storeOpts;
202
142
  }
@@ -206,8 +146,8 @@ async function buildStoreOpts(cas, file, opts) {
206
146
  * Format: label:keyfile
207
147
  *
208
148
  * @param {string} value
209
- * @param {Array<{ label: string, key: Buffer }>} [previous]
210
- * @returns {Array<{ label: string, key: Buffer }>}
149
+ * @param {Array<{ label: string, key: Uint8Array }>} [previous]
150
+ * @returns {Array<{ label: string, key: Uint8Array }>}
211
151
  */
212
152
  function parseRecipient(value, previous) {
213
153
  const sep = value.indexOf(':');
@@ -227,12 +167,21 @@ function parseRecipient(value, previous) {
227
167
 
228
168
  /** @param {string} v */
229
169
  const parseIntFlag = (v) => {
230
- 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
+ }
231
173
  const n = Number(v);
232
- 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
+ }
233
177
  return n;
234
178
  };
235
179
 
180
+ /** @param {boolean} json */
181
+ function shouldSuppressProgress(json) {
182
+ return Boolean(program.opts().quiet || json);
183
+ }
184
+
236
185
  program
237
186
  .command('store <file>')
238
187
  .description('Store a file into Git CAS')
@@ -241,8 +190,19 @@ program
241
190
  .option('--recipient <label:keyfile>', 'Envelope recipient (repeatable)', parseRecipient)
242
191
  .option('--tree', 'Also create a Git tree and print its OID')
243
192
  .option('--force', 'Overwrite existing vault entry')
244
- .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
+ )
245
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
+ )
246
206
  .option('--gzip', 'Enable gzip compression')
247
207
  .addOption(new Option('--strategy <type>', 'Chunking strategy').choices(['fixed', 'cdc']))
248
208
  .option('--chunk-size <n>', 'Chunk size in bytes', parseIntFlag)
@@ -253,37 +213,54 @@ program
253
213
  .option('--max-chunk-size <n>', 'CDC maximum chunk size', parseIntFlag)
254
214
  .option('--merkle-threshold <n>', 'Chunk count threshold for Merkle sub-manifests', parseIntFlag)
255
215
  .option('--cwd <dir>', 'Git working directory', '.')
256
- .action(runAction(async (/** @type {string} */ file, /** @type {Record<string, any>} */ opts) => {
257
- if (opts.recipient && (opts.keyFile || hasPassphraseSource(opts))) {
258
- throw new Error('Provide --key-file or a vault passphrase source (--vault-passphrase, --vault-passphrase-file, GIT_CAS_PASSPHRASE), or --recipient — not both');
259
- }
260
- if (opts.force && !opts.tree) {
261
- throw new Error('--force requires --tree');
262
- }
263
- const json = program.opts().json;
264
- const quiet = program.opts().quiet || json;
265
- const observer = new EventEmitterObserver();
266
-
267
- const config = loadConfig(opts.cwd);
268
- const { casConfig, storeExtras } = mergeConfig(opts, config);
269
- const cas = createCas(opts.cwd, { observability: observer, ...casConfig });
270
-
271
- const storeOpts = await buildStoreOpts(cas, file, opts);
272
- Object.assign(storeOpts, storeExtras);
273
- const progress = createStoreProgress({ filePath: file, chunkSize: cas.chunkSize, quiet });
274
- progress.attach(observer);
275
- let manifest;
276
- try { manifest = await cas.storeFile(storeOpts); } finally { progress.detach(); }
277
-
278
- if (opts.tree) {
279
- const treeOid = await cas.createTree({ manifest });
280
- await cas.addToVault({ slug: opts.slug, treeOid, force: !!opts.force });
281
- process.stdout.write(json ? `${JSON.stringify({ treeOid })}\n` : `${treeOid}\n`);
282
- } else {
283
- const output = json ? JSON.stringify({ manifest: manifest.toJSON() }) : JSON.stringify(manifest.toJSON(), null, 2);
284
- process.stdout.write(`${output}\n`);
285
- }
286
- }, 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
+ );
287
264
 
288
265
  // ---------------------------------------------------------------------------
289
266
  // tree
@@ -293,18 +270,20 @@ program
293
270
  .description('Create a Git tree from a manifest')
294
271
  .requiredOption('--manifest <path>', 'Path to manifest JSON file')
295
272
  .option('--cwd <dir>', 'Git working directory', '.')
296
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
297
- const cas = createCas(opts.cwd);
298
- const raw = readFileSync(opts.manifest, 'utf8');
299
- const manifest = new Manifest(JSON.parse(raw));
300
- const treeOid = await cas.createTree({ manifest });
301
- const json = program.opts().json;
302
- if (json) {
303
- process.stdout.write(`${JSON.stringify({ treeOid })}\n`);
304
- } else {
305
- process.stdout.write(`${treeOid}\n`);
306
- }
307
- }, 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
+ );
308
287
 
309
288
  // ---------------------------------------------------------------------------
310
289
  // inspect
@@ -316,23 +295,25 @@ program
316
295
  .option('--oid <tree-oid>', 'Direct tree OID')
317
296
  .option('--heatmap', 'Show chunk heatmap visualization')
318
297
  .option('--cwd <dir>', 'Git working directory', '.')
319
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
320
- validateRestoreFlags(opts);
321
- const cas = createCas(opts.cwd);
322
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
323
- const manifest = await cas.readManifest({ treeOid });
324
- const json = program.opts().json;
325
-
326
- if (json) {
327
- process.stdout.write(`${JSON.stringify(manifest.toJSON())}\n`);
328
- } else if (opts.heatmap) {
329
- process.stdout.write(renderHeatmap({ manifest }));
330
- } else if (process.stdout.isTTY) {
331
- process.stdout.write(renderManifestView({ manifest }));
332
- } else {
333
- process.stdout.write(`${JSON.stringify(manifest.toJSON(), null, 2)}\n`);
334
- }
335
- }, 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
+ );
336
317
 
337
318
  // ---------------------------------------------------------------------------
338
319
  // restore
@@ -344,51 +325,77 @@ program
344
325
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
345
326
  .option('--oid <tree-oid>', 'Direct tree OID')
346
327
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
347
- .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
+ )
348
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
+ )
349
341
  .option('--concurrency <n>', 'Parallel chunk I/O operations', parseIntFlag)
350
- .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
+ )
351
347
  .option('--cwd <dir>', 'Git working directory', '.')
352
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
353
- validateRestoreFlags(opts);
354
- const quiet = program.opts().quiet || program.opts().json;
355
- const observer = new EventEmitterObserver();
356
-
357
- const config = loadConfig(opts.cwd);
358
- /** @type {Record<string, any>} */
359
- const casConfig = {};
360
- const concurrency = opts.concurrency ?? config.concurrency;
361
- const maxRestoreBufferSize = opts.maxRestoreBuffer ?? config.maxRestoreBufferSize;
362
- if (concurrency !== undefined) { casConfig.concurrency = concurrency; }
363
- if (maxRestoreBufferSize !== undefined) { casConfig.maxRestoreBufferSize = maxRestoreBufferSize; }
364
-
365
- const cas = createCas(opts.cwd, { observability: observer, ...casConfig });
366
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
367
- const manifest = await cas.readManifest({ treeOid });
368
-
369
- 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
+ }
370
367
 
371
- const progress = createRestoreProgress({
372
- totalChunks: manifest.chunks.length, quiet,
373
- });
374
- progress.attach(observer);
375
- let bytesWritten;
376
- try {
377
- ({ bytesWritten } = await cas.restoreFile({
378
- manifest,
379
- ...(encryptionKey ? { encryptionKey } : {}),
380
- outputPath: opts.out,
381
- }));
382
- } finally {
383
- progress.detach();
384
- }
385
- const json = program.opts().json;
386
- if (json) {
387
- process.stdout.write(`${JSON.stringify({ bytesWritten })}\n`);
388
- } else {
389
- process.stdout.write(`${bytesWritten}\n`);
390
- }
391
- }, 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
+ );
392
399
 
393
400
  // ---------------------------------------------------------------------------
394
401
  // verify
@@ -399,54 +406,121 @@ program
399
406
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
400
407
  .option('--oid <tree-oid>', 'Direct tree OID')
401
408
  .option('--cwd <dir>', 'Git working directory', '.')
402
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
403
- validateRestoreFlags(opts);
404
- const cas = createCas(opts.cwd);
405
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
406
- const manifest = await cas.readManifest({ treeOid });
407
- const ok = await cas.verifyIntegrity(manifest);
408
- const json = program.opts().json;
409
- if (json) {
410
- process.stdout.write(`${JSON.stringify({ ok, slug: manifest.slug, chunks: manifest.chunks.length })}\n`);
411
- } else {
412
- process.stdout.write(ok ? 'ok\n' : `fail: ${manifest.slug}\n`);
413
- }
414
- if (!ok) {
415
- process.exitCode = 1;
416
- }
417
- }, 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
+ );
418
472
 
419
473
  // ---------------------------------------------------------------------------
420
474
  // vault init
421
475
  // ---------------------------------------------------------------------------
422
- const vault = program
423
- .command('vault')
424
- .description('Manage the CAS vault');
476
+ const vault = program.command('vault').description('Manage the CAS vault');
425
477
 
426
478
  vault
427
479
  .command('init')
428
480
  .description('Initialize the vault')
429
- .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
+ )
430
485
  .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
431
- .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']))
432
495
  .option('--cwd <dir>', 'Git working directory', '.')
433
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
434
- const cas = createCas(opts.cwd);
435
- /** @type {{ passphrase?: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
436
- const initOpts = {};
437
- const passphrase = await resolvePassphrase(opts, { confirm: true });
438
- if (passphrase) {
439
- initOpts.passphrase = passphrase;
440
- initOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
441
- }
442
- const { commitOid } = await cas.initVault(initOpts);
443
- const json = program.opts().json;
444
- if (json) {
445
- process.stdout.write(`${JSON.stringify({ commitOid })}\n`);
446
- } else {
447
- process.stdout.write(`${commitOid}\n`);
448
- }
449
- }, 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
+ );
450
524
 
451
525
  // ---------------------------------------------------------------------------
452
526
  // vault list
@@ -456,19 +530,49 @@ vault
456
530
  .description('List vault entries')
457
531
  .option('--filter <pattern>', 'Filter entries by glob pattern')
458
532
  .option('--cwd <dir>', 'Git working directory', '.')
459
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
460
- const cas = createCas(opts.cwd);
461
- const all = await cas.listVault();
462
- const entries = filterEntries(all, opts.filter);
463
- const json = program.opts().json;
464
- if (json) {
465
- process.stdout.write(`${JSON.stringify(entries)}\n`);
466
- } else if (process.stdout.isTTY) {
467
- process.stdout.write(formatTable(entries));
468
- } else {
469
- process.stdout.write(formatTabSeparated(entries));
470
- }
471
- }, 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
+ );
472
576
 
473
577
  // ---------------------------------------------------------------------------
474
578
  // vault remove
@@ -477,16 +581,19 @@ vault
477
581
  .command('remove <slug>')
478
582
  .description('Remove an entry from the vault')
479
583
  .option('--cwd <dir>', 'Git working directory', '.')
480
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
481
- const cas = createCas(opts.cwd);
482
- const { commitOid, removedTreeOid } = await cas.removeFromVault({ slug });
483
- const json = program.opts().json;
484
- if (json) {
485
- process.stdout.write(`${JSON.stringify({ commitOid, removedTreeOid })}\n`);
486
- } else {
487
- process.stdout.write(`${removedTreeOid}\n`);
488
- }
489
- }, 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
+ );
490
597
 
491
598
  // ---------------------------------------------------------------------------
492
599
  // vault info
@@ -496,29 +603,32 @@ vault
496
603
  .description('Show info for a vault entry')
497
604
  .option('--encryption', 'Show vault encryption details')
498
605
  .option('--cwd <dir>', 'Git working directory', '.')
499
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
500
- const cas = createCas(opts.cwd);
501
- const treeOid = await cas.resolveVaultEntry({ slug });
502
- const json = program.opts().json;
503
- if (json) {
504
- /** @type {Record<string, any>} */
505
- const result = { slug, treeOid };
506
- if (opts.encryption) {
507
- const metadata = await cas.getVaultMetadata();
508
- if (metadata?.encryption) {
509
- 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`);
510
628
  }
511
629
  }
512
- process.stdout.write(`${JSON.stringify(result)}\n`);
513
- } else {
514
- process.stdout.write(`slug\t${slug}\n`);
515
- process.stdout.write(`tree\t${treeOid}\n`);
516
- if (opts.encryption) {
517
- const metadata = await cas.getVaultMetadata();
518
- process.stdout.write(`\n${renderEncryptionCard({ metadata })}\n`);
519
- }
520
- }
521
- }, getJson));
630
+ }, getJson)
631
+ );
522
632
 
523
633
  // ---------------------------------------------------------------------------
524
634
  // vault history
@@ -529,34 +639,35 @@ vault
529
639
  .option('--cwd <dir>', 'Git working directory', '.')
530
640
  .option('-n, --max-count <n>', 'Limit number of commits')
531
641
  .option('--pretty', 'Render as color-coded timeline')
532
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
533
- const runner = ShellRunnerFactory.create();
534
- const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
535
- const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
536
- if (opts.maxCount) {
537
- const n = parseInt(opts.maxCount, 10);
538
- if (Number.isNaN(n) || n <= 0) {
539
- throw new Error('--max-count must be a positive integer');
540
- }
541
- args.push(`-${n}`);
542
- }
543
- const output = await plumbing.execute({ args });
544
- const json = program.opts().json;
545
- if (json) {
546
- const history = output
547
- .split('\n')
548
- .filter(Boolean)
549
- .map((/** @type {string} */ line) => {
550
- const [commitOid, ...messageParts] = line.trim().split(/\s+/);
551
- return { commitOid, message: messageParts.join(' ') };
552
- });
553
- process.stdout.write(`${JSON.stringify(history)}\n`);
554
- } else if (opts.pretty && process.stdout.isTTY) {
555
- process.stdout.write(`${renderHistoryTimeline(output)}\n`);
556
- } else {
557
- process.stdout.write(`${output}\n`);
558
- }
559
- }, 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
+ );
560
671
 
561
672
  // ---------------------------------------------------------------------------
562
673
  // vault rotate
@@ -577,58 +688,80 @@ async function resolveRotatePassphrases(opts) {
577
688
  const newPassphrase = opts.newPassphraseFile
578
689
  ? await readPassphraseFile(opts.newPassphraseFile)
579
690
  : opts.newPassphrase;
580
- if (!oldPassphrase) { throw new Error('Old passphrase required (--old-passphrase or --old-passphrase-file)'); }
581
- 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
+ }
582
697
  return { oldPassphrase, newPassphrase };
583
698
  }
584
699
 
585
700
  vault
586
701
  .command('rotate')
587
702
  .description('Rotate vault-level encryption passphrase')
588
- .option('--old-passphrase <pass>', 'Current vault passphrase')
589
- .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 -)')
590
705
  .option('--old-passphrase-file <path>', 'Read old passphrase from file (- for stdin)')
591
706
  .option('--new-passphrase-file <path>', 'Read new passphrase from file (- for stdin)')
592
707
  .addOption(new Option('--algorithm <alg>', 'KDF algorithm').choices(['pbkdf2', 'scrypt']))
593
708
  .option('--cwd <dir>', 'Git working directory', '.')
594
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
595
- const { oldPassphrase, newPassphrase } = await resolveRotatePassphrases(opts);
596
- const cas = createCas(opts.cwd);
597
- /** @type {{ oldPassphrase: string, newPassphrase: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
598
- const rotateOpts = {
599
- oldPassphrase,
600
- newPassphrase,
601
- };
602
- if (opts.algorithm) {
603
- rotateOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
604
- }
605
- const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase(rotateOpts);
606
- const json = program.opts().json;
607
- if (json) {
608
- process.stdout.write(`${JSON.stringify({ commitOid, rotatedSlugs, skippedSlugs })}\n`);
609
- } else {
610
- process.stdout.write(`${commitOid}\n`);
611
- if (rotatedSlugs.length) {
612
- process.stderr.write(`rotated: ${rotatedSlugs.join(', ')}\n`);
613
- }
614
- if (skippedSlugs.length) {
615
- 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) };
616
721
  }
617
- }
618
- }, 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
+ );
619
737
 
620
738
  // ---------------------------------------------------------------------------
621
739
  // vault dashboard
622
740
  // ---------------------------------------------------------------------------
623
741
  vault
624
742
  .command('dashboard')
625
- .description('Interactive vault explorer')
743
+ .description('Interactive CAS explorer')
626
744
  .option('--cwd <dir>', 'Git working directory', '.')
627
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
628
- const cas = createCas(opts.cwd);
629
- const { launchDashboard } = await import('./ui/dashboard.js');
630
- await launchDashboard(cas);
631
- }, 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
+ );
632
765
 
633
766
  // ---------------------------------------------------------------------------
634
767
  // rotate
@@ -642,43 +775,47 @@ program
642
775
  .requiredOption('--new-key-file <path>', 'Path to new 32-byte key file')
643
776
  .option('--label <label>', 'Rotate only the named recipient')
644
777
  .option('--cwd <dir>', 'Git working directory', '.')
645
- .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
646
- validateRestoreFlags(opts);
647
- const cas = createCas(opts.cwd);
648
- const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
649
- const manifest = await cas.readManifest({ treeOid });
650
-
651
- const oldKey = readKeyFile(opts.oldKeyFile);
652
- const newKey = readKeyFile(opts.newKeyFile);
653
-
654
- /** @type {{ manifest: Manifest, oldKey: Buffer, newKey: Buffer, label?: string }} */
655
- const rotateOpts = { manifest, oldKey, newKey };
656
- if (opts.label) { rotateOpts.label = opts.label; }
657
-
658
- const updated = await cas.rotateKey(rotateOpts);
659
- 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
+ }
660
793
 
661
- if (opts.slug) {
662
- const newTreeOid = await cas.createTree({ manifest: updated });
663
- await cas.addToVault({ slug: opts.slug, treeOid: newTreeOid, force: true });
664
- if (json) {
665
- 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`);
666
809
  } else {
667
- process.stdout.write(`${newTreeOid}\n`);
810
+ process.stdout.write(`${JSON.stringify(updated.toJSON(), null, 2)}\n`);
668
811
  }
669
- } else if (json) {
670
- process.stdout.write(`${JSON.stringify(updated.toJSON())}\n`);
671
- } else {
672
- process.stdout.write(`${JSON.stringify(updated.toJSON(), null, 2)}\n`);
673
- }
674
- }, getJson));
812
+ }, getJson)
813
+ );
675
814
 
676
815
  // ---------------------------------------------------------------------------
677
816
  // recipient add / remove / list
678
817
  // ---------------------------------------------------------------------------
679
- const recipient = program
680
- .command('recipient')
681
- .description('Manage envelope encryption recipients');
818
+ const recipient = program.command('recipient').description('Manage envelope encryption recipients');
682
819
 
683
820
  recipient
684
821
  .command('add <slug>')
@@ -687,74 +824,83 @@ recipient
687
824
  .requiredOption('--key-file <path>', 'Path to 32-byte key file for the new recipient')
688
825
  .requiredOption('--existing-key-file <path>', 'Path to key file of an existing recipient')
689
826
  .option('--cwd <dir>', 'Git working directory', '.')
690
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
691
- const cas = createCas(opts.cwd);
692
- const treeOid = await cas.resolveVaultEntry({ slug });
693
- const manifest = await cas.readManifest({ treeOid });
694
-
695
- const existingKey = readKeyFile(opts.existingKeyFile);
696
- const newRecipientKey = readKeyFile(opts.keyFile);
697
-
698
- const updated = await cas.addRecipient({
699
- manifest,
700
- existingKey,
701
- newRecipientKey,
702
- label: opts.label,
703
- });
704
-
705
- const newTreeOid = await cas.createTree({ manifest: updated });
706
- await cas.addToVault({ slug, treeOid: newTreeOid, force: true });
707
-
708
- const json = program.opts().json;
709
- if (json) {
710
- process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
711
- } else {
712
- process.stdout.write(`${newTreeOid}\n`);
713
- }
714
- }, 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
+ );
715
855
 
716
856
  recipient
717
857
  .command('remove <slug>')
718
858
  .description('Remove a recipient from an envelope-encrypted asset')
719
859
  .requiredOption('--label <label>', 'Label of the recipient to remove')
720
860
  .option('--cwd <dir>', 'Git working directory', '.')
721
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
722
- const cas = createCas(opts.cwd);
723
- const treeOid = await cas.resolveVaultEntry({ slug });
724
- 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 });
725
867
 
726
- const updated = await cas.removeRecipient({ manifest, label: opts.label });
868
+ const updated = await cas.removeRecipient({ manifest, label: opts.label });
727
869
 
728
- const newTreeOid = await cas.createTree({ manifest: updated });
729
- 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 });
730
872
 
731
- const json = program.opts().json;
732
- if (json) {
733
- process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid })}\n`);
734
- } else {
735
- process.stdout.write(`${newTreeOid}\n`);
736
- }
737
- }, 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
+ );
738
881
 
739
882
  recipient
740
883
  .command('list <slug>')
741
884
  .description('List recipients of an envelope-encrypted asset')
742
885
  .option('--cwd <dir>', 'Git working directory', '.')
743
- .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
744
- const cas = createCas(opts.cwd);
745
- const treeOid = await cas.resolveVaultEntry({ slug });
746
- const manifest = await cas.readManifest({ treeOid });
747
-
748
- const labels = await cas.listRecipients(manifest);
749
- const json = program.opts().json;
750
- if (json) {
751
- process.stdout.write(`${JSON.stringify(labels)}\n`);
752
- } else {
753
- for (const label of labels) {
754
- 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
+ }
755
901
  }
756
- }
757
- }, getJson));
902
+ }, getJson)
903
+ );
758
904
 
759
905
  await program.parseAsync();
760
906