@git-stunts/git-cas 5.2.1 → 5.3.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 (46) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/README.md +67 -5
  3. package/bin/actions.js +38 -8
  4. package/bin/config.js +203 -0
  5. package/bin/git-cas.js +200 -54
  6. package/bin/ui/context.js +13 -0
  7. package/bin/ui/dashboard-cmds.js +14 -6
  8. package/bin/ui/dashboard-view.js +55 -6
  9. package/bin/ui/dashboard.js +109 -7
  10. package/bin/ui/encryption-card.js +2 -2
  11. package/bin/ui/heatmap.js +20 -2
  12. package/bin/ui/history-timeline.js +8 -6
  13. package/bin/ui/manifest-view.js +37 -8
  14. package/bin/ui/passphrase-prompt.js +100 -0
  15. package/bin/ui/progress.js +60 -38
  16. package/index.d.ts +20 -1
  17. package/index.js +74 -218
  18. package/package.json +2 -1
  19. package/src/domain/errors/CasError.js +3 -1
  20. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  21. package/src/domain/services/CasService.d.ts +21 -1
  22. package/src/domain/services/CasService.js +134 -228
  23. package/src/domain/services/KeyResolver.js +220 -0
  24. package/src/domain/services/Semaphore.js +2 -2
  25. package/src/domain/services/VaultService.js +72 -29
  26. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  27. package/src/infrastructure/adapters/BunCryptoAdapter.js +38 -6
  28. package/src/infrastructure/adapters/EventEmitterObserver.js +19 -7
  29. package/src/infrastructure/adapters/FileIOHelper.js +64 -0
  30. package/src/infrastructure/adapters/GitPersistenceAdapter.js +21 -5
  31. package/src/infrastructure/adapters/GitRefAdapter.js +27 -5
  32. package/src/infrastructure/adapters/NodeCryptoAdapter.js +49 -8
  33. package/src/infrastructure/adapters/SilentObserver.js +15 -0
  34. package/src/infrastructure/adapters/StatsCollector.js +15 -1
  35. package/src/infrastructure/adapters/WebCryptoAdapter.js +120 -42
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/CdcChunker.js +5 -0
  38. package/src/infrastructure/chunkers/FixedChunker.js +28 -8
  39. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  40. package/src/infrastructure/codecs/CborCodec.js +11 -3
  41. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  42. package/src/ports/CodecPort.js +3 -3
  43. package/src/ports/CryptoPort.js +56 -23
  44. package/src/ports/GitPersistencePort.js +4 -4
  45. package/src/ports/GitRefPort.js +10 -10
  46. package/src/types/ambient.d.ts +37 -0
package/bin/git-cas.js CHANGED
@@ -1,9 +1,9 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { readFileSync } from 'node:fs';
4
- import { program } from 'commander';
4
+ import { program, Option } from 'commander';
5
5
  import GitPlumbing, { ShellRunnerFactory } from '@git-stunts/plumbing';
6
- import ContentAddressableStore, { EventEmitterObserver } from '../index.js';
6
+ import ContentAddressableStore, { EventEmitterObserver, CborCodec } from '../index.js';
7
7
  import Manifest from '../src/domain/value-objects/Manifest.js';
8
8
  import { createStoreProgress, createRestoreProgress } from './ui/progress.js';
9
9
  import { renderEncryptionCard } from './ui/encryption-card.js';
@@ -12,41 +12,67 @@ import { renderManifestView } from './ui/manifest-view.js';
12
12
  import { renderHeatmap } from './ui/heatmap.js';
13
13
  import { runAction } from './actions.js';
14
14
  import { filterEntries, formatTable, formatTabSeparated } from './ui/vault-list.js';
15
+ import { readPassphraseFile, promptPassphrase } from './ui/passphrase-prompt.js';
16
+ import { loadConfig, mergeConfig } from './config.js';
15
17
 
16
18
  const getJson = () => program.opts().json;
17
19
 
18
20
  program
19
21
  .name('git-cas')
20
22
  .description('Content Addressable Storage backed by Git')
21
- .version('5.2.1')
23
+ .version('5.2.2')
22
24
  .option('-q, --quiet', 'Suppress progress output')
23
25
  .option('--json', 'Output results as JSON');
24
26
 
25
27
  /**
26
28
  * Read a 32-byte raw encryption key from a file.
29
+ *
30
+ * @param {string} keyFilePath
31
+ * @returns {Buffer}
27
32
  */
28
33
  function readKeyFile(keyFilePath) {
29
- return readFileSync(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;
30
39
  }
31
40
 
32
41
  /**
33
- * Create a CAS instance for the given working directory with an optional observability adapter.
42
+ * Create a CAS instance for the given working directory.
43
+ *
44
+ * @param {string} cwd
45
+ * @param {Record<string, any>} [opts]
46
+ * @returns {ContentAddressableStore}
34
47
  */
35
- function createCas(cwd, { observability } = {}) {
48
+ function createCas(cwd, opts = {}) {
36
49
  const runner = ShellRunnerFactory.create();
37
50
  const plumbing = new GitPlumbing({ runner, cwd });
38
- return new ContentAddressableStore({ plumbing, observability });
51
+ /** @type {Record<string, any>} */
52
+ const casOpts = { plumbing, ...opts };
53
+ if (casOpts.codec === 'cbor') {
54
+ casOpts.codec = new CborCodec();
55
+ }
56
+ return new ContentAddressableStore(casOpts);
39
57
  }
40
58
 
41
59
  /**
42
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>}
43
66
  */
44
67
  async function deriveVaultKey(cas, metadata, passphrase) {
68
+ if (!metadata.encryption?.kdf) {
69
+ throw new Error('Missing or malformed encryption metadata');
70
+ }
45
71
  const { kdf } = metadata.encryption;
46
72
  const { key } = await cas.deriveKey({
47
73
  passphrase,
48
74
  salt: Buffer.from(kdf.salt, 'base64'),
49
- algorithm: kdf.algorithm,
75
+ algorithm: /** @type {"pbkdf2" | "scrypt"} */ (kdf.algorithm),
50
76
  iterations: kdf.iterations,
51
77
  cost: kdf.cost,
52
78
  blockSize: kdf.blockSize,
@@ -56,33 +82,74 @@ async function deriveVaultKey(cas, metadata, passphrase) {
56
82
  }
57
83
 
58
84
  /**
59
- * Resolve passphrase from --vault-passphrase flag or GIT_CAS_PASSPHRASE env var.
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}
60
90
  */
61
- function resolvePassphrase(opts) {
62
- return opts.vaultPassphrase ?? process.env.GIT_CAS_PASSPHRASE;
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;
63
122
  }
64
123
 
65
124
  /**
66
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>}
67
130
  */
68
131
  async function resolveEncryptionKey(cas, opts) {
69
132
  if (opts.keyFile) {
70
133
  return readKeyFile(opts.keyFile);
71
134
  }
72
- const passphrase = resolvePassphrase(opts);
73
- if (!passphrase) {
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
+ }
74
140
  return undefined;
75
141
  }
76
- const metadata = await cas.getVaultMetadata();
77
- if (metadata?.encryption) {
78
- return deriveVaultKey(cas, metadata, passphrase);
142
+ const passphrase = await resolvePassphrase(opts);
143
+ if (!passphrase) {
144
+ return undefined;
79
145
  }
80
- process.stderr.write('warning: passphrase ignored (vault is not encrypted)\n');
81
- return undefined;
146
+ return deriveVaultKey(cas, metadata, passphrase);
82
147
  }
83
148
 
84
149
  /**
85
150
  * Validate --slug / --oid flags (exactly one required).
151
+ *
152
+ * @param {Record<string, any>} opts
86
153
  */
87
154
  function validateRestoreFlags(opts) {
88
155
  if (opts.slug && opts.oid) {
@@ -96,10 +163,25 @@ function validateRestoreFlags(opts) {
96
163
  // ---------------------------------------------------------------------------
97
164
  // store
98
165
  // ---------------------------------------------------------------------------
166
+
167
+ /**
168
+ * @typedef {Object} StoreFileOpts
169
+ * @property {string} filePath - Path to the file to store.
170
+ * @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.
173
+ */
174
+
99
175
  /**
100
176
  * Build store options, resolving encryption key or recipients.
177
+ *
178
+ * @param {ContentAddressableStore} cas
179
+ * @param {string} file
180
+ * @param {Record<string, any>} opts
181
+ * @returns {Promise<StoreFileOpts>}
101
182
  */
102
183
  async function buildStoreOpts(cas, file, opts) {
184
+ /** @type {StoreFileOpts} */
103
185
  const storeOpts = { filePath: file, slug: opts.slug };
104
186
  if (opts.recipient) {
105
187
  storeOpts.recipients = opts.recipient;
@@ -113,6 +195,10 @@ async function buildStoreOpts(cas, file, opts) {
113
195
  /**
114
196
  * Parse a --recipient flag value into { label, key }.
115
197
  * Format: label:keyfile
198
+ *
199
+ * @param {string} value
200
+ * @param {Array<{ label: string, key: Buffer }>} [previous]
201
+ * @returns {Array<{ label: string, key: Buffer }>}
116
202
  */
117
203
  function parseRecipient(value, previous) {
118
204
  const sep = value.indexOf(':');
@@ -130,6 +216,14 @@ function parseRecipient(value, previous) {
130
216
  return list;
131
217
  }
132
218
 
219
+ /** @param {string} v */
220
+ const parseIntFlag = (v) => {
221
+ if (!/^-?\d+$/.test(v)) { throw new Error(`Expected an integer, got "${v}"`); }
222
+ const n = Number(v);
223
+ if (!Number.isSafeInteger(n)) { throw new Error(`Expected a safe integer, got "${v}"`); }
224
+ return n;
225
+ };
226
+
133
227
  program
134
228
  .command('store <file>')
135
229
  .description('Store a file into Git CAS')
@@ -139,10 +233,20 @@ program
139
233
  .option('--tree', 'Also create a Git tree and print its OID')
140
234
  .option('--force', 'Overwrite existing vault entry')
141
235
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for encryption (prefer GIT_CAS_PASSPHRASE env var)')
236
+ .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
237
+ .option('--gzip', 'Enable gzip compression')
238
+ .addOption(new Option('--strategy <type>', 'Chunking strategy').choices(['fixed', 'cdc']))
239
+ .option('--chunk-size <n>', 'Chunk size in bytes', parseIntFlag)
240
+ .option('--concurrency <n>', 'Parallel chunk I/O operations', parseIntFlag)
241
+ .addOption(new Option('--codec <type>', 'Manifest codec').choices(['json', 'cbor']))
242
+ .option('--target-chunk-size <n>', 'CDC target chunk size', parseIntFlag)
243
+ .option('--min-chunk-size <n>', 'CDC minimum chunk size', parseIntFlag)
244
+ .option('--max-chunk-size <n>', 'CDC maximum chunk size', parseIntFlag)
245
+ .option('--merkle-threshold <n>', 'Chunk count threshold for Merkle sub-manifests', parseIntFlag)
142
246
  .option('--cwd <dir>', 'Git working directory', '.')
143
- .action(runAction(async (file, opts) => {
144
- if (opts.recipient && (opts.keyFile || resolvePassphrase(opts))) {
145
- throw new Error('Provide --key-file/--vault-passphrase or --recipient, not both');
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');
146
250
  }
147
251
  if (opts.force && !opts.tree) {
148
252
  throw new Error('--force requires --tree');
@@ -150,9 +254,13 @@ program
150
254
  const json = program.opts().json;
151
255
  const quiet = program.opts().quiet || json;
152
256
  const observer = new EventEmitterObserver();
153
- const cas = createCas(opts.cwd, { observability: observer });
257
+
258
+ const config = loadConfig(opts.cwd);
259
+ const { casConfig, storeExtras } = mergeConfig(opts, config);
260
+ const cas = createCas(opts.cwd, { observability: observer, ...casConfig });
154
261
 
155
262
  const storeOpts = await buildStoreOpts(cas, file, opts);
263
+ Object.assign(storeOpts, storeExtras);
156
264
  const progress = createStoreProgress({ filePath: file, chunkSize: cas.chunkSize, quiet });
157
265
  progress.attach(observer);
158
266
  let manifest;
@@ -176,7 +284,7 @@ program
176
284
  .description('Create a Git tree from a manifest')
177
285
  .requiredOption('--manifest <path>', 'Path to manifest JSON file')
178
286
  .option('--cwd <dir>', 'Git working directory', '.')
179
- .action(runAction(async (opts) => {
287
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
180
288
  const cas = createCas(opts.cwd);
181
289
  const raw = readFileSync(opts.manifest, 'utf8');
182
290
  const manifest = new Manifest(JSON.parse(raw));
@@ -199,7 +307,7 @@ program
199
307
  .option('--oid <tree-oid>', 'Direct tree OID')
200
308
  .option('--heatmap', 'Show chunk heatmap visualization')
201
309
  .option('--cwd <dir>', 'Git working directory', '.')
202
- .action(runAction(async (opts) => {
310
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
203
311
  validateRestoreFlags(opts);
204
312
  const cas = createCas(opts.cwd);
205
313
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
@@ -228,20 +336,28 @@ program
228
336
  .option('--oid <tree-oid>', 'Direct tree OID')
229
337
  .option('--key-file <path>', 'Path to 32-byte raw encryption key file')
230
338
  .option('--vault-passphrase <pass>', 'Vault-level passphrase for decryption (prefer GIT_CAS_PASSPHRASE env var)')
339
+ .option('--vault-passphrase-file <path>', 'Read vault passphrase from file (use - for stdin)')
340
+ .option('--concurrency <n>', 'Parallel chunk I/O operations', parseIntFlag)
341
+ .option('--max-restore-buffer <n>', 'Max bytes for buffered encrypted/compressed restore', parseIntFlag)
231
342
  .option('--cwd <dir>', 'Git working directory', '.')
232
- .action(runAction(async (opts) => {
343
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
233
344
  validateRestoreFlags(opts);
234
345
  const quiet = program.opts().quiet || program.opts().json;
235
346
  const observer = new EventEmitterObserver();
236
- const cas = createCas(opts.cwd, { observability: observer });
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 });
237
357
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
238
358
  const manifest = await cas.readManifest({ treeOid });
239
359
 
240
- const restoreOpts = { manifest };
241
360
  const encryptionKey = await resolveEncryptionKey(cas, opts);
242
- if (encryptionKey) {
243
- restoreOpts.encryptionKey = encryptionKey;
244
- }
245
361
 
246
362
  const progress = createRestoreProgress({
247
363
  totalChunks: manifest.chunks.length, quiet,
@@ -250,7 +366,8 @@ program
250
366
  let bytesWritten;
251
367
  try {
252
368
  ({ bytesWritten } = await cas.restoreFile({
253
- ...restoreOpts,
369
+ manifest,
370
+ ...(encryptionKey ? { encryptionKey } : {}),
254
371
  outputPath: opts.out,
255
372
  }));
256
373
  } finally {
@@ -273,7 +390,7 @@ program
273
390
  .option('--slug <slug>', 'Resolve tree OID from vault slug')
274
391
  .option('--oid <tree-oid>', 'Direct tree OID')
275
392
  .option('--cwd <dir>', 'Git working directory', '.')
276
- .action(runAction(async (opts) => {
393
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
277
394
  validateRestoreFlags(opts);
278
395
  const cas = createCas(opts.cwd);
279
396
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
@@ -301,15 +418,17 @@ vault
301
418
  .command('init')
302
419
  .description('Initialize the vault')
303
420
  .option('--vault-passphrase <pass>', 'Passphrase for vault-level encryption (prefer GIT_CAS_PASSPHRASE env var)')
304
- .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)', 'pbkdf2')
421
+ .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'))
305
423
  .option('--cwd <dir>', 'Git working directory', '.')
306
- .action(runAction(async (opts) => {
424
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
307
425
  const cas = createCas(opts.cwd);
426
+ /** @type {{ passphrase?: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
308
427
  const initOpts = {};
309
- const passphrase = resolvePassphrase(opts);
428
+ const passphrase = await resolvePassphrase(opts, { confirm: true });
310
429
  if (passphrase) {
311
430
  initOpts.passphrase = passphrase;
312
- initOpts.kdfOptions = { algorithm: opts.algorithm };
431
+ initOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
313
432
  }
314
433
  const { commitOid } = await cas.initVault(initOpts);
315
434
  const json = program.opts().json;
@@ -328,7 +447,7 @@ vault
328
447
  .description('List vault entries')
329
448
  .option('--filter <pattern>', 'Filter entries by glob pattern')
330
449
  .option('--cwd <dir>', 'Git working directory', '.')
331
- .action(runAction(async (opts) => {
450
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
332
451
  const cas = createCas(opts.cwd);
333
452
  const all = await cas.listVault();
334
453
  const entries = filterEntries(all, opts.filter);
@@ -349,7 +468,7 @@ vault
349
468
  .command('remove <slug>')
350
469
  .description('Remove an entry from the vault')
351
470
  .option('--cwd <dir>', 'Git working directory', '.')
352
- .action(runAction(async (slug, opts) => {
471
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
353
472
  const cas = createCas(opts.cwd);
354
473
  const { commitOid, removedTreeOid } = await cas.removeFromVault({ slug });
355
474
  const json = program.opts().json;
@@ -368,11 +487,12 @@ vault
368
487
  .description('Show info for a vault entry')
369
488
  .option('--encryption', 'Show vault encryption details')
370
489
  .option('--cwd <dir>', 'Git working directory', '.')
371
- .action(runAction(async (slug, opts) => {
490
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
372
491
  const cas = createCas(opts.cwd);
373
492
  const treeOid = await cas.resolveVaultEntry({ slug });
374
493
  const json = program.opts().json;
375
494
  if (json) {
495
+ /** @type {Record<string, any>} */
376
496
  const result = { slug, treeOid };
377
497
  if (opts.encryption) {
378
498
  const metadata = await cas.getVaultMetadata();
@@ -400,7 +520,7 @@ vault
400
520
  .option('--cwd <dir>', 'Git working directory', '.')
401
521
  .option('-n, --max-count <n>', 'Limit number of commits')
402
522
  .option('--pretty', 'Render as color-coded timeline')
403
- .action(runAction(async (opts) => {
523
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
404
524
  const runner = ShellRunnerFactory.create();
405
525
  const plumbing = new GitPlumbing({ runner, cwd: opts.cwd || '.' });
406
526
  const args = ['log', '--oneline', ContentAddressableStore.VAULT_REF];
@@ -417,7 +537,7 @@ vault
417
537
  const history = output
418
538
  .split('\n')
419
539
  .filter(Boolean)
420
- .map((line) => {
540
+ .map((/** @type {string} */ line) => {
421
541
  const [commitOid, ...messageParts] = line.trim().split(/\s+/);
422
542
  return { commitOid, message: messageParts.join(' ') };
423
543
  });
@@ -432,21 +552,46 @@ vault
432
552
  // ---------------------------------------------------------------------------
433
553
  // vault rotate
434
554
  // ---------------------------------------------------------------------------
555
+ /**
556
+ * Resolve old and new passphrases for vault rotate from flags/files.
557
+ *
558
+ * @param {Record<string, any>} opts
559
+ * @returns {Promise<{ oldPassphrase: string, newPassphrase: string }>}
560
+ */
561
+ async function resolveRotatePassphrases(opts) {
562
+ if (opts.oldPassphraseFile === '-' && opts.newPassphraseFile === '-') {
563
+ throw new Error('Cannot read both old and new passphrase from stdin');
564
+ }
565
+ const oldPassphrase = opts.oldPassphraseFile
566
+ ? await readPassphraseFile(opts.oldPassphraseFile)
567
+ : opts.oldPassphrase;
568
+ const newPassphrase = opts.newPassphraseFile
569
+ ? await readPassphraseFile(opts.newPassphraseFile)
570
+ : 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)'); }
573
+ return { oldPassphrase, newPassphrase };
574
+ }
575
+
435
576
  vault
436
577
  .command('rotate')
437
578
  .description('Rotate vault-level encryption passphrase')
438
- .requiredOption('--old-passphrase <pass>', 'Current vault passphrase')
439
- .requiredOption('--new-passphrase <pass>', 'New vault passphrase')
440
- .option('--algorithm <alg>', 'KDF algorithm (pbkdf2 or scrypt)')
579
+ .option('--old-passphrase <pass>', 'Current vault passphrase')
580
+ .option('--new-passphrase <pass>', 'New vault passphrase')
581
+ .option('--old-passphrase-file <path>', 'Read old passphrase from file (- for stdin)')
582
+ .option('--new-passphrase-file <path>', 'Read new passphrase from file (- for stdin)')
583
+ .addOption(new Option('--algorithm <alg>', 'KDF algorithm').choices(['pbkdf2', 'scrypt']))
441
584
  .option('--cwd <dir>', 'Git working directory', '.')
442
- .action(runAction(async (opts) => {
585
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
586
+ const { oldPassphrase, newPassphrase } = await resolveRotatePassphrases(opts);
443
587
  const cas = createCas(opts.cwd);
588
+ /** @type {{ oldPassphrase: string, newPassphrase: string, kdfOptions?: { algorithm: 'pbkdf2' | 'scrypt' } }} */
444
589
  const rotateOpts = {
445
- oldPassphrase: opts.oldPassphrase,
446
- newPassphrase: opts.newPassphrase,
590
+ oldPassphrase,
591
+ newPassphrase,
447
592
  };
448
593
  if (opts.algorithm) {
449
- rotateOpts.kdfOptions = { algorithm: opts.algorithm };
594
+ rotateOpts.kdfOptions = { algorithm: /** @type {'pbkdf2' | 'scrypt'} */ (opts.algorithm) };
450
595
  }
451
596
  const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase(rotateOpts);
452
597
  const json = program.opts().json;
@@ -470,7 +615,7 @@ vault
470
615
  .command('dashboard')
471
616
  .description('Interactive vault explorer')
472
617
  .option('--cwd <dir>', 'Git working directory', '.')
473
- .action(runAction(async (opts) => {
618
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
474
619
  const cas = createCas(opts.cwd);
475
620
  const { launchDashboard } = await import('./ui/dashboard.js');
476
621
  await launchDashboard(cas);
@@ -488,7 +633,7 @@ program
488
633
  .requiredOption('--new-key-file <path>', 'Path to new 32-byte key file')
489
634
  .option('--label <label>', 'Rotate only the named recipient')
490
635
  .option('--cwd <dir>', 'Git working directory', '.')
491
- .action(runAction(async (opts) => {
636
+ .action(runAction(async (/** @type {Record<string, any>} */ opts) => {
492
637
  validateRestoreFlags(opts);
493
638
  const cas = createCas(opts.cwd);
494
639
  const treeOid = opts.oid || await cas.resolveVaultEntry({ slug: opts.slug });
@@ -497,6 +642,7 @@ program
497
642
  const oldKey = readKeyFile(opts.oldKeyFile);
498
643
  const newKey = readKeyFile(opts.newKeyFile);
499
644
 
645
+ /** @type {{ manifest: Manifest, oldKey: Buffer, newKey: Buffer, label?: string }} */
500
646
  const rotateOpts = { manifest, oldKey, newKey };
501
647
  if (opts.label) { rotateOpts.label = opts.label; }
502
648
 
@@ -507,7 +653,7 @@ program
507
653
  const newTreeOid = await cas.createTree({ manifest: updated });
508
654
  await cas.addToVault({ slug: opts.slug, treeOid: newTreeOid, force: true });
509
655
  if (json) {
510
- process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid, keyVersion: updated.encryption.keyVersion })}\n`);
656
+ process.stdout.write(`${JSON.stringify({ treeOid: newTreeOid, keyVersion: updated.encryption?.keyVersion })}\n`);
511
657
  } else {
512
658
  process.stdout.write(`${newTreeOid}\n`);
513
659
  }
@@ -532,7 +678,7 @@ recipient
532
678
  .requiredOption('--key-file <path>', 'Path to 32-byte key file for the new recipient')
533
679
  .requiredOption('--existing-key-file <path>', 'Path to key file of an existing recipient')
534
680
  .option('--cwd <dir>', 'Git working directory', '.')
535
- .action(runAction(async (slug, opts) => {
681
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
536
682
  const cas = createCas(opts.cwd);
537
683
  const treeOid = await cas.resolveVaultEntry({ slug });
538
684
  const manifest = await cas.readManifest({ treeOid });
@@ -563,7 +709,7 @@ recipient
563
709
  .description('Remove a recipient from an envelope-encrypted asset')
564
710
  .requiredOption('--label <label>', 'Label of the recipient to remove')
565
711
  .option('--cwd <dir>', 'Git working directory', '.')
566
- .action(runAction(async (slug, opts) => {
712
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
567
713
  const cas = createCas(opts.cwd);
568
714
  const treeOid = await cas.resolveVaultEntry({ slug });
569
715
  const manifest = await cas.readManifest({ treeOid });
@@ -585,7 +731,7 @@ recipient
585
731
  .command('list <slug>')
586
732
  .description('List recipients of an envelope-encrypted asset')
587
733
  .option('--cwd <dir>', 'Git working directory', '.')
588
- .action(runAction(async (slug, opts) => {
734
+ .action(runAction(async (/** @type {string} */ slug, /** @type {Record<string, any>} */ opts) => {
589
735
  const cas = createCas(opts.cwd);
590
736
  const treeOid = await cas.resolveVaultEntry({ slug });
591
737
  const manifest = await cas.readManifest({ treeOid });
package/bin/ui/context.js CHANGED
@@ -5,11 +5,14 @@
5
5
  import { createBijou } from '@flyingrobots/bijou';
6
6
  import { nodeRuntime, chalkStyle } from '@flyingrobots/bijou-node';
7
7
 
8
+ /** @type {import('@flyingrobots/bijou').BijouContext | null} */
8
9
  let ctx = null;
9
10
 
10
11
  /**
11
12
  * Returns a bijou context that writes to stderr instead of stdout.
12
13
  * Stdout is reserved for structured output (OIDs, JSON).
14
+ *
15
+ * @returns {import('@flyingrobots/bijou').BijouContext}
13
16
  */
14
17
  export function getCliContext() {
15
18
  if (ctx) {
@@ -25,8 +28,12 @@ export function getCliContext() {
25
28
  return ctx;
26
29
  }
27
30
 
31
+ /**
32
+ * @returns {import('@flyingrobots/bijou').IOPort}
33
+ */
28
34
  function stderrIO() {
29
35
  return {
36
+ /** @param {string} data */
30
37
  write(data) {
31
38
  process.stderr.write(data);
32
39
  },
@@ -36,6 +43,7 @@ function stderrIO() {
36
43
  rawInput() {
37
44
  throw new Error('rawInput() not supported in CLI context');
38
45
  },
46
+ /** @param {(cols: number, rows: number) => void} callback */
39
47
  onResize(callback) {
40
48
  const handler = () => {
41
49
  callback(process.stderr.columns ?? 80, process.stderr.rows ?? 24);
@@ -43,12 +51,17 @@ function stderrIO() {
43
51
  process.stderr.on('resize', handler);
44
52
  return { dispose() { process.stderr.removeListener('resize', handler); } };
45
53
  },
54
+ /**
55
+ * @param {() => void} callback
56
+ * @param {number} ms
57
+ */
46
58
  setInterval(callback, ms) {
47
59
  const id = globalThis.setInterval(callback, ms);
48
60
  return { dispose() { globalThis.clearInterval(id); } };
49
61
  },
50
62
  readFile() { throw new Error('readFile() not supported'); },
51
63
  readDir() { throw new Error('readDir() not supported'); },
64
+ /** @param {string[]} segments */
52
65
  joinPath(...segments) { return segments.join('/'); },
53
66
  };
54
67
  }
@@ -2,8 +2,12 @@
2
2
  * Async command factories for the vault dashboard.
3
3
  */
4
4
 
5
+ /** @typedef {import('../../index.js').default} ContentAddressableStore */
6
+
5
7
  /**
6
8
  * Load vault entries and metadata in parallel.
9
+ *
10
+ * @param {ContentAddressableStore} cas
7
11
  */
8
12
  export function loadEntriesCmd(cas) {
9
13
  return async () => {
@@ -12,23 +16,27 @@ export function loadEntriesCmd(cas) {
12
16
  cas.listVault(),
13
17
  cas.getVaultMetadata(),
14
18
  ]);
15
- return { type: 'loaded-entries', entries, metadata };
16
- } catch (err) {
17
- return { type: 'load-error', source: 'entries', error: err.message };
19
+ return /** @type {const} */ ({ type: 'loaded-entries', entries, metadata });
20
+ } catch (/** @type {any} */ err) {
21
+ return /** @type {const} */ ({ type: 'load-error', source: 'entries', error: /** @type {Error} */ (err).message });
18
22
  }
19
23
  };
20
24
  }
21
25
 
22
26
  /**
23
27
  * Load a single manifest by slug and tree OID.
28
+ *
29
+ * @param {ContentAddressableStore} cas
30
+ * @param {string} slug
31
+ * @param {string} treeOid
24
32
  */
25
33
  export function loadManifestCmd(cas, slug, treeOid) {
26
34
  return async () => {
27
35
  try {
28
36
  const manifest = await cas.readManifest({ treeOid });
29
- return { type: 'loaded-manifest', slug, manifest };
30
- } catch (err) {
31
- return { type: 'load-error', source: 'manifest', slug, error: err.message };
37
+ return /** @type {const} */ ({ type: 'loaded-manifest', slug, manifest });
38
+ } catch (/** @type {any} */ err) {
39
+ return /** @type {const} */ ({ type: 'load-error', source: 'manifest', slug, error: /** @type {Error} */ (err).message });
32
40
  }
33
41
  };
34
42
  }