@git-stunts/git-cas 5.1.0 → 5.2.4

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 (45) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +144 -7
  3. package/bin/actions.js +25 -7
  4. package/bin/git-cas.js +150 -26
  5. package/bin/ui/context.js +13 -0
  6. package/bin/ui/dashboard-cmds.js +14 -6
  7. package/bin/ui/dashboard-view.js +55 -6
  8. package/bin/ui/dashboard.js +109 -7
  9. package/bin/ui/encryption-card.js +2 -2
  10. package/bin/ui/heatmap.js +20 -2
  11. package/bin/ui/history-timeline.js +8 -6
  12. package/bin/ui/manifest-view.js +37 -8
  13. package/bin/ui/progress.js +60 -38
  14. package/index.d.ts +22 -1
  15. package/index.js +80 -114
  16. package/package.json +2 -1
  17. package/src/domain/helpers/buildKdfMetadata.js +18 -0
  18. package/src/domain/schemas/ManifestSchema.d.ts +2 -0
  19. package/src/domain/schemas/ManifestSchema.js +2 -0
  20. package/src/domain/services/CasService.d.ts +8 -1
  21. package/src/domain/services/CasService.js +123 -210
  22. package/src/domain/services/KeyResolver.js +220 -0
  23. package/src/domain/services/Semaphore.js +2 -2
  24. package/src/domain/services/VaultService.js +49 -27
  25. package/src/domain/services/rotateVaultPassphrase.js +143 -0
  26. package/src/domain/value-objects/Manifest.d.ts +2 -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 +38 -7
  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 +68 -18
  36. package/src/infrastructure/adapters/createCryptoAdapter.js +25 -0
  37. package/src/infrastructure/chunkers/FixedChunker.js +5 -1
  38. package/src/infrastructure/chunkers/resolveChunker.js +45 -0
  39. package/src/infrastructure/codecs/CborCodec.js +11 -3
  40. package/src/infrastructure/codecs/JsonCodec.js +10 -2
  41. package/src/ports/CodecPort.js +3 -3
  42. package/src/ports/CryptoPort.js +56 -23
  43. package/src/ports/GitPersistencePort.js +4 -4
  44. package/src/ports/GitRefPort.js +10 -10
  45. package/src/types/ambient.d.ts +37 -0
package/CHANGELOG.md CHANGED
@@ -5,6 +5,82 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [Unreleased]
9
+
10
+ ## [5.2.4] — Prism polish (2026-03-03)
11
+
12
+ ### Fixed
13
+ - **`CryptoPortBase.sha256()` type** — `index.d.ts` declaration corrected from `string | Promise<string>` to `Promise<string>`, matching the async implementation since v5.2.3.
14
+ - **`keyLength` passthrough** — `KeyResolver.#resolveKeyFromPassphrase` and `deriveKekFromKdf` now forward `kdf.keyLength` to `deriveKey()`, fixing a latent bug for vaults configured with non-default key lengths.
15
+ - **Deno test compatibility** — `createCryptoAdapter.test.js` no longer crashes on Deno by guarding immutable `globalThis.Deno` restoration with try/catch and skipping Node-only tests on non-Node runtimes.
16
+ - **README wording** — "no public API changes" corrected to "no breaking API changes" in the v5.2.3 summary.
17
+ - **Barrel re-export description** — README and CHANGELOG now show the correct `export { default as X } from '...'` syntax.
18
+ - **Vestigial `lastchat.txt`** removed from `jsr.json` exclude list.
19
+
20
+ ### Changed
21
+ - **`keyResolver` is now private** — `CasService.keyResolver` changed to `#keyResolver`, preventing external access to an internal implementation detail.
22
+ - **`VaultPassphraseRotator.js` → `rotateVaultPassphrase.js`** — renamed to follow camelCase convention for files that export a function (PascalCase is reserved for classes).
23
+ - **`resolveChunker` validation** — `chunkSize` now validated as a finite positive number before constructing `FixedChunker`; invalid values fall through to CasService default.
24
+ - **`@fileoverview` JSDoc** added to `FileIOHelper.js`, `createCryptoAdapter.js`, and `resolveChunker.js`.
25
+ - **`KeyResolver` design note** — class JSDoc now documents the direct `CryptoPort.deriveKey()` call (bypasses `CasService.deriveKey()`).
26
+ - **Long function signature wrapped** — `rotateVaultPassphrase()` export signature broken across multiple lines.
27
+ - **Test hardening** — salt assertion in `KeyResolver.resolveForStore`, `keyLength` round-trip test, `resolveChunker` edge-case tests, guarded `rmSync` teardown in `FileIOHelper.test.js`.
28
+
29
+ ## [5.2.3] — Prism refactor (2026-03-03)
30
+
31
+ ### Changed
32
+ - **Async `sha256()` across all adapters** — `NodeCryptoAdapter.sha256()` now returns `Promise<string>` (was sync `string`), matching Bun and Web adapters. Fixes Liskov Substitution violation; all callers already `await`. `CryptoPort` JSDoc and `CasService.d.ts` updated to `Promise<string>`.
33
+ - **Extract `KeyResolver`** — ~170 lines of key resolution logic (`wrapDek`, `unwrapDek`, `resolveForDecryption`, `resolveForStore`, `resolveRecipients`, `resolveKeyForRecipients`, passphrase derivation, mutual-exclusion validation) extracted from `CasService` into `src/domain/services/KeyResolver.js`. CasService delegates via `this.keyResolver`. No public API changes. 24 new unit tests.
34
+ - **Move `createCryptoAdapter`** — runtime crypto detection moved from `index.js` to `src/infrastructure/adapters/createCryptoAdapter.js`; test helper now delegates instead of duplicating.
35
+ - **Factor out `resolveChunker`** — chunker factory resolution moved from `index.js` private method to `src/infrastructure/chunkers/resolveChunker.js`.
36
+ - **Move file I/O helpers** — `storeFile()` and `restoreFile()` moved from `index.js` to `src/infrastructure/adapters/FileIOHelper.js`; all `node:*` imports removed from facade.
37
+ - **Factor out `rotateVaultPassphrase`** — passphrase rotation orchestration (~100 lines with retry/backoff) moved from `index.js` to `src/domain/services/rotateVaultPassphrase.js`; `CasError` and `buildKdfMetadata` imports removed from facade.
38
+ - **Private `#config` field** — facade constructor stores options in a single private `#config` field instead of 10 public `this.fooConfig` properties.
39
+ - **Barrel re-exports** — 10 re-export-only modules (`NodeCryptoAdapter`, `Manifest`, `Chunk`, ports, observers, chunkers) converted to `export { default as X } from '...'` form, eliminating unnecessary local bindings.
40
+ - **Configurable retry** — `rotateVaultPassphrase()` now accepts optional `maxRetries` (default 3) and `retryBaseMs` (default 50) options for tuning optimistic-concurrency backoff.
41
+ - **Deterministic fuzz test** — envelope fuzz round-trip test now uses a seeded xorshift32 PRNG instead of `Math.random()`, making failures reproducible across runs.
42
+ - **DRY chunk verification** — extracted `_readAndVerifyChunk()` in `CasService`; both the buffered and streaming restore paths now delegate to the same single-chunk verification method.
43
+ - **DRY KDF metadata** — extracted `buildKdfMetadata()` helper (`src/domain/helpers/buildKdfMetadata.js`); `VaultService` and `ContentAddressableStore` both call it instead of duplicating the KDF object construction.
44
+
45
+ ## [5.2.2] — JSDoc total coverage (2026-02-28)
46
+
47
+ ### Added
48
+ - `tsconfig.checkjs.json` — strict `checkJs` configuration; `tsc --noEmit` passes with zero errors.
49
+ - `src/types/ambient.d.ts` — ambient type declarations for `@git-stunts/plumbing` and `bun` modules.
50
+ - `@types/node` dev dependency for typecheck support.
51
+ - JSDoc `@typedef` types: `EncryptionMeta`, `KdfParamSet`, `DeriveKeyParams` (CryptoPort); `VaultMetadata`, `VaultState`, `VaultEncryptionMeta` (VaultService).
52
+
53
+ ### Changed
54
+ - Every exported and internal function, class method, and callback across all 32 source files now has complete JSDoc `@param`/`@returns` annotations.
55
+ - CryptoPort return types widened to `string | Promise<string>` (sha256), `Buffer | Uint8Array` (randomBytes), sync-or-async for encrypt/decrypt — accurately reflecting adapter implementations.
56
+ - Port `@param` names corrected to match underscore-prefixed abstract parameters (fixes TS8024).
57
+ - Observer adapter methods (`SilentObserver`, `EventEmitterObserver`, `StatsCollector`) fully typed.
58
+ - CLI files (`bin/`) comprehensively annotated with JSDoc types for all Commander callbacks and TUI render functions.
59
+
60
+ ## [5.2.1] — Carousel polish (2026-02-28)
61
+
62
+ ### Added
63
+ - CLI reference in `docs/API.md` for `git cas rotate` and `git cas vault rotate` flags.
64
+
65
+ ### Changed
66
+ - Rotation helpers in `CasService` use native `#private` methods, matching the facade's style.
67
+ - `VAULT_CONFLICT` and `VAULT_METADATA_INVALID` error code docs now list `rotateVaultPassphrase()`.
68
+
69
+ ### Fixed
70
+ - `rotateVaultPassphrase` now honours `kdfOptions.algorithm` instead of silently using the old algorithm.
71
+ - Rotation integration test no longer flaps under CI load (reduced test-only KDF iterations).
72
+
73
+ ## [5.2.0] — Carousel (2026-02-28)
74
+
75
+ ### Added
76
+ - **Key rotation without re-encrypting data** — `CasService.rotateKey()` re-wraps the DEK with a new KEK, leaving data blobs untouched. Enables key compromise response without re-storing assets.
77
+ - **`keyVersion` tracking** — manifest-level and per-recipient `keyVersion` counters track rotation history for audit compliance. Optional field, backward-compatible with existing manifests.
78
+ - **`git cas rotate` CLI command** — rotate a recipient's key via `--slug` (vault round-trip) or `--oid` (manifest-only). Supports `--label` for targeted single-recipient rotation.
79
+ - **`rotateVaultPassphrase()`** — rotate the vault-level encryption passphrase across all envelope-encrypted entries in a single atomic commit. Non-envelope entries are skipped with reporting.
80
+ - **`git cas vault rotate` CLI command** — rotate vault passphrase from the command line with `--old-passphrase` and `--new-passphrase`.
81
+ - **`ROTATION_NOT_SUPPORTED` error code** — thrown when `rotateKey()` is called on a manifest without envelope encryption (legacy/direct-key).
82
+ - 27 new unit tests covering key rotation, schema validation, and vault passphrase rotation.
83
+
8
84
  ## [5.1.0] — Locksmith (2026-02-28)
9
85
 
10
86
  ### Added
package/README.md CHANGED
@@ -19,8 +19,10 @@ We use the object database.
19
19
  ## What you get
20
20
 
21
21
  - **Dedupe for free** Git already hashes objects. We just lean into it.
22
- - **Chunked storage** big files become stable, reusable blobs.
22
+ - **Chunked storage** big files become stable, reusable blobs. Fixed-size or content-defined chunking (CDC).
23
23
  - **Optional AES-256-GCM encryption** store secrets without leaking plaintext into the ODB.
24
+ - **Multi-recipient encryption** envelope model (DEK/KEK) — add/remove access without re-encrypting data.
25
+ - **Key rotation** rotate keys without re-encrypting data blobs. Respond to compromise in seconds.
24
26
  - **Compression** gzip before encryption — smaller blobs, same round-trip.
25
27
  - **Passphrase encryption** derive keys from passphrases via PBKDF2 or scrypt — no raw key management.
26
28
  - **Merkle manifests** large files auto-split into sub-manifests for scalability.
@@ -29,18 +31,105 @@ We use the object database.
29
31
  - **Full round-trip** store, tree, and restore — get your bytes back, verified.
30
32
  - **Lifecycle management** `readManifest`, `deleteAsset`, `findOrphanedChunks` — inspect trees, plan deletions, audit storage.
31
33
  - **Vault** GC-safe ref-based storage. One ref (`refs/cas/vault`) indexes all assets by slug. No more silent data loss from `git gc`.
34
+ - **Interactive dashboard** `git cas inspect` with chunk heatmap, animated progress bars, and rich manifest views.
35
+ - **Verify & JSON output** `git cas verify` checks integrity; `--json` on all commands for CI/scripting.
32
36
 
33
37
  **Use it for:** binary assets, build artifacts, model weights, data packs, secret bundles, weird experiments, etc.
34
38
 
35
39
  <img src="./docs/demo.gif" alt="git-cas demo" />
36
40
 
37
- ## What's new in v2.0.0
41
+ ## What's new in v5.2.4
38
42
 
39
- **Compression** — `compression: { algorithm: 'gzip' }` on `store()`. Compression runs before encryption. Decompression on `restore()` is automatic.
43
+ **Code review polish — bug fixes, internal hardening, no breaking changes.**
40
44
 
41
- **Passphrase-based encryption** — Pass `passphrase` instead of `encryptionKey`. Keys are derived via PBKDF2 (default) or scrypt. KDF parameters are stored in the manifest for deterministic re-derivation. Use `deriveKey()` directly for manual control.
45
+ - **`keyLength` passthrough fixed** — KDF derivation now correctly forwards `kdf.keyLength`, fixing a latent bug for vaults configured with non-default key lengths.
46
+ - **`sha256()` type declaration fixed** — `index.d.ts` corrected from `string | Promise<string>` to `Promise<string>`.
47
+ - **Deno CI fixed** — `createCryptoAdapter` tests no longer crash on Deno due to immutable global restoration.
48
+ - **`keyResolver` made private** — `CasService.#keyResolver` prevents external access to an internal detail.
49
+ - **`resolveChunker` validation** — `chunkSize` now validated as a finite positive number before constructing `FixedChunker`.
50
+ - **File rename** — `VaultPassphraseRotator.js` → `rotateVaultPassphrase.js` (camelCase for functions, PascalCase for classes).
42
51
 
43
- **Merkle tree manifests** — When chunk count exceeds `merkleThreshold` (default: 1000), manifests are automatically split into sub-manifests stored as separate blobs. `readManifest()` transparently reconstitutes them. Full backward compatibility with v1 manifests.
52
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
53
+
54
+ ## What's new in v5.2.3
55
+
56
+ **Internal refactoring — no breaking API changes.** The facade, CasService, and crypto adapters were restructured for better separation of concerns:
57
+
58
+ - **Consistent async `sha256()`** — `NodeCryptoAdapter.sha256()` now returns `Promise<string>` like Bun and Web adapters, fixing a Liskov Substitution violation.
59
+ - **`KeyResolver` extracted** — ~170 lines of key resolution logic (DEK wrap/unwrap, passphrase derivation, envelope recipients) moved from CasService (1085 → 909 lines) into a dedicated `KeyResolver` service.
60
+ - **Facade decomposed** — `createCryptoAdapter`, `resolveChunker`, `FileIOHelper`, `rotateVaultPassphrase`, and `buildKdfMetadata` extracted from the monolithic `index.js` into focused modules.
61
+ - **Barrel re-exports** — 10 re-export-only modules converted to `export { default as X } from '...'` form.
62
+
63
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
64
+
65
+ ## What's new in v5.2.1
66
+
67
+ Bug fix: `rotateVaultPassphrase` now honours `kdfOptions.algorithm` — previously the `--algorithm` flag was silently ignored, always reusing the old KDF algorithm. CLI flag tables in `docs/API.md` are now split per command with `--cwd` documented.
68
+
69
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
70
+
71
+ ## What's new in v5.2.0
72
+
73
+ **Key rotation without re-encrypting data** — Rotate a recipient's key by re-wrapping the DEK. Data blobs are never touched. Respond to key compromise in seconds, not hours.
74
+
75
+ ```js
76
+ // Rotate a single recipient's key
77
+ const rotated = await cas.rotateKey({
78
+ manifest, oldKey: aliceOldKey, newKey: aliceNewKey, label: 'alice',
79
+ });
80
+
81
+ // Rotate the vault passphrase (all entries, atomic commit)
82
+ const { commitOid, rotatedSlugs, skippedSlugs } = await cas.rotateVaultPassphrase({
83
+ oldPassphrase: 'old-secret', newPassphrase: 'new-secret',
84
+ });
85
+ ```
86
+
87
+ ```bash
88
+ # Rotate a recipient key
89
+ git cas rotate --slug prod-secrets --old-key-file old.key --new-key-file new.key
90
+
91
+ # Rotate vault passphrase
92
+ git cas vault rotate --old-passphrase old-secret --new-passphrase new-secret
93
+ ```
94
+
95
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
96
+
97
+ ## What's new in v5.1.0
98
+
99
+ **Multi-recipient envelope encryption** — Each file is encrypted with a random DEK; recipient KEKs wrap the DEK. Add or remove team members without re-encrypting data.
100
+
101
+ ```js
102
+ // API: store for multiple recipients
103
+ const manifest = await cas.storeFile({
104
+ filePath: './secrets.tar.gz',
105
+ slug: 'prod-secrets',
106
+ recipients: [
107
+ { label: 'alice', key: aliceKey },
108
+ { label: 'bob', key: bobKey },
109
+ ],
110
+ });
111
+
112
+ // Add a recipient later (no re-encryption)
113
+ const updated = await cas.addRecipient({
114
+ manifest, existingKey: aliceKey, newRecipientKey: carolKey, label: 'carol',
115
+ });
116
+
117
+ // List / remove recipients
118
+ const labels = await cas.listRecipients({ manifest });
119
+ const trimmed = await cas.removeRecipient({ manifest, label: 'bob' });
120
+ ```
121
+
122
+ ```bash
123
+ # CLI: store with multiple recipients
124
+ git cas store ./secrets.tar.gz --slug prod-secrets \
125
+ --recipient alice:./keys/alice.key \
126
+ --recipient bob:./keys/bob.key --tree
127
+
128
+ # Manage recipients
129
+ git cas recipient list prod-secrets
130
+ git cas recipient add prod-secrets --label carol --key-file ./keys/carol.key --existing-key-file ./keys/alice.key
131
+ git cas recipient remove prod-secrets --label bob
132
+ ```
44
133
 
45
134
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
46
135
 
@@ -83,6 +172,28 @@ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
83
172
 
84
173
  See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
85
174
 
175
+ ## What's new in v3.1.0
176
+
177
+ **Interactive vault dashboard** — `git cas inspect --slug my-asset` renders a rich TUI with chunk heatmap, encryption card, and history timeline. Animated progress bars for long store/restore operations.
178
+
179
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
180
+
181
+ ## What's new in v3.0.0
182
+
183
+ **Vault** — GC-safe ref-based storage under `refs/cas/vault`. Assets are indexed by slug and survive `git gc`. Full CLI: `git cas vault init`, `list`, `info`, `remove`, `history`. Store with `--tree` to vault automatically.
184
+
185
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
186
+
187
+ ## What's new in v2.0.0
188
+
189
+ **Compression** — `compression: { algorithm: 'gzip' }` on `store()`. Compression runs before encryption. Decompression on `restore()` is automatic.
190
+
191
+ **Passphrase-based encryption** — Pass `passphrase` instead of `encryptionKey`. Keys are derived via PBKDF2 (default) or scrypt. KDF parameters are stored in the manifest for deterministic re-derivation. Use `deriveKey()` directly for manual control.
192
+
193
+ **Merkle tree manifests** — When chunk count exceeds `merkleThreshold` (default: 1000), manifests are automatically split into sub-manifests stored as separate blobs. `readManifest()` transparently reconstitutes them. Full backward compatibility with v1 manifests.
194
+
195
+ See [CHANGELOG.md](./CHANGELOG.md) for the full list of changes.
196
+
86
197
  ## Install
87
198
 
88
199
  ```bash
@@ -148,18 +259,44 @@ git cas restore --slug my-image --out ./restored.png
148
259
  # Restore from a direct tree OID
149
260
  git cas restore --oid <tree-oid> --out ./restored.png
150
261
 
262
+ # Verify integrity without restoring
263
+ git cas verify --slug my-image
264
+
265
+ # Inspect manifest (interactive dashboard)
266
+ git cas inspect --slug my-image
267
+
151
268
  # Vault management
152
269
  git cas vault init
153
- git cas vault list
270
+ git cas vault list # TTY table
271
+ git cas vault list --json # structured JSON
272
+ git cas vault list --filter "photos/*" # glob filter
154
273
  git cas vault info my-image
155
274
  git cas vault remove my-image
156
275
  git cas vault history
157
276
 
277
+ # Multi-recipient encryption
278
+ git cas store ./secret.bin --slug shared \
279
+ --recipient alice:./keys/alice.key \
280
+ --recipient bob:./keys/bob.key --tree
281
+ git cas recipient list shared
282
+ git cas recipient add shared --label carol --key-file ./keys/carol.key --existing-key-file ./keys/alice.key
283
+ git cas recipient remove shared --label bob
284
+
285
+ # Key rotation (no re-encryption)
286
+ git cas rotate --slug shared --old-key-file old.key --new-key-file new.key
287
+ git cas rotate --slug shared --old-key-file old.key --new-key-file new.key --label alice
288
+
289
+ # Vault passphrase rotation
290
+ git cas vault rotate --old-passphrase old-secret --new-passphrase new-secret
291
+
158
292
  # Encrypted vault round-trip (passphrase via env var or --vault-passphrase flag)
159
293
  export GIT_CAS_PASSPHRASE="secret"
160
294
  git cas vault init
161
295
  git cas store ./secret.bin --slug vault-entry --tree
162
296
  git cas restore --slug vault-entry --out ./decrypted.bin
297
+
298
+ # JSON output on any command (for CI/scripting)
299
+ git cas store ./data.bin --slug my-data --tree --json
163
300
  ```
164
301
 
165
302
  ## Documentation
@@ -181,7 +318,7 @@ That's git-cas. The orphan branch gives you none of:
181
318
 
182
319
  | | Orphan branch | git-cas |
183
320
  |---|---|---|
184
- | **Encryption** | None — plaintext forever in history | AES-256-GCM + passphrase KDF |
321
+ | **Encryption** | None — plaintext forever in history | AES-256-GCM + passphrase KDF + multi-recipient + key rotation |
185
322
  | **Large files** | Bloats `git clone` for everyone | Chunked, restored on demand |
186
323
  | **Dedup** | None | Chunk-level content addressing |
187
324
  | **Integrity** | Git SHA-1 | SHA-256 per chunk + GCM auth tag |
package/bin/actions.js CHANGED
@@ -2,6 +2,9 @@
2
2
  * CLI error handler — wraps command actions with structured error output.
3
3
  */
4
4
 
5
+ /** @typedef {{ code?: string, message?: string }} ErrorLike */
6
+
7
+ /** @type {Readonly<Record<string, string>>} */
5
8
  const HINTS = {
6
9
  MISSING_KEY: 'Provide --key-file or --vault-passphrase',
7
10
  MANIFEST_NOT_FOUND: 'Verify the tree OID contains a manifest',
@@ -13,43 +16,58 @@ const HINTS = {
13
16
  RECIPIENT_NOT_FOUND: 'No recipient with that label exists in the manifest',
14
17
  RECIPIENT_ALREADY_EXISTS: 'A recipient with that label already exists',
15
18
  CANNOT_REMOVE_LAST_RECIPIENT: 'At least one recipient must remain in the manifest',
19
+ ROTATION_NOT_SUPPORTED: 'Key rotation requires envelope encryption — store with --recipient first',
16
20
  };
17
21
 
18
22
  /**
19
23
  * Format and write an error to stderr.
20
24
  *
21
- * @param {Error} err
25
+ * @param {ErrorLike} err
22
26
  * @param {boolean} json - Whether to output JSON.
23
27
  */
24
28
  function writeError(err, json) {
25
29
  const message = err?.message ?? String(err);
26
30
  const code = typeof err?.code === 'string' ? err.code : undefined;
27
31
  if (json) {
32
+ /** @type {{ error: string, code?: string }} */
28
33
  const obj = { error: message };
29
34
  if (code) { obj.code = code; }
30
35
  process.stderr.write(`${JSON.stringify(obj)}\n`);
31
36
  } else {
32
37
  const prefix = code ? `error [${code}]: ` : 'error: ';
33
38
  process.stderr.write(`${prefix}${message}\n`);
34
- const hint = code ? HINTS[code] : undefined;
39
+ const hint = getHint(code);
35
40
  if (hint) {
36
41
  process.stderr.write(`hint: ${hint}\n`);
37
42
  }
38
43
  }
39
44
  }
40
45
 
46
+ /**
47
+ * Look up a hint for the given error code, guarding against prototype keys.
48
+ *
49
+ * @param {string | undefined} code
50
+ * @returns {string | undefined}
51
+ */
52
+ function getHint(code) {
53
+ if (code && Object.prototype.hasOwnProperty.call(HINTS, code)) {
54
+ return HINTS[code];
55
+ }
56
+ return undefined;
57
+ }
58
+
41
59
  /**
42
60
  * Wrap a command action with structured error handling.
43
61
  *
44
- * @param {Function} fn - The async action function.
45
- * @param {Function} getJson - Lazy getter for --json flag value.
46
- * @returns {Function} Wrapped action.
62
+ * @param {(...args: any[]) => Promise<void>} fn - The async action function.
63
+ * @param {() => boolean} getJson - Lazy getter for --json flag value.
64
+ * @returns {(...args: any[]) => Promise<void>} Wrapped action.
47
65
  */
48
66
  export function runAction(fn, getJson) {
49
- return async (...args) => {
67
+ return async (/** @type {any[]} */ ...args) => {
50
68
  try {
51
69
  await fn(...args);
52
- } catch (err) {
70
+ } catch (/** @type {any} */ err) {
53
71
  writeError(err, getJson());
54
72
  process.exitCode = 1;
55
73
  }