@mago-foundation/mago-ski 0.1.0 → 0.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 (91) hide show
  1. package/README.md +54 -9
  2. package/action.yml +2 -2
  3. package/dist/hosts/github/run.d.ts +9 -1
  4. package/dist/hosts/github/run.js +64 -11
  5. package/dist/hosts/pi/index.d.ts +5 -3
  6. package/dist/hosts/pi/index.js +219 -14
  7. package/dist/src/admin.d.ts +140 -1
  8. package/dist/src/admin.js +328 -63
  9. package/dist/src/canonical-json.js +73 -28
  10. package/dist/src/certificate.js +23 -15
  11. package/dist/src/cli.js +590 -89
  12. package/dist/src/diff.d.ts +0 -4
  13. package/dist/src/diff.js +326 -70
  14. package/dist/src/dsse.d.ts +6 -4
  15. package/dist/src/dsse.js +22 -6
  16. package/dist/src/fs-safe.d.ts +32 -3
  17. package/dist/src/fs-safe.js +193 -31
  18. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  20. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  21. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  22. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  23. package/dist/src/gate/adapters/claude-code.js +193 -0
  24. package/dist/src/gate/adapters/client.d.ts +13 -0
  25. package/dist/src/gate/adapters/client.js +57 -0
  26. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  27. package/dist/src/gate/adapters/codex-hook.js +5 -0
  28. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  29. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  30. package/dist/src/gate/adapters/codex.d.ts +16 -0
  31. package/dist/src/gate/adapters/codex.js +574 -0
  32. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  33. package/dist/src/gate/adapters/hook-main.js +35 -0
  34. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  35. package/dist/src/gate/adapters/host-pid.js +20 -0
  36. package/dist/src/gate/admission.d.ts +54 -0
  37. package/dist/src/gate/admission.js +490 -0
  38. package/dist/src/gate/contract.d.ts +51 -0
  39. package/dist/src/gate/contract.js +94 -0
  40. package/dist/src/gate/decision-log.d.ts +38 -0
  41. package/dist/src/gate/decision-log.js +251 -0
  42. package/dist/src/gate/generations.d.ts +67 -0
  43. package/dist/src/gate/generations.js +518 -0
  44. package/dist/src/gate/proc.d.ts +31 -0
  45. package/dist/src/gate/proc.js +79 -0
  46. package/dist/src/gate/refresh.d.ts +11 -0
  47. package/dist/src/gate/refresh.js +30 -0
  48. package/dist/src/gate/run-verifier.d.ts +23 -0
  49. package/dist/src/gate/run-verifier.js +89 -0
  50. package/dist/src/gate/service.d.ts +80 -0
  51. package/dist/src/gate/service.js +722 -0
  52. package/dist/src/gate/strict-json.d.ts +11 -0
  53. package/dist/src/gate/strict-json.js +190 -0
  54. package/dist/src/gate/trust-store.d.ts +36 -0
  55. package/dist/src/gate/trust-store.js +251 -0
  56. package/dist/src/gate/verifier-worker.d.ts +8 -0
  57. package/dist/src/gate/verifier-worker.js +66 -0
  58. package/dist/src/index.d.ts +2 -0
  59. package/dist/src/index.js +2 -0
  60. package/dist/src/keys.d.ts +4 -0
  61. package/dist/src/keys.js +85 -30
  62. package/dist/src/main-module.js +1 -1
  63. package/dist/src/names.js +2 -4
  64. package/dist/src/policy.d.ts +173 -6
  65. package/dist/src/policy.js +685 -54
  66. package/dist/src/recovery-admin.d.ts +173 -0
  67. package/dist/src/recovery-admin.js +400 -0
  68. package/dist/src/revocations.js +3 -1
  69. package/dist/src/root-events.d.ts +107 -0
  70. package/dist/src/root-events.js +376 -0
  71. package/dist/src/time.d.ts +19 -3
  72. package/dist/src/time.js +50 -8
  73. package/dist/src/timestamp.d.ts +61 -0
  74. package/dist/src/timestamp.js +107 -0
  75. package/dist/src/tree-digest.d.ts +4 -0
  76. package/dist/src/tree-digest.js +41 -16
  77. package/dist/src/trust-root.d.ts +5 -0
  78. package/dist/src/trust-root.js +34 -13
  79. package/dist/src/verify.d.ts +69 -13
  80. package/dist/src/verify.js +309 -61
  81. package/docs/hosts/adapter-interface.md +8 -2
  82. package/docs/hosts/github-action.md +3 -3
  83. package/docs/hosts/pi.md +10 -3
  84. package/docs/spec/gui-admin-rack-v1.md +289 -0
  85. package/docs/spec/root-recovery-v1.md +451 -0
  86. package/docs/spec/skill-certificate-v1.md +1 -1
  87. package/docs/spec/skill-tree-v2.md +2 -2
  88. package/docs/spec/trust-documents-v1.md +12 -6
  89. package/docs/spec/verification.md +20 -3
  90. package/docs/threat-model.md +9 -6
  91. package/package.json +49 -44
package/dist/src/cli.js CHANGED
@@ -2,60 +2,96 @@
2
2
  import { readFileSync } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
- import { addApprover, approveSkill, initRoot, removeApprover, updateRevocations } from "./admin.js";
5
+ import { addApprover, approveSkill, initRoot, removeApprover, renewTrustRoot, updateRevocations } from "./admin.js";
6
6
  import { parseCertificate } from "./certificate.js";
7
7
  import { diffSkillTrees } from "./diff.js";
8
8
  import { readRegularFile } from "./fs-safe.js";
9
9
  import { generateKeyPair, validateKeyId } from "./keys.js";
10
- import { appendDecision, decisionRecord, DEFAULT_POLICY_PATH, findSkillDirs, loadPolicy, loadPolicyTrust, tooDeepResult, verifyWithPolicy, } from "./policy.js";
10
+ import { appendDecision, decisionRecord, defaultPolicyPath, effectiveMode, findSkillDirs, forbiddenApproverKeys, loadPolicy, loadPolicyTrust, tooDeepResult, trustFailureEvent, trustFailureRecord, verifyWithPolicy, } from "./policy.js";
11
+ import { adoptTrustDocuments, appendRootEvent, buildRecoverySet, currentRootState, describeRootEvent, initRootEventLog, prepareRootEvent, recoverySetJson, showRootEvent, signPolicyTimestamp, signRootEvent, } from "./recovery-admin.js";
11
12
  import { isMainModule } from "./main-module.js";
12
13
  import { formatTimestamp } from "./time.js";
13
14
  import { collectSkillTree, TREE_PROFILE } from "./tree-digest.js";
14
15
  import { verifyTrustRoot } from "./trust-root.js";
15
- import { unverifiable } from "./verify.js";
16
- const usage = `mago-ski: organization-approved Skill certificates, enforced on the agent host.
17
-
18
- Keys and trust (run by the organization's root key holder):
19
- mago-ski keygen --private-key FILE --public-key FILE
20
- mago-ski root init --root-key FILE --trust-root OUT --revocations OUT [--trust-root-expires 365d] [--revocations-expires 30d]
21
- mago-ski root add-approver --root-key FILE --trust-root FILE --public-key FILE --name LABEL --scope PATTERN [--scope ...] --expires 180d [--out FILE] [--trust-root-expires 365d]
22
- mago-ski root remove-approver --root-key FILE --trust-root FILE --key-id ID [--out FILE]
23
- mago-ski root show --trust-root FILE --root-fingerprint ID
24
- mago-ski revoke key --root-key FILE --revocations FILE --key-id ID --reason TEXT [--expires 30d] [--out FILE]
25
- mago-ski revoke digest --root-key FILE --revocations FILE --digest sha256:... --reason TEXT [--expires 30d] [--out FILE]
26
- mago-ski revoke refresh --root-key FILE --revocations FILE [--expires 30d] [--out FILE]
27
-
28
- Approving Skills (run by a reviewer with an approver key):
29
- mago-ski approve SKILL_DIR --key FILE --expires 90d --reason TEXT [--name NAME] [--previous CERT|DIGEST] [--out FILE]
30
-
31
- Checking Skills (uses .mago-ski/policy.json unless --policy is given):
32
- mago-ski verify SKILL_DIR [--policy FILE] [--name NAME] [--certificate FILE] [--json]
33
- mago-ski verify-all [--policy FILE] [--json]
34
- mago-ski digest SKILL_DIR [--explain]
35
- mago-ski diff --base DIR --candidate DIR
36
- mago-ski inspect CERTIFICATE
37
-
38
- Verdicts: VERIFIED, UNAPPROVED_CHANGE, NO_CERTIFICATE, UNTRUSTED_SIGNER, REVOKED, EXPIRED, UNVERIFIABLE.
39
- Exit codes: 0 success or VERIFIED; 1 any other verdict or a required re-certification; 2 usage or input error.
40
- Run "mago-ski <command> --help" for a command's options, and "mago-ski --version" for the version.
41
-
42
- A certificate records who approved an exact Skill version. It does not certify that the Skill is safe.`;
16
+ import { resolveSkillName, unverifiable } from "./verify.js";
17
+ import { createRequire } from 'node:module';
18
+ const usage = `mago-ski — organization-approved Skill certificates,
19
+ enforced on the agent host
20
+
21
+ USAGE
22
+ mago-ski <command> [options]
23
+
24
+ KEYS AND TRUST (root key holder)
25
+ keygen Create an Ed25519 key pair
26
+ root init Create the trust root and revocation list
27
+ root add-approver Add or replace an approver
28
+ root remove-approver Remove an approver
29
+ root renew Extend the trust root's lifetime
30
+ root show Verify and print a trust root
31
+ root adopt Re-sign trust documents with a new root key
32
+ revoke key Revoke an approver key
33
+ revoke digest Revoke one approved Skill version
34
+ revoke refresh Re-sign the revocation list
35
+
36
+ ROOT RECOVERY (recovery key holders, timestamp job)
37
+ recovery init Build the policy's recovery set
38
+ root-events init|prepare-revoke|prepare-rotate|show|sign|append
39
+ Propose, check, sign and append root events
40
+ timestamp sign Sign the freshness timestamp
41
+
42
+ APPROVING SKILLS (reviewer)
43
+ approve SKILL_DIR Issue a certificate for a Skill
44
+
45
+ CHECKING SKILLS
46
+ verify SKILL_DIR Check one Skill, print its verdict
47
+ verify-all Check every Skill in the policy
48
+ digest SKILL_DIR Print a Skill's tree digest
49
+ diff Compare two versions of a Skill
50
+ inspect CERTIFICATE Print a certificate's contents
51
+ policy check Check a policy the way a host does
52
+
53
+ POLICY
54
+ --policy FILE, else $MAGO_SKI_POLICY, else
55
+ ~/.mago-ski/policy.json (never the current directory)
56
+
57
+ VERDICTS
58
+ VERIFIED UNAPPROVED_CHANGE NO_CERTIFICATE
59
+ UNTRUSTED_SIGNER REVOKED EXPIRED UNVERIFIABLE
60
+
61
+ EXIT CODES
62
+ 0 success, or VERIFIED
63
+ 1 any other verdict, or re-certification required
64
+ 2 usage or input error
65
+
66
+ Run "mago-ski <command> --help" for a command's options,
67
+ and "mago-ski --version" for the version.
68
+
69
+ A certificate records who approved an exact Skill
70
+ version. It does not certify that the Skill is safe.`;
43
71
  const DURATION_NOTE = 'Durations are a number plus d, h or m, for example 90d, 12h or 30m.';
72
+ /* ****************************************************************************************** */
44
73
  /** Per-command help: `mago-ski <command> --help`. Keys are "command" or "command subcommand". */
74
+ /* ****************************************************************************************** */
45
75
  const COMMAND_HELP = {
46
76
  keygen: `Usage: mago-ski keygen --private-key FILE --public-key FILE
47
77
 
48
78
  Creates an Ed25519 key pair for a root key or an approver key.
49
79
 
50
- --private-key FILE where to write the private key (created with mode 600; must not exist yet)
51
- --public-key FILE where to write the public key
80
+ --private-key FILE where to write the private key (created with mode 600; must not exist yet)
81
+ --public-key FILE where to write the public key
52
82
 
53
83
  Keep private keys secret and outside every Skill directory; keygen refuses to write inside one.
54
84
  Prints the key id (sha256:...), which identifies the key in trust roots and revocations.`,
55
- root: `Usage: mago-ski root <init | add-approver | remove-approver | show> [options]
85
+ /* ****************************************************************************************** */
86
+ /** Per-command: root */
87
+ /* ****************************************************************************************** */
88
+ root: `Usage: mago-ski root <init | add-approver | remove-approver | renew | show> [options]
56
89
 
57
90
  Manages the organization's signed trust root (who may approve which Skills).
58
91
  Run "mago-ski root <subcommand> --help" for details.`,
92
+ /* *************************************** */
93
+ /* Per-command "root" -> "root init" */
94
+ /* *************************************** */
59
95
  'root init': `Usage: mago-ski root init --root-key FILE --trust-root OUT --revocations OUT [options]
60
96
 
61
97
  Creates version 1 of the signed trust root (no approvers yet) and an empty signed revocation list.
@@ -68,6 +104,9 @@ Creates version 1 of the signed trust root (no approvers yet) and an empty signe
68
104
 
69
105
  Prints root_fingerprint: put it in every host policy as "root_fingerprint".
70
106
  ${DURATION_NOTE}`,
107
+ /* ******************************************** */
108
+ /* Per-command "root" -> "root add-approver */
109
+ /* ******************************************** */
71
110
  'root add-approver': `Usage: mago-ski root add-approver --root-key FILE --trust-root FILE --public-key FILE --name LABEL --scope PATTERN [--scope ...] --expires DUR [options]
72
111
 
73
112
  Adds (or replaces) an approver and re-signs the trust root with the next version.
@@ -81,17 +120,34 @@ Adds (or replaces) an approver and re-signs the trust root with the next version
81
120
  --expires DUR how long the approver key stays valid
82
121
  --out FILE write the new trust root here instead
83
122
  --trust-root-expires DUR also set a new trust root lifetime
123
+ --policy FILE refuse keys that hold or held another role in this organisation (recommended)
84
124
  ${DURATION_NOTE}`,
125
+ /* ************************************************* */
126
+ /* Per-command "root" -> "root remove-approver" */
127
+ /* *********************************************** */
85
128
  'root remove-approver': `Usage: mago-ski root remove-approver --root-key FILE --trust-root FILE --key-id ID [--out FILE] [--trust-root-expires DUR]
86
129
 
87
130
  Removes an approver and re-signs the trust root. Certificates from that approver stop verifying once hosts read
88
131
  the new trust root. If the key may be compromised, also revoke it with "mago-ski revoke key".`,
132
+ /* Per-command "root" -> "root renew" */
133
+ 'root renew': `Usage: mago-ski root renew --root-key FILE --trust-root FILE --expires DUR [--out FILE]
134
+
135
+ Re-signs the trust root with a new expiry and the same approvers.`,
136
+ /* ************************************** */
137
+ /* Per-command "root" -> "root show" */
138
+ /* ************************************** */
89
139
  'root show': `Usage: mago-ski root show --trust-root FILE --root-fingerprint ID
90
140
 
91
141
  Verifies a trust root against the pinned root fingerprint and prints its version, expiry and approvers.`,
142
+ /* ****************************************************************************************** */
143
+ /** Per-command: revoke */
144
+ /* ****************************************************************************************** */
92
145
  revoke: `Usage: mago-ski revoke <key | digest | refresh> [options]
93
146
 
94
147
  Updates the organization's signed revocation list. Run "mago-ski revoke <subcommand> --help" for details.`,
148
+ /* *************************************** */
149
+ /* Per-command "revoke" -> "revoke key" */
150
+ /* *************************************** */
95
151
  'revoke key': `Usage: mago-ski revoke key --root-key FILE --revocations FILE --key-id ID --reason TEXT [--expires DUR] [--out FILE]
96
152
 
97
153
  Revokes an approver key: every certificate it signed stops verifying once hosts read the new list.
@@ -100,14 +156,23 @@ Revokes an approver key: every certificate it signed stops verifying once hosts
100
156
  --reason TEXT shown in verdicts
101
157
  --expires DUR lifetime of the new list (default 30d)
102
158
  ${DURATION_NOTE}`,
159
+ /* ****************************************** */
160
+ /* Per-command "revoke" -> "revoke digest" */
161
+ /* ****************************************** */
103
162
  'revoke digest': `Usage: mago-ski revoke digest --root-key FILE --revocations FILE --digest sha256:... --reason TEXT [--expires DUR] [--out FILE]
104
163
 
105
164
  Revokes one approved Skill version (its tree digest), whoever signed it.
106
165
  ${DURATION_NOTE}`,
166
+ /* ******************************************* */
167
+ /* Per-command "revoke" -> "revoke refresh" */
168
+ /* ******************************************* */
107
169
  'revoke refresh': `Usage: mago-ski revoke refresh --root-key FILE --revocations FILE [--expires DUR] [--out FILE]
108
170
 
109
171
  Re-signs the revocation list with the next version and a new expiry, without changing its entries.
110
172
  Hosts refuse an expired list, so refresh it before it expires (default lifetime 30d).`,
173
+ /* ****************************************************************************************** */
174
+ /** Per-command: approve */
175
+ /* ****************************************************************************************** */
111
176
  approve: `Usage: mago-ski approve SKILL_DIR --key FILE --expires DUR --reason TEXT [options]
112
177
 
113
178
  Issues a certificate for the exact current bytes of a Skill, signed with your approver key.
@@ -118,95 +183,245 @@ Issues a certificate for the exact current bytes of a Skill, signed with your ap
118
183
  --name NAME Skill name (default: "name" in SKILL.md, else the directory name)
119
184
  --previous CERT|DIG the previously approved certificate or digest, for the update history
120
185
  --out FILE where to write the certificate (default: SKILL_DIR/.mago-ski-cert.json)
186
+ --expect-digest DIG the digest you reviewed (sha256:...); refuses to sign if the Skill changed since
121
187
 
122
188
  Refuses a Skill that contains a private key. A certificate records who approved which exact version;
123
189
  it does not certify that the Skill is safe.
124
190
  ${DURATION_NOTE}`,
191
+ /* ****************************************************************************************** */
192
+ /** Per-command: verify */
193
+ /* ****************************************************************************************** */
125
194
  verify: `Usage: mago-ski verify SKILL_DIR [--policy FILE] [--name NAME] [--certificate FILE] [--json]
126
195
 
127
196
  Checks one Skill against the policy's trust root and revocation list, and prints its verdict.
128
197
 
129
- --policy FILE policy file (default: .mago-ski/policy.json)
198
+ --policy FILE policy file (default: $MAGO_SKI_POLICY, which must be absolute, else ~/.mago-ski/policy.json;
199
+ never a file in the current directory, which the code under review may control)
130
200
  --name NAME Skill name to check (default: "name" in SKILL.md, else the directory name)
131
201
  --certificate FILE also try this certificate
132
202
  --json print the result as JSON
133
203
 
134
204
  Exit code 0 when VERIFIED, 1 for any other verdict, 2 for usage or input errors.`,
205
+ /* ******************************************* */
206
+ /* Per-command "verify" -> "verify-all" */
207
+ /* ******************************************* */
135
208
  'verify-all': `Usage: mago-ski verify-all [--policy FILE] [--json]
136
209
 
137
210
  Checks every Skill found under the policy's skill_dirs and prints one line per Skill and a summary.
138
211
  Exits 1 if any Skill is not VERIFIED, in shadow mode too (shadow mode affects hosts, not this exit code).`,
212
+ /* ****************************************************************************************** */
213
+ /** Per-command: digest */
214
+ /* ****************************************************************************************** */
139
215
  digest: `Usage: mago-ski digest SKILL_DIR [--explain]
140
216
 
141
217
  Prints the Skill's tree digest (sha256:...). --explain also lists every covered file, its hash and
142
218
  executable bit, and the paths excluded from the digest.`,
219
+ /* ****************************************************************************************** */
220
+ /** Per-command: diff */
221
+ /* ****************************************************************************************** */
143
222
  diff: `Usage: mago-ski diff --base DIR --candidate DIR
144
223
 
145
224
  Compares two versions of a Skill: changed files and Markdown sections, executable-bit changes, and added
146
225
  or removed network origins. Exits 1 when the digest changed, since that always needs a new certificate.`,
226
+ /* ****************************************************************************************** */
227
+ /** Per-command: inspect */
228
+ /* ****************************************************************************************** */
147
229
  inspect: `Usage: mago-ski inspect CERTIFICATE
148
230
 
149
231
  Prints a certificate's Skill, digest, approver, dates and reason. Checks structure only; use
150
232
  "mago-ski verify" to check its signature against your trust root.`,
233
+ /* ****************************************************************************************** */
234
+ /** Per-command: root recovery */
235
+ /* ****************************************************************************************** */
236
+ 'root adopt': `Usage: mago-ski root adopt --root-key FILE --from-root-fingerprint ID --trust-root FILE --revocations FILE [options]
237
+
238
+ After a rotate root event: re-signs the trust root and revocation list with the new root key. Every approver and
239
+ revocation entry is kept, and each document gets the next version. Both files are updated in place.
240
+
241
+ --root-key FILE the new root private key (the rotate event's new root)
242
+ --from-root-fingerprint ID the root key the current documents are signed by
243
+ --trust-root-expires DUR new trust root lifetime (default 365d)
244
+ --revocations-expires DUR new revocation list lifetime (default 30d)
245
+
246
+ The current documents may have been signed by a leaked key: review the printed approvers before publishing.
247
+ ${DURATION_NOTE}`,
248
+ recovery: `Usage: mago-ski recovery init --public-key FILE [--public-key ...] --rotate-threshold N --revoke-threshold N
249
+
250
+ Prints the "recovery" block for a mago.policy/v2 policy: the recovery keys' fingerprints and both thresholds.
251
+ Recovery keys only sign root events. Keep each one offline, with a different person, never next to the root key.
252
+ 1 <= revoke-threshold <= rotate-threshold <= number of keys; 3 keys, rotate 2, revoke 1 is a good default.`,
253
+ 'recovery init': `Usage: mago-ski recovery init --public-key FILE [--public-key ...] --rotate-threshold N --revoke-threshold N
254
+
255
+ Prints the "recovery" block for a mago.policy/v2 policy: the recovery keys' fingerprints and both thresholds.
256
+ Recovery keys only sign root events. Keep each one offline, with a different person, never next to the root key.
257
+ 1 <= revoke-threshold <= rotate-threshold <= number of keys; 3 keys, rotate 2, revoke 1 is a good default.`,
258
+ 'root-events': `Usage: mago-ski root-events <init | prepare-revoke | prepare-rotate | show | sign | append> [options]
259
+
260
+ Manages the root event log: signed, numbered events that revoke or replace the root key.
261
+ Run "mago-ski root-events <subcommand> --help" for details.`,
262
+ 'root-events init': `Usage: mago-ski root-events init --out FILE
263
+
264
+ Writes an empty root event log. Publish it next to the trust root: a policy with "recovery" needs the file to exist.`,
265
+ 'root-events prepare-revoke': `Usage: mago-ski root-events prepare-revoke --policy FILE --signer-public FILE [--signer-public ...] --reason TEXT --out FILE
266
+
267
+ Writes an unsigned proposal to revoke the active root key. Hosts that read the event block every Skill, in shadow
268
+ mode too, until a rotate event. List every recovery key that will sign (at least revoke_threshold of them).
269
+
270
+ --policy FILE the organization's policy (names the root event log)
271
+ --signer-public FILE public key of a recovery key that will sign; repeat for several
272
+ --reason TEXT shown in every host's block message (at most 1024 characters)
273
+ --out FILE the proposal file (must not exist yet)`,
274
+ 'root-events prepare-rotate': `Usage: mago-ski root-events prepare-rotate --policy FILE --new-root-public FILE --signer-public FILE [...] --reason TEXT --out FILE [options]
275
+
276
+ Writes an unsigned proposal to replace the root key, and optionally the recovery set or the timestamp key.
277
+ It must be signed by rotate_threshold keys of the current recovery set, the new set's rotate_threshold keys,
278
+ the new root key, and the new timestamp key if one is given.
279
+
280
+ --policy FILE the organization's policy (names the root event log)
281
+ --new-root-public FILE the new root public key (may be the current root to change only the other keys)
282
+ --signer-public FILE public key of a recovery key that will sign; repeat for several
283
+ --new-recovery-public FILE a key of the new recovery set; repeat for each (default: keep the current set)
284
+ --rotate-threshold N the new set's rotate threshold (required with --new-recovery-public)
285
+ --revoke-threshold N the new set's revoke threshold (required with --new-recovery-public)
286
+ --new-timestamp-public FILE a new timestamp key
287
+ --reason TEXT why (at most 1024 characters)
288
+ --out FILE the proposal file (must not exist yet)`,
289
+ 'root-events show': `Usage: mago-ski root-events show PROPOSAL [--policy FILE]
290
+
291
+ Prints what a proposal does (action, number, root key, new keys, reason), who has signed and who still must.
292
+ With --policy, also checks that it is the next event of the published log. Run it before you sign, and compare
293
+ the output with what was agreed through a channel other than the one that delivered the proposal.`,
294
+ 'root-events sign': `Usage: mago-ski root-events sign PROPOSAL --key FILE [--policy FILE]
295
+
296
+ Adds your signature to a proposal, in place, and prints the event you signed and who still has to sign. Refuses a
297
+ key the event does not list. With --policy, refuses a proposal that is not the next event of the published log.
298
+ Check the event with "mago-ski root-events show" first: your signature covers everything in it.`,
299
+ 'root-events append': `Usage: mago-ski root-events append PROPOSAL --policy FILE
300
+
301
+ Adds a fully signed proposal to the policy's root event log, after checking the whole new log exactly as a host
302
+ would. Prepare proposals against the published log, never a private copy: two events with the same number are a
303
+ fork, and hosts fail closed on a fork.`,
304
+ timestamp: `Usage: mago-ski timestamp sign --policy FILE --key FILE [--expires DUR] [--version N]
305
+
306
+ Signs the policy's freshness timestamp: the digests of the root event log, trust root and revocation list as they
307
+ are now, with the next version. Run it from an automated job every 6 hours with a 24h lifetime, and publish the
308
+ timestamp together with the documents it names.
309
+
310
+ --key FILE the active timestamp private key (keep it away from the root key)
311
+ --expires DUR lifetime (default 24h; at most the policy's freshness max_lifetime)
312
+ --version N the version to use, when the current timestamp file cannot be read`,
313
+ 'timestamp sign': `Usage: mago-ski timestamp sign --policy FILE --key FILE [--expires DUR] [--version N]
314
+
315
+ Signs the policy's freshness timestamp: the digests of the root event log, trust root and revocation list as they
316
+ are now, with the next version. Run it from an automated job every 6 hours with a 24h lifetime, and publish the
317
+ timestamp together with the documents it names.
318
+
319
+ --key FILE the active timestamp private key (keep it away from the root key)
320
+ --expires DUR lifetime (default 24h; at most the policy's freshness max_lifetime)
321
+ --version N the version to use, when the current timestamp file cannot be read`,
322
+ policy: `Usage: mago-ski policy check [--policy FILE] [--json]
323
+
324
+ Loads the policy, walks the root event log, checks the timestamp if "freshness" is set, verifies the trust root and
325
+ revocation list against the active root, and prints the active keys and thresholds. Never writes the host state.
326
+ Exits 0 when everything checks, 1 otherwise: use it to gate a policy rollout.`,
327
+ 'policy check': `Usage: mago-ski policy check [--policy FILE] [--json]
328
+
329
+ Loads the policy, walks the root event log, checks the timestamp if "freshness" is set, verifies the trust root and
330
+ revocation list against the active root, and prints the active keys and thresholds. Never writes the host state.
331
+ Exits 0 when everything checks, 1 otherwise: use it to gate a policy rollout.`,
151
332
  };
333
+ /* ****************************************************************************************** */
334
+ /* Utility functions for the CLI. */
335
+ const require = createRequire(import.meta.url);
152
336
  function readVersion() {
153
- for (const candidate of ['../package.json', '../../package.json']) {
154
- try {
155
- const pkg = JSON.parse(readFileSync(fileURLToPath(new URL(candidate, import.meta.url)), 'utf8'));
156
- if ((pkg.name === '@mago-foundation/mago-ski' || pkg.name === 'mago-ski') && pkg.version)
157
- return pkg.version;
158
- }
159
- catch {
160
- // try the next location (source tree vs. built dist/)
161
- }
337
+ try {
338
+ const pkg = require('#package.json');
339
+ return pkg.version ?? 'unknown';
340
+ }
341
+ catch {
342
+ return 'unknown';
162
343
  }
163
- return 'unknown';
164
344
  }
345
+ /* Usage error thrown for when users misuse the CLI. */
165
346
  class UsageError extends Error {
166
347
  }
348
+ /* The actual boolean flags that should take no value. */
167
349
  const BOOLEAN_FLAGS = new Set(['--json', '--explain', '--help']);
350
+ /* flags Map: A map of flags to their values. */
351
+ function addFlag(flags, flag, value) {
352
+ const values = flags.get(flag) ?? [];
353
+ values.push(value);
354
+ flags.set(flag, values);
355
+ }
356
+ /* Parses command-line arguments into a Parsed object. */
168
357
  function parseArgs(args) {
169
- const parsed = { positional: [], flags: new Map(), booleans: new Set() };
170
- for (let index = 0; index < args.length; index += 1) {
358
+ const parsed = {
359
+ positional: [],
360
+ flags: new Map(),
361
+ booleans: new Set()
362
+ };
363
+ for (let index = 0; index < args.length; index++) {
171
364
  const arg = args[index];
172
- if (BOOLEAN_FLAGS.has(arg)) {
365
+ /* 1. If it's a boolean flag, add it to the set of booleans. */
366
+ if (BOOLEAN_FLAGS.has(arg))
173
367
  parsed.booleans.add(arg);
174
- }
368
+ /* 2. If it starts with --, it's a flag with a value. */
175
369
  else if (arg.startsWith('--')) {
176
370
  const value = args[index + 1];
371
+ /* 3. If the value is missing or starts with --, throw an error. */
177
372
  if (value === undefined || value.startsWith('--') || value === '')
178
373
  throw new UsageError(`Missing value for ${arg}`);
179
- parsed.flags.set(arg, [...(parsed.flags.get(arg) ?? []), value]);
374
+ addFlag(parsed.flags, arg, value);
180
375
  index += 1;
181
376
  }
182
- else {
377
+ else
183
378
  parsed.positional.push(arg);
184
- }
185
379
  }
186
380
  return parsed;
187
381
  }
188
- function allow(parsed, allowed, positional, repeatable = []) {
382
+ /* Validation function */
383
+ function allow(parsed, allowed = [], positional = 0, repeatable = []) {
384
+ /* Check flags for validity and repeatability. */
189
385
  for (const [flag, values] of parsed.flags) {
190
386
  if (!allowed.includes(flag))
191
387
  throw new UsageError(`Unsupported option ${flag}`);
192
388
  if (values.length > 1 && !repeatable.includes(flag))
193
389
  throw new UsageError(`${flag} may be given only once`);
194
390
  }
391
+ /* Check boolean flags for validity. */
195
392
  for (const flag of parsed.booleans)
196
- if (flag !== '--json' && flag !== '--explain' && !allowed.includes(flag))
393
+ if (!BOOLEAN_FLAGS.has(flag) && !allowed.includes(flag))
197
394
  throw new UsageError(`Unsupported option ${flag}`);
198
- if (parsed.positional.length !== positional)
199
- throw new UsageError(`Expected ${positional} positional argument(s), got ${parsed.positional.length}`);
395
+ /* Check positional arguments count. */
396
+ const count = parsed.positional.length;
397
+ const { min, max } = typeof positional === 'number'
398
+ ? {
399
+ min: positional,
400
+ max: positional
401
+ } : positional;
402
+ /* Exact? */
403
+ if (min !== undefined && min === max && count !== min)
404
+ throw new UsageError(`Expected exactly ${min} positional argument(s), got ${count}`);
405
+ /* Under minimum? */
406
+ if (min !== undefined && count < min)
407
+ throw new UsageError(`Expected at least ${min} positional argument(s), got ${count}`);
408
+ /* Over maximum? */
409
+ if (max !== undefined && count > max)
410
+ throw new UsageError(`Expected at most ${max} positional argument(s), got ${count}`);
200
411
  }
412
+ /* First value of a flag, or throw if missing. */
201
413
  function one(parsed, flag) {
202
414
  const value = parsed.flags.get(flag)?.[0];
203
415
  if (!value)
204
416
  throw new UsageError(`${flag} is required`);
205
417
  return value;
206
418
  }
419
+ /* ****************************************************************************************** */
420
+ /* Optional first value of a flag, or undefined if missing. */
207
421
  function optional(parsed, flag) {
208
422
  return parsed.flags.get(flag)?.[0];
209
423
  }
424
+ /* Prints a value as JSON to stdout. */
210
425
  function print(value) {
211
426
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
212
427
  }
@@ -219,34 +434,83 @@ function printResult(result, json) {
219
434
  const mark = result.verdict === 'VERIFIED' ? 'ok' : 'FAIL';
220
435
  process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${result.skillName} ${result.reason}\n`);
221
436
  }
437
+ /* ****************************************************************************************** */
222
438
  async function runRoot(sub, parsed, now) {
223
439
  if (sub === 'init') {
224
440
  allow(parsed, ['--root-key', '--trust-root', '--revocations', '--trust-root-expires', '--revocations-expires'], 0);
225
441
  const result = await initRoot({
226
- rootKeyPath: one(parsed, '--root-key'), trustRootOut: one(parsed, '--trust-root'), revocationsOut: one(parsed, '--revocations'), now,
227
- trustRootExpires: optional(parsed, '--trust-root-expires'), revocationsExpires: optional(parsed, '--revocations-expires'),
442
+ rootKeyPath: one(parsed, '--root-key'),
443
+ trustRootOut: one(parsed, '--trust-root'),
444
+ revocationsOut: one(parsed, '--revocations'),
445
+ now,
446
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
447
+ revocationsExpires: optional(parsed, '--revocations-expires'),
448
+ });
449
+ print({
450
+ status: 'ROOT_INITIALIZED',
451
+ root_fingerprint: result.rootKeyId,
452
+ trust_root: result.trustRoot,
453
+ revocations: result.revocations,
454
+ next: 'Store the root private key offline. Put root_fingerprint in each host policy.'
228
455
  });
229
- print({ status: 'ROOT_INITIALIZED', root_fingerprint: result.rootKeyId, trust_root: result.trustRoot, revocations: result.revocations,
230
- next: 'Store the root private key offline. Put root_fingerprint in each host policy.' });
231
456
  return 0;
232
457
  }
233
458
  if (sub === 'add-approver') {
234
- allow(parsed, ['--root-key', '--trust-root', '--out', '--public-key', '--name', '--scope', '--expires', '--trust-root-expires'], 0, ['--scope']);
459
+ allow(parsed, ['--root-key', '--trust-root', '--out', '--public-key', '--name', '--scope', '--expires', '--trust-root-expires', '--policy'], 0, ['--scope']);
460
+ const policyFile = optional(parsed, '--policy');
461
+ const forbidden = policyFile === undefined ? undefined : await forbiddenApproverKeys(await loadPolicy(policyFile), now);
235
462
  const result = await addApprover({
236
- rootKeyPath: one(parsed, '--root-key'), trustRootPath: one(parsed, '--trust-root'), out: optional(parsed, '--out'), now,
237
- trustRootExpires: optional(parsed, '--trust-root-expires'), publicKeyPath: one(parsed, '--public-key'),
238
- name: one(parsed, '--name'), scopes: parsed.flags.get('--scope') ?? [], expires: one(parsed, '--expires'),
463
+ rootKeyPath: one(parsed, '--root-key'),
464
+ trustRootPath: one(parsed, '--trust-root'),
465
+ out: optional(parsed, '--out'),
466
+ now,
467
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
468
+ publicKeyPath: one(parsed, '--public-key'),
469
+ name: one(parsed, '--name'),
470
+ scopes: parsed.flags.get('--scope') ?? [],
471
+ expires: one(parsed, '--expires'),
472
+ ...(forbidden ? { forbidden } : {}),
473
+ });
474
+ print({
475
+ status: 'APPROVER_ADDED',
476
+ key_id: result.keyId,
477
+ trust_root_version: result.version,
478
+ trust_root: result.path
239
479
  });
240
- print({ status: 'APPROVER_ADDED', key_id: result.keyId, trust_root_version: result.version, trust_root: result.path });
241
480
  return 0;
242
481
  }
243
482
  if (sub === 'remove-approver') {
244
483
  allow(parsed, ['--root-key', '--trust-root', '--out', '--key-id', '--trust-root-expires'], 0);
245
484
  const result = await removeApprover({
246
- rootKeyPath: one(parsed, '--root-key'), trustRootPath: one(parsed, '--trust-root'), out: optional(parsed, '--out'), now,
247
- trustRootExpires: optional(parsed, '--trust-root-expires'), keyId: validateKeyId(one(parsed, '--key-id'), '--key-id'),
485
+ rootKeyPath: one(parsed, '--root-key'),
486
+ trustRootPath: one(parsed, '--trust-root'),
487
+ out: optional(parsed, '--out'),
488
+ now,
489
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
490
+ keyId: validateKeyId(one(parsed, '--key-id'), '--key-id'),
491
+ });
492
+ print({
493
+ status: 'APPROVER_REMOVED',
494
+ trust_root_version: result.version,
495
+ trust_root: result.path
496
+ });
497
+ return 0;
498
+ }
499
+ if (sub === 'renew') {
500
+ allow(parsed, ['--root-key', '--trust-root', '--out', '--expires'], 0);
501
+ const result = await renewTrustRoot({
502
+ rootKeyPath: one(parsed, '--root-key'),
503
+ trustRootPath: one(parsed, '--trust-root'),
504
+ out: optional(parsed, '--out'),
505
+ now,
506
+ expires: one(parsed, '--expires'),
507
+ });
508
+ print({
509
+ status: 'TRUST_ROOT_RENEWED',
510
+ trust_root_version: result.version,
511
+ trust_root: result.path,
512
+ expires_at: formatTimestamp(result.expiresAt),
248
513
  });
249
- print({ status: 'APPROVER_REMOVED', trust_root_version: result.version, trust_root: result.path });
250
514
  return 0;
251
515
  }
252
516
  if (sub === 'show') {
@@ -259,7 +523,28 @@ async function runRoot(sub, parsed, now) {
259
523
  });
260
524
  return 0;
261
525
  }
262
- throw new UsageError('Unknown root command; use init, add-approver, remove-approver or show');
526
+ if (sub === 'adopt') {
527
+ allow(parsed, ['--root-key', '--from-root-fingerprint', '--trust-root', '--revocations', '--trust-root-expires', '--revocations-expires'], 0);
528
+ const result = await adoptTrustDocuments({
529
+ rootKeyPath: one(parsed, '--root-key'),
530
+ fromRootKeyId: validateKeyId(one(parsed, '--from-root-fingerprint'), '--from-root-fingerprint'),
531
+ trustRootPath: one(parsed, '--trust-root'),
532
+ revocationsPath: one(parsed, '--revocations'),
533
+ now,
534
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
535
+ revocationsExpires: optional(parsed, '--revocations-expires'),
536
+ });
537
+ print({
538
+ status: 'TRUST_DOCUMENTS_ADOPTED',
539
+ root_key_id: result.trustRoot.root.keyId,
540
+ trust_root_version: result.trustRootVersion,
541
+ revocations_version: result.revocationsVersion,
542
+ approvers: result.trustRoot.approvers.map((entry) => ({ name: entry.name, key_id: entry.keyId, scopes: entry.scopes, expires_at: formatTimestamp(entry.expiresAt) })),
543
+ next: 'Review the approvers above (the old key may have been misused), then publish both files.',
544
+ });
545
+ return 0;
546
+ }
547
+ throw new UsageError('Unknown root command; use init, add-approver, remove-approver, renew, show or adopt');
263
548
  }
264
549
  async function runRevoke(sub, parsed, now) {
265
550
  const common = ['--root-key', '--revocations', '--out', '--expires'];
@@ -281,15 +566,200 @@ async function runRevoke(sub, parsed, now) {
281
566
  ...(sub === 'key' ? { revokeKey: validateKeyId(one(parsed, '--key-id'), '--key-id'), reason: one(parsed, '--reason') } : {}),
282
567
  ...(sub === 'digest' ? { revokeDigest: one(parsed, '--digest'), reason: one(parsed, '--reason') } : {}),
283
568
  });
284
- print({ status: sub === 'refresh' ? 'REVOCATIONS_REFRESHED' : 'REVOKED', revocations_version: result.version, expires_at: formatTimestamp(result.expiresAt), revocations: result.path });
569
+ print({
570
+ status: sub === 'refresh' ? 'REVOCATIONS_REFRESHED' : 'REVOKED',
571
+ revocations_version: result.version,
572
+ expires_at: formatTimestamp(result.expiresAt),
573
+ revocations: result.path
574
+ });
575
+ return 0;
576
+ }
577
+ /** Loads the policy named by --policy, else the host default. The checkout being verified never chooses its own root. */
578
+ async function loadCliPolicy(parsed) {
579
+ const explicit = optional(parsed, '--policy');
580
+ let policyPath;
581
+ try {
582
+ policyPath = explicit ?? defaultPolicyPath();
583
+ }
584
+ catch (error) {
585
+ throw new UsageError(error.message);
586
+ }
587
+ try {
588
+ return await loadPolicy(policyPath);
589
+ }
590
+ catch (error) {
591
+ const missing = error;
592
+ if (!explicit && missing?.code === 'ENOENT') {
593
+ throw new UsageError(`No policy at ${policyPath}. Pass --policy FILE, or set MAGO_SKI_POLICY to an absolute path`);
594
+ }
595
+ // Only when the policy file itself is missing; a missing trust root or other input keeps its own error.
596
+ if (missing?.code === 'ENOENT' && missing.path === path.resolve(policyPath)) {
597
+ throw new UsageError(`Policy file not found: ${path.resolve(policyPath)}`);
598
+ }
599
+ throw error;
600
+ }
601
+ }
602
+ function integerFlag(parsed, flag) {
603
+ const value = optional(parsed, flag);
604
+ if (value === undefined)
605
+ return undefined;
606
+ if (!/^[0-9]{1,6}$/u.test(value))
607
+ throw new UsageError(`${flag} must be a positive integer`);
608
+ return Number(value);
609
+ }
610
+ async function requiredPolicy(parsed) {
611
+ one(parsed, '--policy');
612
+ return await loadCliPolicy(parsed);
613
+ }
614
+ async function runRecovery(sub, parsed) {
615
+ if (sub !== 'init')
616
+ throw new UsageError('Unknown recovery command; use init');
617
+ allow(parsed, ['--public-key', '--rotate-threshold', '--revoke-threshold'], 0, ['--public-key']);
618
+ const rotate = integerFlag(parsed, '--rotate-threshold');
619
+ const revoke = integerFlag(parsed, '--revoke-threshold');
620
+ if (rotate === undefined || revoke === undefined)
621
+ throw new UsageError('--rotate-threshold and --revoke-threshold are required');
622
+ const keys = parsed.flags.get('--public-key') ?? [];
623
+ if (keys.length === 0)
624
+ throw new UsageError('--public-key is required');
625
+ const set = await buildRecoverySet({ publicKeyPaths: keys, rotateThreshold: rotate, revokeThreshold: revoke });
626
+ print({ recovery: recoverySetJson(set), next: 'Put "recovery" in each host policy (policy_version "mago.policy/v2"), with "root_events" naming an empty log.' });
627
+ return 0;
628
+ }
629
+ async function runRootEvents(sub, parsed, now) {
630
+ if (sub === 'init') {
631
+ allow(parsed, ['--out'], 0);
632
+ print({ status: 'ROOT_EVENTS_INITIALIZED', root_events: await initRootEventLog(one(parsed, '--out')) });
633
+ return 0;
634
+ }
635
+ if (sub === 'prepare-revoke' || sub === 'prepare-rotate') {
636
+ const common = ['--policy', '--signer-public', '--reason', '--out'];
637
+ if (sub === 'prepare-revoke')
638
+ allow(parsed, common, 0, ['--signer-public']);
639
+ else
640
+ allow(parsed, [...common, '--new-root-public', '--new-recovery-public', '--rotate-threshold', '--revoke-threshold', '--new-timestamp-public'], 0, ['--signer-public', '--new-recovery-public']);
641
+ const policy = await requiredPolicy(parsed);
642
+ const prepared = await prepareRootEvent({
643
+ policy,
644
+ action: sub === 'prepare-revoke' ? 'revoke' : 'rotate',
645
+ reason: one(parsed, '--reason'),
646
+ signerPublicPaths: parsed.flags.get('--signer-public') ?? [],
647
+ out: one(parsed, '--out'),
648
+ now,
649
+ newRootPublicPath: optional(parsed, '--new-root-public'),
650
+ newRecoveryPublicPaths: parsed.flags.get('--new-recovery-public'),
651
+ rotateThreshold: integerFlag(parsed, '--rotate-threshold'),
652
+ revokeThreshold: integerFlag(parsed, '--revoke-threshold'),
653
+ newTimestampPublicPath: optional(parsed, '--new-timestamp-public'),
654
+ });
655
+ print({
656
+ status: 'ROOT_EVENT_PREPARED', proposal: prepared.path, sequence: prepared.event.sequence, action: prepared.event.action,
657
+ root_key_id: prepared.event.rootKeyId, must_be_signed_by: prepared.required,
658
+ next: 'Each listed key holder runs "mago-ski root-events sign PROPOSAL --key FILE"; then "mago-ski root-events append".',
659
+ });
660
+ return 0;
661
+ }
662
+ if (sub === 'show') {
663
+ allow(parsed, ['--policy'], 1);
664
+ const policy = optional(parsed, '--policy') ? await loadCliPolicy(parsed) : undefined;
665
+ const result = await showRootEvent({ proposalPath: parsed.positional[0], policy, now });
666
+ print({ event: describeRootEvent(result.event), signatures: result.signed, still_missing: result.missing, ...(policy ? { extends_log: true } : {}) });
667
+ return 0;
668
+ }
669
+ if (sub === 'sign') {
670
+ allow(parsed, ['--key', '--policy'], 1);
671
+ const policy = optional(parsed, '--policy') ? await loadCliPolicy(parsed) : undefined;
672
+ const result = await signRootEvent({ proposalPath: parsed.positional[0], keyPath: one(parsed, '--key'), policy, now });
673
+ print({ status: 'ROOT_EVENT_SIGNED', signed_by: result.keyId, event: describeRootEvent(result.event), signatures: result.signed, still_missing: result.missing });
674
+ return 0;
675
+ }
676
+ if (sub === 'append') {
677
+ allow(parsed, ['--policy'], 1);
678
+ const policy = await requiredPolicy(parsed);
679
+ const result = await appendRootEvent({ policy, proposalPath: parsed.positional[0], now });
680
+ print({
681
+ status: 'ROOT_EVENT_APPENDED', root_events: result.path, sequence: result.event.sequence, action: result.event.action,
682
+ active_root_key_id: result.walk.activeRootKeyId, root_revoked: result.walk.revoked !== null,
683
+ next: result.walk.revoked
684
+ ? 'Publish the log now. Hosts that read it block every Skill until a rotate event.'
685
+ : 'Publish the log. Then sign a trust root and revocation list with the active root ("mago-ski root adopt") and re-sign the timestamp.',
686
+ });
687
+ return 0;
688
+ }
689
+ throw new UsageError('Unknown root-events command; use init, prepare-revoke, prepare-rotate, show, sign or append');
690
+ }
691
+ async function runTimestamp(sub, parsed, now) {
692
+ if (sub !== 'sign')
693
+ throw new UsageError('Unknown timestamp command; use sign');
694
+ allow(parsed, ['--policy', '--key', '--expires', '--version'], 0);
695
+ const policy = await requiredPolicy(parsed);
696
+ const result = await signPolicyTimestamp({
697
+ policy, keyPath: one(parsed, '--key'), now, expires: optional(parsed, '--expires'), version: integerFlag(parsed, '--version'),
698
+ });
699
+ print({
700
+ status: 'TIMESTAMP_SIGNED', timestamp: result.path, version: result.timestamp.version,
701
+ expires_at: formatTimestamp(result.timestamp.expiresAt), root_events_count: result.timestamp.rootEvents.count,
702
+ trust_root_version: result.timestamp.trustRoot.version, revocations_version: result.timestamp.revocations.version,
703
+ });
285
704
  return 0;
286
705
  }
706
+ async function runPolicyCheck(sub, parsed, now) {
707
+ if (sub !== 'check')
708
+ throw new UsageError('Unknown policy command; use check');
709
+ allow(parsed, ['--policy'], 0);
710
+ const policy = await loadCliPolicy(parsed);
711
+ const trust = await loadPolicyTrust(policy, now, { recordVersions: false });
712
+ const root = policy.recovery ? await currentRootState(policy, now).catch(() => null) : null;
713
+ const report = {
714
+ status: trust.ok ? 'OK' : trust.rootRevoked ? 'ROOT_REVOKED' : 'TRUST_UNAVAILABLE',
715
+ policy: policy.path,
716
+ mode: policy.mode,
717
+ effective_mode: effectiveMode(policy.mode, trust),
718
+ root_fingerprint: policy.rootKeyId,
719
+ recovery: policy.recovery !== null,
720
+ };
721
+ if (root) {
722
+ report.active_root_key_id = root.activeRootKeyId;
723
+ report.root_events = root.count;
724
+ report.recovery_set = recoverySetJson(root.recovery);
725
+ report.timestamp_key_id = root.timestampKeyId;
726
+ if (root.revoked)
727
+ report.revoked_by_event = root.revoked.sequence;
728
+ }
729
+ if (trust.ok) {
730
+ report.trust_root_version = trust.context.trustRoot.version;
731
+ report.revocations_version = trust.context.revocations.version;
732
+ report.trust_root_expires_at = formatTimestamp(trust.context.trustRoot.expiresAt);
733
+ report.revocations_expires_at = formatTimestamp(trust.context.revocations.expiresAt);
734
+ report.approvers = trust.context.trustRoot.approvers.length;
735
+ if (trust.context.root?.timestamp) {
736
+ report.timestamp_version = trust.context.root.timestamp.version;
737
+ report.timestamp_expires_at = formatTimestamp(trust.context.root.timestamp.expiresAt);
738
+ }
739
+ }
740
+ else {
741
+ report.verdict = trust.verdict;
742
+ report.reason = trust.reason;
743
+ }
744
+ print(report);
745
+ return trust.ok ? 0 : 1;
746
+ }
287
747
  async function runVerify(parsed, now) {
288
748
  allow(parsed, ['--policy', '--name', '--certificate'], 1);
289
- const policy = await loadPolicy(optional(parsed, '--policy') ?? DEFAULT_POLICY_PATH);
749
+ const policy = await loadCliPolicy(parsed);
290
750
  const skillDir = parsed.positional[0];
751
+ const trust = await loadPolicyTrust(policy, now);
752
+ if (!trust.ok) {
753
+ // A trust failure affects every Skill: one record for the host, not one per Skill.
754
+ const name = optional(parsed, '--name') ?? await resolveSkillName(skillDir).catch(() => path.basename(path.resolve(skillDir)));
755
+ await appendDecision(policy.decisionLogPath, trustFailureRecord(trust, policy.mode, now));
756
+ printResult(unverifiable(path.resolve(skillDir), name, trust.reason, now, trust.verdict), parsed.booleans.has('--json'));
757
+ return 1;
758
+ }
291
759
  const result = await verifyWithPolicy(policy, skillDir, {
292
- now, ...(optional(parsed, '--name') ? { skillName: one(parsed, '--name') } : {}),
760
+ now,
761
+ context: trust.context,
762
+ ...(optional(parsed, '--name') ? { skillName: one(parsed, '--name') } : {}),
293
763
  ...(optional(parsed, '--certificate') ? { certificate: one(parsed, '--certificate') } : {}),
294
764
  });
295
765
  await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'cli-verify'));
@@ -298,17 +768,25 @@ async function runVerify(parsed, now) {
298
768
  }
299
769
  async function runVerifyAll(parsed, now) {
300
770
  allow(parsed, ['--policy'], 0);
301
- const policy = await loadPolicy(optional(parsed, '--policy') ?? DEFAULT_POLICY_PATH);
771
+ const policy = await loadCliPolicy(parsed);
302
772
  if (policy.skillDirs.length === 0)
303
773
  throw new UsageError('Policy has no skill_dirs to scan');
304
774
  const { skillDirs, tooDeep } = await findSkillDirs(policy.skillDirs);
305
775
  const trust = await loadPolicyTrust(policy, now);
776
+ if (!trust.ok) {
777
+ // Reported once for the host instead of once per Skill, so it is not buried among identical lines.
778
+ const event = trustFailureEvent(trust);
779
+ await appendDecision(policy.decisionLogPath, trustFailureRecord(trust, policy.mode, now));
780
+ if (parsed.booleans.has('--json'))
781
+ process.stdout.write(`${JSON.stringify({ event, verdict: trust.verdict, reason: trust.reason, skills: skillDirs.length + tooDeep.length })}\n`);
782
+ else
783
+ process.stdout.write(`FAIL ${event.toUpperCase()} ${trust.reason}\n0/${skillDirs.length + tooDeep.length} Skills verified (mode: ${effectiveMode(policy.mode, trust)})\n`);
784
+ return 1;
785
+ }
306
786
  let failures = 0;
307
787
  const results = [];
308
788
  for (const skillDir of skillDirs) {
309
- results.push(trust.ok
310
- ? await verifyWithPolicy(policy, skillDir, { now, context: trust.context })
311
- : unverifiable(skillDir, path.basename(skillDir), trust.reason, now, trust.verdict));
789
+ results.push(await verifyWithPolicy(policy, skillDir, { now, context: trust.context }));
312
790
  }
313
791
  for (const directory of tooDeep)
314
792
  results.push(tooDeepResult(directory, now));
@@ -318,9 +796,8 @@ async function runVerifyAll(parsed, now) {
318
796
  await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'cli-verify-all'));
319
797
  printResult(result, parsed.booleans.has('--json'));
320
798
  }
321
- if (!parsed.booleans.has('--json')) {
799
+ if (!parsed.booleans.has('--json'))
322
800
  process.stdout.write(`${results.length - failures}/${results.length} Skills verified (mode: ${policy.mode})\n`);
323
- }
324
801
  return failures === 0 ? 0 : 1;
325
802
  }
326
803
  export async function runCli(argv = process.argv.slice(2), now = new Date()) {
@@ -344,7 +821,7 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
344
821
  process.stdout.write(`${text}\n`);
345
822
  return 0;
346
823
  }
347
- const hasSub = command === 'root' || command === 'revoke';
824
+ const hasSub = ['root', 'revoke', 'recovery', 'root-events', 'timestamp', 'policy'].includes(command);
348
825
  const parsed = parseArgs(argv.slice(hasSub ? 2 : 1));
349
826
  switch (command) {
350
827
  case 'keygen': {
@@ -358,17 +835,35 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
358
835
  return await runRoot(maybeSub, parsed, now);
359
836
  case 'revoke':
360
837
  return await runRevoke(maybeSub, parsed, now);
838
+ case 'recovery':
839
+ return await runRecovery(maybeSub, parsed);
840
+ case 'root-events':
841
+ return await runRootEvents(maybeSub, parsed, now);
842
+ case 'timestamp':
843
+ return await runTimestamp(maybeSub, parsed, now);
844
+ case 'policy':
845
+ return await runPolicyCheck(maybeSub, parsed, now);
361
846
  case 'approve': {
362
- allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out'], 1);
847
+ allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out', '--expect-digest'], 1);
363
848
  const result = await approveSkill({
364
- skillDir: parsed.positional[0], approverKeyPath: one(parsed, '--key'), now, expires: one(parsed, '--expires'),
849
+ skillDir: parsed.positional[0],
850
+ approverKeyPath: one(parsed, '--key'),
851
+ now,
852
+ expires: one(parsed, '--expires'),
365
853
  reason: one(parsed, '--reason'),
366
854
  ...(optional(parsed, '--name') ? { name: one(parsed, '--name') } : {}),
367
855
  ...(optional(parsed, '--previous') ? { previous: one(parsed, '--previous') } : {}),
368
856
  ...(optional(parsed, '--out') ? { out: one(parsed, '--out') } : {}),
857
+ ...(optional(parsed, '--expect-digest') ? { expectDigest: one(parsed, '--expect-digest') } : {}),
858
+ });
859
+ print({
860
+ status: 'CERTIFICATE_ISSUED',
861
+ skill: result.skillName,
862
+ digest: result.digest,
863
+ certificate_id: result.certificateId,
864
+ expires_at: formatTimestamp(result.expiresAt),
865
+ certificate: result.path
369
866
  });
370
- print({ status: 'CERTIFICATE_ISSUED', skill: result.skillName, digest: result.digest, certificate_id: result.certificateId,
371
- expires_at: formatTimestamp(result.expiresAt), certificate: result.path });
372
867
  return 0;
373
868
  }
374
869
  case 'verify':
@@ -378,15 +873,15 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
378
873
  case 'digest': {
379
874
  allow(parsed, [], 1);
380
875
  const tree = await collectSkillTree(parsed.positional[0]);
381
- if (parsed.booleans.has('--explain')) {
876
+ if (parsed.booleans.has('--explain'))
382
877
  print({ profile: TREE_PROFILE, digest: tree.digest, root: tree.root, total_bytes: tree.totalBytes, files: tree.files, excluded: tree.excluded });
383
- }
384
- else {
878
+ else
385
879
  process.stdout.write(`${tree.digest}\n`);
386
- }
387
880
  return 0;
388
881
  }
389
882
  case 'diff': {
883
+ if (parsed.positional.length > 0)
884
+ throw new UsageError(`diff takes the two directories as options: mago-ski diff --base ${parsed.positional[0]} --candidate ${parsed.positional[1] ?? 'DIR'}`);
390
885
  allow(parsed, ['--base', '--candidate'], 0);
391
886
  const result = await diffSkillTrees(one(parsed, '--base'), one(parsed, '--candidate'));
392
887
  print(result);
@@ -396,9 +891,15 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
396
891
  allow(parsed, [], 1);
397
892
  const certificate = parseCertificate(await readRegularFile(parsed.positional[0], 'Certificate', 8 * 1024 * 1024));
398
893
  print({
399
- certificate_id: certificate.id, skill: certificate.skillName, digest: certificate.digest, approver_key_id: certificate.approverKeyId,
400
- issued_at: formatTimestamp(certificate.issuedAt), expires_at: formatTimestamp(certificate.expiresAt), reason: certificate.reason,
401
- previous_digest: certificate.previousDigest, file_count: certificate.files.length,
894
+ certificate_id: certificate.id,
895
+ skill: certificate.skillName,
896
+ digest: certificate.digest,
897
+ approver_key_id: certificate.approverKeyId,
898
+ issued_at: formatTimestamp(certificate.issuedAt),
899
+ expires_at: formatTimestamp(certificate.expiresAt),
900
+ reason: certificate.reason,
901
+ previous_digest: certificate.previousDigest,
902
+ file_count: certificate.files.length,
402
903
  note: 'Structure only. Run mago-ski verify to check the signature against your trust root.',
403
904
  });
404
905
  return 0;