@mago-foundation/mago-ski 0.1.0 → 0.2.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.
package/dist/src/cli.js CHANGED
@@ -7,55 +7,81 @@ 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, findSkillDirs, loadPolicy, loadPolicyTrust, tooDeepResult, verifyWithPolicy, } from "./policy.js";
11
11
  import { isMainModule } from "./main-module.js";
12
12
  import { formatTimestamp } from "./time.js";
13
13
  import { collectSkillTree, TREE_PROFILE } from "./tree-digest.js";
14
14
  import { verifyTrustRoot } from "./trust-root.js";
15
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 { createRequire } from 'node:module';
17
+ const usage = `mago-ski — organization-approved Skill certificates,
18
+ enforced on the agent host
19
+
20
+ USAGE
21
+ mago-ski <command> [options]
22
+
23
+ KEYS AND TRUST (root key holder)
24
+ keygen Create an Ed25519 key pair
25
+ root init Create the trust root and revocation list
26
+ root add-approver Add or replace an approver
27
+ root remove-approver Remove an approver
28
+ root show Verify and print a trust root
29
+ revoke key Revoke an approver key
30
+ revoke digest Revoke one approved Skill version
31
+ revoke refresh Re-sign the revocation list
32
+
33
+ APPROVING SKILLS (reviewer)
34
+ approve SKILL_DIR Issue a certificate for a Skill
35
+
36
+ CHECKING SKILLS
37
+ verify SKILL_DIR Check one Skill, print its verdict
38
+ verify-all Check every Skill in the policy
39
+ digest SKILL_DIR Print a Skill's tree digest
40
+ diff Compare two versions of a Skill
41
+ inspect CERTIFICATE Print a certificate's contents
42
+
43
+ POLICY
44
+ --policy FILE, else $MAGO_SKI_POLICY, else
45
+ ~/.mago-ski/policy.json (never the current directory)
46
+
47
+ VERDICTS
48
+ VERIFIED UNAPPROVED_CHANGE NO_CERTIFICATE
49
+ UNTRUSTED_SIGNER REVOKED EXPIRED UNVERIFIABLE
50
+
51
+ EXIT CODES
52
+ 0 success, or VERIFIED
53
+ 1 any other verdict, or re-certification required
54
+ 2 usage or input error
55
+
56
+ Run "mago-ski <command> --help" for a command's options,
57
+ and "mago-ski --version" for the version.
58
+
59
+ A certificate records who approved an exact Skill
60
+ version. It does not certify that the Skill is safe.`;
43
61
  const DURATION_NOTE = 'Durations are a number plus d, h or m, for example 90d, 12h or 30m.';
62
+ /* ****************************************************************************************** */
44
63
  /** Per-command help: `mago-ski <command> --help`. Keys are "command" or "command subcommand". */
64
+ /* ****************************************************************************************** */
45
65
  const COMMAND_HELP = {
46
66
  keygen: `Usage: mago-ski keygen --private-key FILE --public-key FILE
47
67
 
48
68
  Creates an Ed25519 key pair for a root key or an approver key.
49
69
 
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
70
+ --private-key FILE where to write the private key (created with mode 600; must not exist yet)
71
+ --public-key FILE where to write the public key
52
72
 
53
73
  Keep private keys secret and outside every Skill directory; keygen refuses to write inside one.
54
74
  Prints the key id (sha256:...), which identifies the key in trust roots and revocations.`,
75
+ /* ****************************************************************************************** */
76
+ /** Per-command: root */
77
+ /* ****************************************************************************************** */
55
78
  root: `Usage: mago-ski root <init | add-approver | remove-approver | show> [options]
56
79
 
57
80
  Manages the organization's signed trust root (who may approve which Skills).
58
81
  Run "mago-ski root <subcommand> --help" for details.`,
82
+ /* *************************************** */
83
+ /* Per-command "root" -> "root init" */
84
+ /* *************************************** */
59
85
  'root init': `Usage: mago-ski root init --root-key FILE --trust-root OUT --revocations OUT [options]
60
86
 
61
87
  Creates version 1 of the signed trust root (no approvers yet) and an empty signed revocation list.
@@ -68,6 +94,9 @@ Creates version 1 of the signed trust root (no approvers yet) and an empty signe
68
94
 
69
95
  Prints root_fingerprint: put it in every host policy as "root_fingerprint".
70
96
  ${DURATION_NOTE}`,
97
+ /* ******************************************** */
98
+ /* Per-command "root" -> "root add-approver */
99
+ /* ******************************************** */
71
100
  '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
101
 
73
102
  Adds (or replaces) an approver and re-signs the trust root with the next version.
@@ -82,16 +111,28 @@ Adds (or replaces) an approver and re-signs the trust root with the next version
82
111
  --out FILE write the new trust root here instead
83
112
  --trust-root-expires DUR also set a new trust root lifetime
84
113
  ${DURATION_NOTE}`,
114
+ /* ************************************************* */
115
+ /* Per-command "root" -> "root remove-approver" */
116
+ /* *********************************************** */
85
117
  '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
118
 
87
119
  Removes an approver and re-signs the trust root. Certificates from that approver stop verifying once hosts read
88
120
  the new trust root. If the key may be compromised, also revoke it with "mago-ski revoke key".`,
121
+ /* ************************************** */
122
+ /* Per-command "root" -> "root show" */
123
+ /* ************************************** */
89
124
  'root show': `Usage: mago-ski root show --trust-root FILE --root-fingerprint ID
90
125
 
91
126
  Verifies a trust root against the pinned root fingerprint and prints its version, expiry and approvers.`,
127
+ /* ****************************************************************************************** */
128
+ /** Per-command: revoke */
129
+ /* ****************************************************************************************** */
92
130
  revoke: `Usage: mago-ski revoke <key | digest | refresh> [options]
93
131
 
94
132
  Updates the organization's signed revocation list. Run "mago-ski revoke <subcommand> --help" for details.`,
133
+ /* *************************************** */
134
+ /* Per-command "revoke" -> "revoke key" */
135
+ /* *************************************** */
95
136
  'revoke key': `Usage: mago-ski revoke key --root-key FILE --revocations FILE --key-id ID --reason TEXT [--expires DUR] [--out FILE]
96
137
 
97
138
  Revokes an approver key: every certificate it signed stops verifying once hosts read the new list.
@@ -100,14 +141,23 @@ Revokes an approver key: every certificate it signed stops verifying once hosts
100
141
  --reason TEXT shown in verdicts
101
142
  --expires DUR lifetime of the new list (default 30d)
102
143
  ${DURATION_NOTE}`,
144
+ /* ****************************************** */
145
+ /* Per-command "revoke" -> "revoke digest" */
146
+ /* ****************************************** */
103
147
  'revoke digest': `Usage: mago-ski revoke digest --root-key FILE --revocations FILE --digest sha256:... --reason TEXT [--expires DUR] [--out FILE]
104
148
 
105
149
  Revokes one approved Skill version (its tree digest), whoever signed it.
106
150
  ${DURATION_NOTE}`,
151
+ /* ******************************************* */
152
+ /* Per-command "revoke" -> "revoke refresh" */
153
+ /* ******************************************* */
107
154
  'revoke refresh': `Usage: mago-ski revoke refresh --root-key FILE --revocations FILE [--expires DUR] [--out FILE]
108
155
 
109
156
  Re-signs the revocation list with the next version and a new expiry, without changing its entries.
110
157
  Hosts refuse an expired list, so refresh it before it expires (default lifetime 30d).`,
158
+ /* ****************************************************************************************** */
159
+ /** Per-command: approve */
160
+ /* ****************************************************************************************** */
111
161
  approve: `Usage: mago-ski approve SKILL_DIR --key FILE --expires DUR --reason TEXT [options]
112
162
 
113
163
  Issues a certificate for the exact current bytes of a Skill, signed with your approver key.
@@ -118,95 +168,146 @@ Issues a certificate for the exact current bytes of a Skill, signed with your ap
118
168
  --name NAME Skill name (default: "name" in SKILL.md, else the directory name)
119
169
  --previous CERT|DIG the previously approved certificate or digest, for the update history
120
170
  --out FILE where to write the certificate (default: SKILL_DIR/.mago-ski-cert.json)
171
+ --expect-digest DIG the digest you reviewed (sha256:...); refuses to sign if the Skill changed since
121
172
 
122
173
  Refuses a Skill that contains a private key. A certificate records who approved which exact version;
123
174
  it does not certify that the Skill is safe.
124
175
  ${DURATION_NOTE}`,
176
+ /* ****************************************************************************************** */
177
+ /** Per-command: verify */
178
+ /* ****************************************************************************************** */
125
179
  verify: `Usage: mago-ski verify SKILL_DIR [--policy FILE] [--name NAME] [--certificate FILE] [--json]
126
180
 
127
181
  Checks one Skill against the policy's trust root and revocation list, and prints its verdict.
128
182
 
129
- --policy FILE policy file (default: .mago-ski/policy.json)
183
+ --policy FILE policy file (default: $MAGO_SKI_POLICY, which must be absolute, else ~/.mago-ski/policy.json;
184
+ never a file in the current directory, which the code under review may control)
130
185
  --name NAME Skill name to check (default: "name" in SKILL.md, else the directory name)
131
186
  --certificate FILE also try this certificate
132
187
  --json print the result as JSON
133
188
 
134
189
  Exit code 0 when VERIFIED, 1 for any other verdict, 2 for usage or input errors.`,
190
+ /* ******************************************* */
191
+ /* Per-command "verify" -> "verify-all" */
192
+ /* ******************************************* */
135
193
  'verify-all': `Usage: mago-ski verify-all [--policy FILE] [--json]
136
194
 
137
195
  Checks every Skill found under the policy's skill_dirs and prints one line per Skill and a summary.
138
196
  Exits 1 if any Skill is not VERIFIED, in shadow mode too (shadow mode affects hosts, not this exit code).`,
197
+ /* ****************************************************************************************** */
198
+ /** Per-command: digest */
199
+ /* ****************************************************************************************** */
139
200
  digest: `Usage: mago-ski digest SKILL_DIR [--explain]
140
201
 
141
202
  Prints the Skill's tree digest (sha256:...). --explain also lists every covered file, its hash and
142
203
  executable bit, and the paths excluded from the digest.`,
204
+ /* ****************************************************************************************** */
205
+ /** Per-command: diff */
206
+ /* ****************************************************************************************** */
143
207
  diff: `Usage: mago-ski diff --base DIR --candidate DIR
144
208
 
145
209
  Compares two versions of a Skill: changed files and Markdown sections, executable-bit changes, and added
146
210
  or removed network origins. Exits 1 when the digest changed, since that always needs a new certificate.`,
211
+ /* ****************************************************************************************** */
212
+ /** Per-command: inspect */
213
+ /* ****************************************************************************************** */
147
214
  inspect: `Usage: mago-ski inspect CERTIFICATE
148
215
 
149
216
  Prints a certificate's Skill, digest, approver, dates and reason. Checks structure only; use
150
217
  "mago-ski verify" to check its signature against your trust root.`,
151
218
  };
219
+ /* ****************************************************************************************** */
220
+ /* Utility functions for the CLI. */
221
+ const require = createRequire(import.meta.url);
152
222
  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
- }
223
+ try {
224
+ const pkg = require('#package.json');
225
+ return pkg.version ?? 'unknown';
226
+ }
227
+ catch {
228
+ return 'unknown';
162
229
  }
163
- return 'unknown';
164
230
  }
231
+ /* Usage error thrown for when users misuse the CLI. */
165
232
  class UsageError extends Error {
166
233
  }
234
+ /* The actual boolean flags that should take no value. */
167
235
  const BOOLEAN_FLAGS = new Set(['--json', '--explain', '--help']);
236
+ /* flags Map: A map of flags to their values. */
237
+ function addFlag(flags, flag, value) {
238
+ const values = flags.get(flag) ?? [];
239
+ values.push(value);
240
+ flags.set(flag, values);
241
+ }
242
+ /* Parses command-line arguments into a Parsed object. */
168
243
  function parseArgs(args) {
169
- const parsed = { positional: [], flags: new Map(), booleans: new Set() };
170
- for (let index = 0; index < args.length; index += 1) {
244
+ const parsed = {
245
+ positional: [],
246
+ flags: new Map(),
247
+ booleans: new Set()
248
+ };
249
+ for (let index = 0; index < args.length; index++) {
171
250
  const arg = args[index];
172
- if (BOOLEAN_FLAGS.has(arg)) {
251
+ /* 1. If it's a boolean flag, add it to the set of booleans. */
252
+ if (BOOLEAN_FLAGS.has(arg))
173
253
  parsed.booleans.add(arg);
174
- }
254
+ /* 2. If it starts with --, it's a flag with a value. */
175
255
  else if (arg.startsWith('--')) {
176
256
  const value = args[index + 1];
257
+ /* 3. If the value is missing or starts with --, throw an error. */
177
258
  if (value === undefined || value.startsWith('--') || value === '')
178
259
  throw new UsageError(`Missing value for ${arg}`);
179
- parsed.flags.set(arg, [...(parsed.flags.get(arg) ?? []), value]);
260
+ addFlag(parsed.flags, arg, value);
180
261
  index += 1;
181
262
  }
182
- else {
263
+ else
183
264
  parsed.positional.push(arg);
184
- }
185
265
  }
186
266
  return parsed;
187
267
  }
188
- function allow(parsed, allowed, positional, repeatable = []) {
268
+ /* Validation function */
269
+ function allow(parsed, allowed = [], positional = 0, repeatable = []) {
270
+ /* Check flags for validity and repeatability. */
189
271
  for (const [flag, values] of parsed.flags) {
190
272
  if (!allowed.includes(flag))
191
273
  throw new UsageError(`Unsupported option ${flag}`);
192
274
  if (values.length > 1 && !repeatable.includes(flag))
193
275
  throw new UsageError(`${flag} may be given only once`);
194
276
  }
277
+ /* Check boolean flags for validity. */
195
278
  for (const flag of parsed.booleans)
196
- if (flag !== '--json' && flag !== '--explain' && !allowed.includes(flag))
279
+ if (!BOOLEAN_FLAGS.has(flag) && !allowed.includes(flag))
197
280
  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}`);
281
+ /* Check positional arguments count. */
282
+ const count = parsed.positional.length;
283
+ const { min, max } = typeof positional === 'number'
284
+ ? {
285
+ min: positional,
286
+ max: positional
287
+ } : positional;
288
+ /* Exact? */
289
+ if (min !== undefined && min === max && count !== min)
290
+ throw new UsageError(`Expected exactly ${min} positional argument(s), got ${count}`);
291
+ /* Under minimum? */
292
+ if (min !== undefined && count < min)
293
+ throw new UsageError(`Expected at least ${min} positional argument(s), got ${count}`);
294
+ /* Over maximum? */
295
+ if (max !== undefined && count > max)
296
+ throw new UsageError(`Expected at most ${max} positional argument(s), got ${count}`);
200
297
  }
298
+ /* First value of a flag, or throw if missing. */
201
299
  function one(parsed, flag) {
202
300
  const value = parsed.flags.get(flag)?.[0];
203
301
  if (!value)
204
302
  throw new UsageError(`${flag} is required`);
205
303
  return value;
206
304
  }
305
+ /* ****************************************************************************************** */
306
+ /* Optional first value of a flag, or undefined if missing. */
207
307
  function optional(parsed, flag) {
208
308
  return parsed.flags.get(flag)?.[0];
209
309
  }
310
+ /* Prints a value as JSON to stdout. */
210
311
  function print(value) {
211
312
  process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
212
313
  }
@@ -219,34 +320,63 @@ function printResult(result, json) {
219
320
  const mark = result.verdict === 'VERIFIED' ? 'ok' : 'FAIL';
220
321
  process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${result.skillName} ${result.reason}\n`);
221
322
  }
323
+ /* ****************************************************************************************** */
222
324
  async function runRoot(sub, parsed, now) {
223
325
  if (sub === 'init') {
224
326
  allow(parsed, ['--root-key', '--trust-root', '--revocations', '--trust-root-expires', '--revocations-expires'], 0);
225
327
  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'),
328
+ rootKeyPath: one(parsed, '--root-key'),
329
+ trustRootOut: one(parsed, '--trust-root'),
330
+ revocationsOut: one(parsed, '--revocations'),
331
+ now,
332
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
333
+ revocationsExpires: optional(parsed, '--revocations-expires'),
334
+ });
335
+ print({
336
+ status: 'ROOT_INITIALIZED',
337
+ root_fingerprint: result.rootKeyId,
338
+ trust_root: result.trustRoot,
339
+ revocations: result.revocations,
340
+ next: 'Store the root private key offline. Put root_fingerprint in each host policy.'
228
341
  });
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
342
  return 0;
232
343
  }
233
344
  if (sub === 'add-approver') {
234
345
  allow(parsed, ['--root-key', '--trust-root', '--out', '--public-key', '--name', '--scope', '--expires', '--trust-root-expires'], 0, ['--scope']);
235
346
  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'),
347
+ rootKeyPath: one(parsed, '--root-key'),
348
+ trustRootPath: one(parsed, '--trust-root'),
349
+ out: optional(parsed, '--out'),
350
+ now,
351
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
352
+ publicKeyPath: one(parsed, '--public-key'),
353
+ name: one(parsed, '--name'),
354
+ scopes: parsed.flags.get('--scope') ?? [],
355
+ expires: one(parsed, '--expires'),
356
+ });
357
+ print({
358
+ status: 'APPROVER_ADDED',
359
+ key_id: result.keyId,
360
+ trust_root_version: result.version,
361
+ trust_root: result.path
239
362
  });
240
- print({ status: 'APPROVER_ADDED', key_id: result.keyId, trust_root_version: result.version, trust_root: result.path });
241
363
  return 0;
242
364
  }
243
365
  if (sub === 'remove-approver') {
244
366
  allow(parsed, ['--root-key', '--trust-root', '--out', '--key-id', '--trust-root-expires'], 0);
245
367
  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'),
368
+ rootKeyPath: one(parsed, '--root-key'),
369
+ trustRootPath: one(parsed, '--trust-root'),
370
+ out: optional(parsed, '--out'),
371
+ now,
372
+ trustRootExpires: optional(parsed, '--trust-root-expires'),
373
+ keyId: validateKeyId(one(parsed, '--key-id'), '--key-id'),
374
+ });
375
+ print({
376
+ status: 'APPROVER_REMOVED',
377
+ trust_root_version: result.version,
378
+ trust_root: result.path
248
379
  });
249
- print({ status: 'APPROVER_REMOVED', trust_root_version: result.version, trust_root: result.path });
250
380
  return 0;
251
381
  }
252
382
  if (sub === 'show') {
@@ -281,15 +411,46 @@ async function runRevoke(sub, parsed, now) {
281
411
  ...(sub === 'key' ? { revokeKey: validateKeyId(one(parsed, '--key-id'), '--key-id'), reason: one(parsed, '--reason') } : {}),
282
412
  ...(sub === 'digest' ? { revokeDigest: one(parsed, '--digest'), reason: one(parsed, '--reason') } : {}),
283
413
  });
284
- print({ status: sub === 'refresh' ? 'REVOCATIONS_REFRESHED' : 'REVOKED', revocations_version: result.version, expires_at: formatTimestamp(result.expiresAt), revocations: result.path });
414
+ print({
415
+ status: sub === 'refresh' ? 'REVOCATIONS_REFRESHED' : 'REVOKED',
416
+ revocations_version: result.version,
417
+ expires_at: formatTimestamp(result.expiresAt),
418
+ revocations: result.path
419
+ });
285
420
  return 0;
286
421
  }
422
+ /** Loads the policy named by --policy, else the host default. The checkout being verified never chooses its own root. */
423
+ async function loadCliPolicy(parsed) {
424
+ const explicit = optional(parsed, '--policy');
425
+ let policyPath;
426
+ try {
427
+ policyPath = explicit ?? defaultPolicyPath();
428
+ }
429
+ catch (error) {
430
+ throw new UsageError(error.message);
431
+ }
432
+ try {
433
+ return await loadPolicy(policyPath);
434
+ }
435
+ catch (error) {
436
+ const missing = error;
437
+ if (!explicit && missing?.code === 'ENOENT') {
438
+ throw new UsageError(`No policy at ${policyPath}. Pass --policy FILE, or set MAGO_SKI_POLICY to an absolute path`);
439
+ }
440
+ // Only when the policy file itself is missing; a missing trust root or other input keeps its own error.
441
+ if (missing?.code === 'ENOENT' && missing.path === path.resolve(policyPath)) {
442
+ throw new UsageError(`Policy file not found: ${path.resolve(policyPath)}`);
443
+ }
444
+ throw error;
445
+ }
446
+ }
287
447
  async function runVerify(parsed, now) {
288
448
  allow(parsed, ['--policy', '--name', '--certificate'], 1);
289
- const policy = await loadPolicy(optional(parsed, '--policy') ?? DEFAULT_POLICY_PATH);
449
+ const policy = await loadCliPolicy(parsed);
290
450
  const skillDir = parsed.positional[0];
291
451
  const result = await verifyWithPolicy(policy, skillDir, {
292
- now, ...(optional(parsed, '--name') ? { skillName: one(parsed, '--name') } : {}),
452
+ now,
453
+ ...(optional(parsed, '--name') ? { skillName: one(parsed, '--name') } : {}),
293
454
  ...(optional(parsed, '--certificate') ? { certificate: one(parsed, '--certificate') } : {}),
294
455
  });
295
456
  await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'cli-verify'));
@@ -298,7 +459,7 @@ async function runVerify(parsed, now) {
298
459
  }
299
460
  async function runVerifyAll(parsed, now) {
300
461
  allow(parsed, ['--policy'], 0);
301
- const policy = await loadPolicy(optional(parsed, '--policy') ?? DEFAULT_POLICY_PATH);
462
+ const policy = await loadCliPolicy(parsed);
302
463
  if (policy.skillDirs.length === 0)
303
464
  throw new UsageError('Policy has no skill_dirs to scan');
304
465
  const { skillDirs, tooDeep } = await findSkillDirs(policy.skillDirs);
@@ -318,9 +479,8 @@ async function runVerifyAll(parsed, now) {
318
479
  await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'cli-verify-all'));
319
480
  printResult(result, parsed.booleans.has('--json'));
320
481
  }
321
- if (!parsed.booleans.has('--json')) {
482
+ if (!parsed.booleans.has('--json'))
322
483
  process.stdout.write(`${results.length - failures}/${results.length} Skills verified (mode: ${policy.mode})\n`);
323
- }
324
484
  return failures === 0 ? 0 : 1;
325
485
  }
326
486
  export async function runCli(argv = process.argv.slice(2), now = new Date()) {
@@ -359,16 +519,26 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
359
519
  case 'revoke':
360
520
  return await runRevoke(maybeSub, parsed, now);
361
521
  case 'approve': {
362
- allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out'], 1);
522
+ allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out', '--expect-digest'], 1);
363
523
  const result = await approveSkill({
364
- skillDir: parsed.positional[0], approverKeyPath: one(parsed, '--key'), now, expires: one(parsed, '--expires'),
524
+ skillDir: parsed.positional[0],
525
+ approverKeyPath: one(parsed, '--key'),
526
+ now,
527
+ expires: one(parsed, '--expires'),
365
528
  reason: one(parsed, '--reason'),
366
529
  ...(optional(parsed, '--name') ? { name: one(parsed, '--name') } : {}),
367
530
  ...(optional(parsed, '--previous') ? { previous: one(parsed, '--previous') } : {}),
368
531
  ...(optional(parsed, '--out') ? { out: one(parsed, '--out') } : {}),
532
+ ...(optional(parsed, '--expect-digest') ? { expectDigest: one(parsed, '--expect-digest') } : {}),
533
+ });
534
+ print({
535
+ status: 'CERTIFICATE_ISSUED',
536
+ skill: result.skillName,
537
+ digest: result.digest,
538
+ certificate_id: result.certificateId,
539
+ expires_at: formatTimestamp(result.expiresAt),
540
+ certificate: result.path
369
541
  });
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
542
  return 0;
373
543
  }
374
544
  case 'verify':
@@ -378,15 +548,15 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
378
548
  case 'digest': {
379
549
  allow(parsed, [], 1);
380
550
  const tree = await collectSkillTree(parsed.positional[0]);
381
- if (parsed.booleans.has('--explain')) {
551
+ if (parsed.booleans.has('--explain'))
382
552
  print({ profile: TREE_PROFILE, digest: tree.digest, root: tree.root, total_bytes: tree.totalBytes, files: tree.files, excluded: tree.excluded });
383
- }
384
- else {
553
+ else
385
554
  process.stdout.write(`${tree.digest}\n`);
386
- }
387
555
  return 0;
388
556
  }
389
557
  case 'diff': {
558
+ if (parsed.positional.length > 0)
559
+ throw new UsageError(`diff takes the two directories as options: mago-ski diff --base ${parsed.positional[0]} --candidate ${parsed.positional[1] ?? 'DIR'}`);
390
560
  allow(parsed, ['--base', '--candidate'], 0);
391
561
  const result = await diffSkillTrees(one(parsed, '--base'), one(parsed, '--candidate'));
392
562
  print(result);
@@ -396,9 +566,15 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
396
566
  allow(parsed, [], 1);
397
567
  const certificate = parseCertificate(await readRegularFile(parsed.positional[0], 'Certificate', 8 * 1024 * 1024));
398
568
  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,
569
+ certificate_id: certificate.id,
570
+ skill: certificate.skillName,
571
+ digest: certificate.digest,
572
+ approver_key_id: certificate.approverKeyId,
573
+ issued_at: formatTimestamp(certificate.issuedAt),
574
+ expires_at: formatTimestamp(certificate.expiresAt),
575
+ reason: certificate.reason,
576
+ previous_digest: certificate.previousDigest,
577
+ file_count: certificate.files.length,
402
578
  note: 'Structure only. Run mago-ski verify to check the signature against your trust root.',
403
579
  });
404
580
  return 0;
@@ -23,8 +23,4 @@ export interface DiffResult {
23
23
  diff_truncated: boolean;
24
24
  files: FileChange[];
25
25
  }
26
- /**
27
- * Compares two Skill directories. Any digest difference requires a new certificate,
28
- * whatever the capability evidence says: unchanged origins never waive a content change.
29
- */
30
26
  export declare function diffSkillTrees(baseRoot: string, candidateRoot: string): Promise<DiffResult>;