@mago-foundation/mago-ski 0.0.0-stage → 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.
Files changed (56) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +139 -2
  4. package/action.yml +58 -0
  5. package/dist/hosts/github/run.d.ts +27 -0
  6. package/dist/hosts/github/run.js +152 -0
  7. package/dist/hosts/pi/index.d.ts +13 -0
  8. package/dist/hosts/pi/index.js +550 -0
  9. package/dist/hosts/pi/paths.d.ts +9 -0
  10. package/dist/hosts/pi/paths.js +55 -0
  11. package/dist/src/admin.d.ts +74 -0
  12. package/dist/src/admin.js +243 -0
  13. package/dist/src/canonical-json.d.ts +12 -0
  14. package/dist/src/canonical-json.js +149 -0
  15. package/dist/src/certificate.d.ts +34 -0
  16. package/dist/src/certificate.js +112 -0
  17. package/dist/src/cli.d.ts +2 -0
  18. package/dist/src/cli.js +595 -0
  19. package/dist/src/diff.d.ts +26 -0
  20. package/dist/src/diff.js +404 -0
  21. package/dist/src/dsse.d.ts +25 -0
  22. package/dist/src/dsse.js +71 -0
  23. package/dist/src/experimental/sigstore.d.ts +26 -0
  24. package/dist/src/experimental/sigstore.js +153 -0
  25. package/dist/src/fs-safe.d.ts +27 -0
  26. package/dist/src/fs-safe.js +229 -0
  27. package/dist/src/index.d.ts +14 -0
  28. package/dist/src/index.js +14 -0
  29. package/dist/src/keys.d.ts +21 -0
  30. package/dist/src/keys.js +154 -0
  31. package/dist/src/main-module.d.ts +5 -0
  32. package/dist/src/main-module.js +19 -0
  33. package/dist/src/names.d.ts +7 -0
  34. package/dist/src/names.js +38 -0
  35. package/dist/src/policy.d.ts +81 -0
  36. package/dist/src/policy.js +349 -0
  37. package/dist/src/revocations.d.ts +28 -0
  38. package/dist/src/revocations.js +93 -0
  39. package/dist/src/time.d.ts +25 -0
  40. package/dist/src/time.js +74 -0
  41. package/dist/src/tree-digest.d.ts +46 -0
  42. package/dist/src/tree-digest.js +268 -0
  43. package/dist/src/trust-root.d.ts +38 -0
  44. package/dist/src/trust-root.js +136 -0
  45. package/dist/src/verify.d.ts +96 -0
  46. package/dist/src/verify.js +380 -0
  47. package/docs/hosts/adapter-interface.md +33 -0
  48. package/docs/hosts/github-action.md +45 -0
  49. package/docs/hosts/pi.md +41 -0
  50. package/docs/spec/root-recovery-v1.md +430 -0
  51. package/docs/spec/skill-certificate-v1.md +60 -0
  52. package/docs/spec/skill-tree-v2.md +59 -0
  53. package/docs/spec/trust-documents-v1.md +103 -0
  54. package/docs/spec/verification.md +56 -0
  55. package/docs/threat-model.md +45 -0
  56. package/package.json +77 -4
@@ -0,0 +1,595 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { addApprover, approveSkill, initRoot, removeApprover, updateRevocations } from "./admin.js";
6
+ import { parseCertificate } from "./certificate.js";
7
+ import { diffSkillTrees } from "./diff.js";
8
+ import { readRegularFile } from "./fs-safe.js";
9
+ import { generateKeyPair, validateKeyId } from "./keys.js";
10
+ import { appendDecision, decisionRecord, defaultPolicyPath, findSkillDirs, loadPolicy, loadPolicyTrust, tooDeepResult, verifyWithPolicy, } from "./policy.js";
11
+ import { isMainModule } from "./main-module.js";
12
+ import { formatTimestamp } from "./time.js";
13
+ import { collectSkillTree, TREE_PROFILE } from "./tree-digest.js";
14
+ import { verifyTrustRoot } from "./trust-root.js";
15
+ import { unverifiable } from "./verify.js";
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.`;
61
+ const DURATION_NOTE = 'Durations are a number plus d, h or m, for example 90d, 12h or 30m.';
62
+ /* ****************************************************************************************** */
63
+ /** Per-command help: `mago-ski <command> --help`. Keys are "command" or "command subcommand". */
64
+ /* ****************************************************************************************** */
65
+ const COMMAND_HELP = {
66
+ keygen: `Usage: mago-ski keygen --private-key FILE --public-key FILE
67
+
68
+ Creates an Ed25519 key pair for a root key or an approver key.
69
+
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
72
+
73
+ Keep private keys secret and outside every Skill directory; keygen refuses to write inside one.
74
+ Prints the key id (sha256:...), which identifies the key in trust roots and revocations.`,
75
+ /* ****************************************************************************************** */
76
+ /** Per-command: root */
77
+ /* ****************************************************************************************** */
78
+ root: `Usage: mago-ski root <init | add-approver | remove-approver | show> [options]
79
+
80
+ Manages the organization's signed trust root (who may approve which Skills).
81
+ Run "mago-ski root <subcommand> --help" for details.`,
82
+ /* *************************************** */
83
+ /* Per-command "root" -> "root init" */
84
+ /* *************************************** */
85
+ 'root init': `Usage: mago-ski root init --root-key FILE --trust-root OUT --revocations OUT [options]
86
+
87
+ Creates version 1 of the signed trust root (no approvers yet) and an empty signed revocation list.
88
+
89
+ --root-key FILE the root private key (keep it offline)
90
+ --trust-root OUT where to write trust-root.json (must not exist yet)
91
+ --revocations OUT where to write revocations.json (must not exist yet)
92
+ --trust-root-expires DUR trust root lifetime (default 365d)
93
+ --revocations-expires DUR revocation list lifetime (default 30d; republish before it expires)
94
+
95
+ Prints root_fingerprint: put it in every host policy as "root_fingerprint".
96
+ ${DURATION_NOTE}`,
97
+ /* ******************************************** */
98
+ /* Per-command "root" -> "root add-approver */
99
+ /* ******************************************** */
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]
101
+
102
+ Adds (or replaces) an approver and re-signs the trust root with the next version.
103
+
104
+ --root-key FILE the root private key
105
+ --trust-root FILE the current trust root (updated in place unless --out is given)
106
+ --public-key FILE the approver's public key
107
+ --name LABEL a readable name, shown in verdicts
108
+ --scope PATTERN Skill names this approver may approve; repeat for several.
109
+ "*" = every Skill, "docs-*" = names starting with docs-, otherwise an exact name
110
+ --expires DUR how long the approver key stays valid
111
+ --out FILE write the new trust root here instead
112
+ --trust-root-expires DUR also set a new trust root lifetime
113
+ ${DURATION_NOTE}`,
114
+ /* ************************************************* */
115
+ /* Per-command "root" -> "root remove-approver" */
116
+ /* *********************************************** */
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]
118
+
119
+ Removes an approver and re-signs the trust root. Certificates from that approver stop verifying once hosts read
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
+ /* ************************************** */
124
+ 'root show': `Usage: mago-ski root show --trust-root FILE --root-fingerprint ID
125
+
126
+ Verifies a trust root against the pinned root fingerprint and prints its version, expiry and approvers.`,
127
+ /* ****************************************************************************************** */
128
+ /** Per-command: revoke */
129
+ /* ****************************************************************************************** */
130
+ revoke: `Usage: mago-ski revoke <key | digest | refresh> [options]
131
+
132
+ Updates the organization's signed revocation list. Run "mago-ski revoke <subcommand> --help" for details.`,
133
+ /* *************************************** */
134
+ /* Per-command "revoke" -> "revoke key" */
135
+ /* *************************************** */
136
+ 'revoke key': `Usage: mago-ski revoke key --root-key FILE --revocations FILE --key-id ID --reason TEXT [--expires DUR] [--out FILE]
137
+
138
+ Revokes an approver key: every certificate it signed stops verifying once hosts read the new list.
139
+
140
+ --key-id ID the approver's key id (sha256:...)
141
+ --reason TEXT shown in verdicts
142
+ --expires DUR lifetime of the new list (default 30d)
143
+ ${DURATION_NOTE}`,
144
+ /* ****************************************** */
145
+ /* Per-command "revoke" -> "revoke digest" */
146
+ /* ****************************************** */
147
+ 'revoke digest': `Usage: mago-ski revoke digest --root-key FILE --revocations FILE --digest sha256:... --reason TEXT [--expires DUR] [--out FILE]
148
+
149
+ Revokes one approved Skill version (its tree digest), whoever signed it.
150
+ ${DURATION_NOTE}`,
151
+ /* ******************************************* */
152
+ /* Per-command "revoke" -> "revoke refresh" */
153
+ /* ******************************************* */
154
+ 'revoke refresh': `Usage: mago-ski revoke refresh --root-key FILE --revocations FILE [--expires DUR] [--out FILE]
155
+
156
+ Re-signs the revocation list with the next version and a new expiry, without changing its entries.
157
+ Hosts refuse an expired list, so refresh it before it expires (default lifetime 30d).`,
158
+ /* ****************************************************************************************** */
159
+ /** Per-command: approve */
160
+ /* ****************************************************************************************** */
161
+ approve: `Usage: mago-ski approve SKILL_DIR --key FILE --expires DUR --reason TEXT [options]
162
+
163
+ Issues a certificate for the exact current bytes of a Skill, signed with your approver key.
164
+
165
+ --key FILE your approver private key (must be outside the Skill directory)
166
+ --expires DUR how long the approval is valid
167
+ --reason TEXT what you reviewed; stored in the certificate
168
+ --name NAME Skill name (default: "name" in SKILL.md, else the directory name)
169
+ --previous CERT|DIG the previously approved certificate or digest, for the update history
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
172
+
173
+ Refuses a Skill that contains a private key. A certificate records who approved which exact version;
174
+ it does not certify that the Skill is safe.
175
+ ${DURATION_NOTE}`,
176
+ /* ****************************************************************************************** */
177
+ /** Per-command: verify */
178
+ /* ****************************************************************************************** */
179
+ verify: `Usage: mago-ski verify SKILL_DIR [--policy FILE] [--name NAME] [--certificate FILE] [--json]
180
+
181
+ Checks one Skill against the policy's trust root and revocation list, and prints its verdict.
182
+
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)
185
+ --name NAME Skill name to check (default: "name" in SKILL.md, else the directory name)
186
+ --certificate FILE also try this certificate
187
+ --json print the result as JSON
188
+
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
+ /* ******************************************* */
193
+ 'verify-all': `Usage: mago-ski verify-all [--policy FILE] [--json]
194
+
195
+ Checks every Skill found under the policy's skill_dirs and prints one line per Skill and a summary.
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
+ /* ****************************************************************************************** */
200
+ digest: `Usage: mago-ski digest SKILL_DIR [--explain]
201
+
202
+ Prints the Skill's tree digest (sha256:...). --explain also lists every covered file, its hash and
203
+ executable bit, and the paths excluded from the digest.`,
204
+ /* ****************************************************************************************** */
205
+ /** Per-command: diff */
206
+ /* ****************************************************************************************** */
207
+ diff: `Usage: mago-ski diff --base DIR --candidate DIR
208
+
209
+ Compares two versions of a Skill: changed files and Markdown sections, executable-bit changes, and added
210
+ or removed network origins. Exits 1 when the digest changed, since that always needs a new certificate.`,
211
+ /* ****************************************************************************************** */
212
+ /** Per-command: inspect */
213
+ /* ****************************************************************************************** */
214
+ inspect: `Usage: mago-ski inspect CERTIFICATE
215
+
216
+ Prints a certificate's Skill, digest, approver, dates and reason. Checks structure only; use
217
+ "mago-ski verify" to check its signature against your trust root.`,
218
+ };
219
+ /* ****************************************************************************************** */
220
+ /* Utility functions for the CLI. */
221
+ const require = createRequire(import.meta.url);
222
+ function readVersion() {
223
+ try {
224
+ const pkg = require('#package.json');
225
+ return pkg.version ?? 'unknown';
226
+ }
227
+ catch {
228
+ return 'unknown';
229
+ }
230
+ }
231
+ /* Usage error thrown for when users misuse the CLI. */
232
+ class UsageError extends Error {
233
+ }
234
+ /* The actual boolean flags that should take no value. */
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. */
243
+ function parseArgs(args) {
244
+ const parsed = {
245
+ positional: [],
246
+ flags: new Map(),
247
+ booleans: new Set()
248
+ };
249
+ for (let index = 0; index < args.length; index++) {
250
+ const arg = args[index];
251
+ /* 1. If it's a boolean flag, add it to the set of booleans. */
252
+ if (BOOLEAN_FLAGS.has(arg))
253
+ parsed.booleans.add(arg);
254
+ /* 2. If it starts with --, it's a flag with a value. */
255
+ else if (arg.startsWith('--')) {
256
+ const value = args[index + 1];
257
+ /* 3. If the value is missing or starts with --, throw an error. */
258
+ if (value === undefined || value.startsWith('--') || value === '')
259
+ throw new UsageError(`Missing value for ${arg}`);
260
+ addFlag(parsed.flags, arg, value);
261
+ index += 1;
262
+ }
263
+ else
264
+ parsed.positional.push(arg);
265
+ }
266
+ return parsed;
267
+ }
268
+ /* Validation function */
269
+ function allow(parsed, allowed = [], positional = 0, repeatable = []) {
270
+ /* Check flags for validity and repeatability. */
271
+ for (const [flag, values] of parsed.flags) {
272
+ if (!allowed.includes(flag))
273
+ throw new UsageError(`Unsupported option ${flag}`);
274
+ if (values.length > 1 && !repeatable.includes(flag))
275
+ throw new UsageError(`${flag} may be given only once`);
276
+ }
277
+ /* Check boolean flags for validity. */
278
+ for (const flag of parsed.booleans)
279
+ if (!BOOLEAN_FLAGS.has(flag) && !allowed.includes(flag))
280
+ throw new UsageError(`Unsupported option ${flag}`);
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}`);
297
+ }
298
+ /* First value of a flag, or throw if missing. */
299
+ function one(parsed, flag) {
300
+ const value = parsed.flags.get(flag)?.[0];
301
+ if (!value)
302
+ throw new UsageError(`${flag} is required`);
303
+ return value;
304
+ }
305
+ /* ****************************************************************************************** */
306
+ /* Optional first value of a flag, or undefined if missing. */
307
+ function optional(parsed, flag) {
308
+ return parsed.flags.get(flag)?.[0];
309
+ }
310
+ /* Prints a value as JSON to stdout. */
311
+ function print(value) {
312
+ process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
313
+ }
314
+ function printResult(result, json) {
315
+ if (json) {
316
+ const { files: _files, ...rest } = result;
317
+ process.stdout.write(`${JSON.stringify(rest)}\n`);
318
+ return;
319
+ }
320
+ const mark = result.verdict === 'VERIFIED' ? 'ok' : 'FAIL';
321
+ process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${result.skillName} ${result.reason}\n`);
322
+ }
323
+ /* ****************************************************************************************** */
324
+ async function runRoot(sub, parsed, now) {
325
+ if (sub === 'init') {
326
+ allow(parsed, ['--root-key', '--trust-root', '--revocations', '--trust-root-expires', '--revocations-expires'], 0);
327
+ const result = await initRoot({
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.'
341
+ });
342
+ return 0;
343
+ }
344
+ if (sub === 'add-approver') {
345
+ allow(parsed, ['--root-key', '--trust-root', '--out', '--public-key', '--name', '--scope', '--expires', '--trust-root-expires'], 0, ['--scope']);
346
+ const result = await addApprover({
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
362
+ });
363
+ return 0;
364
+ }
365
+ if (sub === 'remove-approver') {
366
+ allow(parsed, ['--root-key', '--trust-root', '--out', '--key-id', '--trust-root-expires'], 0);
367
+ const result = await removeApprover({
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
379
+ });
380
+ return 0;
381
+ }
382
+ if (sub === 'show') {
383
+ allow(parsed, ['--trust-root', '--root-fingerprint'], 0);
384
+ const trustRoot = verifyTrustRoot(await readRegularFile(one(parsed, '--trust-root'), 'Trust root', 4 * 1024 * 1024), validateKeyId(one(parsed, '--root-fingerprint'), '--root-fingerprint'), now);
385
+ print({
386
+ version: trustRoot.version, issued_at: formatTimestamp(trustRoot.issuedAt), expires_at: formatTimestamp(trustRoot.expiresAt),
387
+ root_fingerprint: trustRoot.root.keyId,
388
+ approvers: trustRoot.approvers.map((entry) => ({ name: entry.name, key_id: entry.keyId, scopes: entry.scopes, expires_at: formatTimestamp(entry.expiresAt) })),
389
+ });
390
+ return 0;
391
+ }
392
+ throw new UsageError('Unknown root command; use init, add-approver, remove-approver or show');
393
+ }
394
+ async function runRevoke(sub, parsed, now) {
395
+ const common = ['--root-key', '--revocations', '--out', '--expires'];
396
+ const base = { rootKeyPath: '', revocationsPath: '', now };
397
+ if (sub !== 'key' && sub !== 'digest' && sub !== 'refresh')
398
+ throw new UsageError('Unknown revoke command; use key, digest or refresh');
399
+ if (sub === 'key')
400
+ allow(parsed, [...common, '--key-id', '--reason'], 0);
401
+ if (sub === 'digest')
402
+ allow(parsed, [...common, '--digest', '--reason'], 0);
403
+ if (sub === 'refresh')
404
+ allow(parsed, common, 0);
405
+ const result = await updateRevocations({
406
+ ...base,
407
+ rootKeyPath: one(parsed, '--root-key'),
408
+ revocationsPath: one(parsed, '--revocations'),
409
+ ...(optional(parsed, '--out') ? { out: one(parsed, '--out') } : {}),
410
+ ...(optional(parsed, '--expires') ? { expires: one(parsed, '--expires') } : {}),
411
+ ...(sub === 'key' ? { revokeKey: validateKeyId(one(parsed, '--key-id'), '--key-id'), reason: one(parsed, '--reason') } : {}),
412
+ ...(sub === 'digest' ? { revokeDigest: one(parsed, '--digest'), reason: one(parsed, '--reason') } : {}),
413
+ });
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
+ });
420
+ return 0;
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
+ }
447
+ async function runVerify(parsed, now) {
448
+ allow(parsed, ['--policy', '--name', '--certificate'], 1);
449
+ const policy = await loadCliPolicy(parsed);
450
+ const skillDir = parsed.positional[0];
451
+ const result = await verifyWithPolicy(policy, skillDir, {
452
+ now,
453
+ ...(optional(parsed, '--name') ? { skillName: one(parsed, '--name') } : {}),
454
+ ...(optional(parsed, '--certificate') ? { certificate: one(parsed, '--certificate') } : {}),
455
+ });
456
+ await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'cli-verify'));
457
+ printResult(result, parsed.booleans.has('--json'));
458
+ return result.verdict === 'VERIFIED' ? 0 : 1;
459
+ }
460
+ async function runVerifyAll(parsed, now) {
461
+ allow(parsed, ['--policy'], 0);
462
+ const policy = await loadCliPolicy(parsed);
463
+ if (policy.skillDirs.length === 0)
464
+ throw new UsageError('Policy has no skill_dirs to scan');
465
+ const { skillDirs, tooDeep } = await findSkillDirs(policy.skillDirs);
466
+ const trust = await loadPolicyTrust(policy, now);
467
+ let failures = 0;
468
+ const results = [];
469
+ for (const skillDir of skillDirs) {
470
+ results.push(trust.ok
471
+ ? await verifyWithPolicy(policy, skillDir, { now, context: trust.context })
472
+ : unverifiable(skillDir, path.basename(skillDir), trust.reason, now, trust.verdict));
473
+ }
474
+ for (const directory of tooDeep)
475
+ results.push(tooDeepResult(directory, now));
476
+ for (const result of results) {
477
+ if (result.verdict !== 'VERIFIED')
478
+ failures += 1;
479
+ await appendDecision(policy.decisionLogPath, decisionRecord(result, policy.mode, 'cli-verify-all'));
480
+ printResult(result, parsed.booleans.has('--json'));
481
+ }
482
+ if (!parsed.booleans.has('--json'))
483
+ process.stdout.write(`${results.length - failures}/${results.length} Skills verified (mode: ${policy.mode})\n`);
484
+ return failures === 0 ? 0 : 1;
485
+ }
486
+ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
487
+ if (argv[0] === '--version' || argv[0] === '-V' || argv[0] === 'version') {
488
+ process.stdout.write(`mago-ski ${readVersion()}\n`);
489
+ return 0;
490
+ }
491
+ // "mago-ski help verify" is the same as "mago-ski verify --help".
492
+ if (argv[0] === 'help' && argv.length > 1)
493
+ argv = [...argv.slice(1), '--help'];
494
+ if (argv.length === 0 || argv[0] === '--help' || argv[0] === '-h' || argv[0] === 'help') {
495
+ process.stdout.write(`${usage}\n`);
496
+ return 0;
497
+ }
498
+ const [command, maybeSub] = argv;
499
+ if (argv.slice(1).some((arg) => arg === '--help' || arg === '-h')) {
500
+ const sub = maybeSub && !maybeSub.startsWith('-') ? `${command} ${maybeSub}` : undefined;
501
+ const text = (sub && COMMAND_HELP[sub]) ?? COMMAND_HELP[command];
502
+ if (!text)
503
+ throw new UsageError(`Unknown command: ${command}`);
504
+ process.stdout.write(`${text}\n`);
505
+ return 0;
506
+ }
507
+ const hasSub = command === 'root' || command === 'revoke';
508
+ const parsed = parseArgs(argv.slice(hasSub ? 2 : 1));
509
+ switch (command) {
510
+ case 'keygen': {
511
+ allow(parsed, ['--private-key', '--public-key'], 0);
512
+ const pair = await generateKeyPair(one(parsed, '--private-key'), one(parsed, '--public-key'));
513
+ print({ status: 'KEY_CREATED', key_id: pair.keyId, private_key: pair.privatePath, public_key: pair.publicPath });
514
+ process.stderr.write('Keep the private key secret and outside any Skill directory.\n');
515
+ return 0;
516
+ }
517
+ case 'root':
518
+ return await runRoot(maybeSub, parsed, now);
519
+ case 'revoke':
520
+ return await runRevoke(maybeSub, parsed, now);
521
+ case 'approve': {
522
+ allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out', '--expect-digest'], 1);
523
+ const result = await approveSkill({
524
+ skillDir: parsed.positional[0],
525
+ approverKeyPath: one(parsed, '--key'),
526
+ now,
527
+ expires: one(parsed, '--expires'),
528
+ reason: one(parsed, '--reason'),
529
+ ...(optional(parsed, '--name') ? { name: one(parsed, '--name') } : {}),
530
+ ...(optional(parsed, '--previous') ? { previous: one(parsed, '--previous') } : {}),
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
541
+ });
542
+ return 0;
543
+ }
544
+ case 'verify':
545
+ return await runVerify(parsed, now);
546
+ case 'verify-all':
547
+ return await runVerifyAll(parsed, now);
548
+ case 'digest': {
549
+ allow(parsed, [], 1);
550
+ const tree = await collectSkillTree(parsed.positional[0]);
551
+ if (parsed.booleans.has('--explain'))
552
+ print({ profile: TREE_PROFILE, digest: tree.digest, root: tree.root, total_bytes: tree.totalBytes, files: tree.files, excluded: tree.excluded });
553
+ else
554
+ process.stdout.write(`${tree.digest}\n`);
555
+ return 0;
556
+ }
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'}`);
560
+ allow(parsed, ['--base', '--candidate'], 0);
561
+ const result = await diffSkillTrees(one(parsed, '--base'), one(parsed, '--candidate'));
562
+ print(result);
563
+ return result.recertification_required ? 1 : 0;
564
+ }
565
+ case 'inspect': {
566
+ allow(parsed, [], 1);
567
+ const certificate = parseCertificate(await readRegularFile(parsed.positional[0], 'Certificate', 8 * 1024 * 1024));
568
+ print({
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,
578
+ note: 'Structure only. Run mago-ski verify to check the signature against your trust root.',
579
+ });
580
+ return 0;
581
+ }
582
+ default:
583
+ throw new UsageError(`Unknown command: ${command}`);
584
+ }
585
+ }
586
+ if (isMainModule(import.meta.url)) {
587
+ runCli().then((code) => {
588
+ process.exitCode = code;
589
+ }, (error) => {
590
+ process.stderr.write(`mago-ski: ${error?.message ?? 'operation failed'}\n`);
591
+ if (error instanceof UsageError)
592
+ process.stderr.write('Run "mago-ski --help" for usage.\n');
593
+ process.exitCode = 2;
594
+ });
595
+ }
@@ -0,0 +1,26 @@
1
+ export interface FileChange {
2
+ path: string;
3
+ change: 'added' | 'deleted' | 'modified' | 'mode-changed';
4
+ before_bytes: number;
5
+ after_bytes: number;
6
+ exec_before: boolean | null;
7
+ exec_after: boolean | null;
8
+ changed_sections: string[];
9
+ sections_truncated: boolean;
10
+ }
11
+ export interface DiffResult {
12
+ result: 'UNCHANGED' | 'CAPABILITY_CHANGED' | 'CONTENT_CHANGED';
13
+ recertification_required: boolean;
14
+ base_digest: string;
15
+ candidate_digest: string;
16
+ capability_evidence: {
17
+ profile: 'mago.network-origin-scan/v1';
18
+ analysis_complete: boolean;
19
+ added_network_origins: string[];
20
+ removed_network_origins: string[];
21
+ note: string;
22
+ };
23
+ diff_truncated: boolean;
24
+ files: FileChange[];
25
+ }
26
+ export declare function diffSkillTrees(baseRoot: string, candidateRoot: string): Promise<DiffResult>;