@mago-foundation/mago-ski 0.2.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 (74) hide show
  1. package/README.md +30 -3
  2. package/dist/hosts/github/run.d.ts +3 -1
  3. package/dist/hosts/github/run.js +29 -9
  4. package/dist/hosts/pi/index.js +48 -5
  5. package/dist/src/admin.d.ts +136 -1
  6. package/dist/src/admin.js +221 -84
  7. package/dist/src/cli.js +335 -10
  8. package/dist/src/fs-safe.d.ts +15 -2
  9. package/dist/src/fs-safe.js +32 -3
  10. package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
  11. package/dist/src/gate/adapters/claude-code-hook.js +4 -0
  12. package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
  13. package/dist/src/gate/adapters/claude-code-settings.js +49 -0
  14. package/dist/src/gate/adapters/claude-code.d.ts +33 -0
  15. package/dist/src/gate/adapters/claude-code.js +193 -0
  16. package/dist/src/gate/adapters/client.d.ts +13 -0
  17. package/dist/src/gate/adapters/client.js +57 -0
  18. package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
  19. package/dist/src/gate/adapters/codex-hook.js +5 -0
  20. package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
  21. package/dist/src/gate/adapters/codex-requirements.js +56 -0
  22. package/dist/src/gate/adapters/codex.d.ts +16 -0
  23. package/dist/src/gate/adapters/codex.js +574 -0
  24. package/dist/src/gate/adapters/hook-main.d.ts +7 -0
  25. package/dist/src/gate/adapters/hook-main.js +35 -0
  26. package/dist/src/gate/adapters/host-pid.d.ts +1 -0
  27. package/dist/src/gate/adapters/host-pid.js +20 -0
  28. package/dist/src/gate/admission.d.ts +54 -0
  29. package/dist/src/gate/admission.js +490 -0
  30. package/dist/src/gate/contract.d.ts +51 -0
  31. package/dist/src/gate/contract.js +94 -0
  32. package/dist/src/gate/decision-log.d.ts +38 -0
  33. package/dist/src/gate/decision-log.js +251 -0
  34. package/dist/src/gate/generations.d.ts +67 -0
  35. package/dist/src/gate/generations.js +518 -0
  36. package/dist/src/gate/proc.d.ts +31 -0
  37. package/dist/src/gate/proc.js +79 -0
  38. package/dist/src/gate/refresh.d.ts +11 -0
  39. package/dist/src/gate/refresh.js +30 -0
  40. package/dist/src/gate/run-verifier.d.ts +23 -0
  41. package/dist/src/gate/run-verifier.js +89 -0
  42. package/dist/src/gate/service.d.ts +80 -0
  43. package/dist/src/gate/service.js +722 -0
  44. package/dist/src/gate/strict-json.d.ts +11 -0
  45. package/dist/src/gate/strict-json.js +190 -0
  46. package/dist/src/gate/trust-store.d.ts +36 -0
  47. package/dist/src/gate/trust-store.js +251 -0
  48. package/dist/src/gate/verifier-worker.d.ts +8 -0
  49. package/dist/src/gate/verifier-worker.js +66 -0
  50. package/dist/src/index.d.ts +2 -0
  51. package/dist/src/index.js +2 -0
  52. package/dist/src/keys.d.ts +4 -0
  53. package/dist/src/keys.js +23 -14
  54. package/dist/src/policy.d.ts +145 -0
  55. package/dist/src/policy.js +554 -35
  56. package/dist/src/recovery-admin.d.ts +173 -0
  57. package/dist/src/recovery-admin.js +400 -0
  58. package/dist/src/root-events.d.ts +107 -0
  59. package/dist/src/root-events.js +376 -0
  60. package/dist/src/timestamp.d.ts +61 -0
  61. package/dist/src/timestamp.js +107 -0
  62. package/dist/src/tree-digest.d.ts +1 -0
  63. package/dist/src/tree-digest.js +1 -1
  64. package/dist/src/verify.d.ts +33 -0
  65. package/dist/src/verify.js +4 -2
  66. package/docs/hosts/adapter-interface.md +8 -2
  67. package/docs/hosts/github-action.md +1 -1
  68. package/docs/hosts/pi.md +2 -0
  69. package/docs/spec/gui-admin-rack-v1.md +289 -0
  70. package/docs/spec/root-recovery-v1.md +33 -12
  71. package/docs/spec/trust-documents-v1.md +8 -2
  72. package/docs/spec/verification.md +9 -2
  73. package/docs/threat-model.md +4 -2
  74. package/package.json +3 -1
package/dist/src/cli.js CHANGED
@@ -2,17 +2,18 @@
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, defaultPolicyPath, 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
+ import { resolveSkillName, unverifiable } from "./verify.js";
16
17
  import { createRequire } from 'node:module';
17
18
  const usage = `mago-ski — organization-approved Skill certificates,
18
19
  enforced on the agent host
@@ -25,11 +26,19 @@ KEYS AND TRUST (root key holder)
25
26
  root init Create the trust root and revocation list
26
27
  root add-approver Add or replace an approver
27
28
  root remove-approver Remove an approver
29
+ root renew Extend the trust root's lifetime
28
30
  root show Verify and print a trust root
31
+ root adopt Re-sign trust documents with a new root key
29
32
  revoke key Revoke an approver key
30
33
  revoke digest Revoke one approved Skill version
31
34
  revoke refresh Re-sign the revocation list
32
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
+
33
42
  APPROVING SKILLS (reviewer)
34
43
  approve SKILL_DIR Issue a certificate for a Skill
35
44
 
@@ -39,6 +48,7 @@ CHECKING SKILLS
39
48
  digest SKILL_DIR Print a Skill's tree digest
40
49
  diff Compare two versions of a Skill
41
50
  inspect CERTIFICATE Print a certificate's contents
51
+ policy check Check a policy the way a host does
42
52
 
43
53
  POLICY
44
54
  --policy FILE, else $MAGO_SKI_POLICY, else
@@ -75,7 +85,7 @@ Prints the key id (sha256:...), which identifies the key in trust roots and revo
75
85
  /* ****************************************************************************************** */
76
86
  /** Per-command: root */
77
87
  /* ****************************************************************************************** */
78
- root: `Usage: mago-ski root <init | add-approver | remove-approver | show> [options]
88
+ root: `Usage: mago-ski root <init | add-approver | remove-approver | renew | show> [options]
79
89
 
80
90
  Manages the organization's signed trust root (who may approve which Skills).
81
91
  Run "mago-ski root <subcommand> --help" for details.`,
@@ -110,6 +120,7 @@ Adds (or replaces) an approver and re-signs the trust root with the next version
110
120
  --expires DUR how long the approver key stays valid
111
121
  --out FILE write the new trust root here instead
112
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)
113
124
  ${DURATION_NOTE}`,
114
125
  /* ************************************************* */
115
126
  /* Per-command "root" -> "root remove-approver" */
@@ -118,6 +129,10 @@ ${DURATION_NOTE}`,
118
129
 
119
130
  Removes an approver and re-signs the trust root. Certificates from that approver stop verifying once hosts read
120
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.`,
121
136
  /* ************************************** */
122
137
  /* Per-command "root" -> "root show" */
123
138
  /* ************************************** */
@@ -215,6 +230,105 @@ or removed network origins. Exits 1 when the digest changed, since that always n
215
230
 
216
231
  Prints a certificate's Skill, digest, approver, dates and reason. Checks structure only; use
217
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.`,
218
332
  };
219
333
  /* ****************************************************************************************** */
220
334
  /* Utility functions for the CLI. */
@@ -342,7 +456,9 @@ async function runRoot(sub, parsed, now) {
342
456
  return 0;
343
457
  }
344
458
  if (sub === 'add-approver') {
345
- 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);
346
462
  const result = await addApprover({
347
463
  rootKeyPath: one(parsed, '--root-key'),
348
464
  trustRootPath: one(parsed, '--trust-root'),
@@ -353,6 +469,7 @@ async function runRoot(sub, parsed, now) {
353
469
  name: one(parsed, '--name'),
354
470
  scopes: parsed.flags.get('--scope') ?? [],
355
471
  expires: one(parsed, '--expires'),
472
+ ...(forbidden ? { forbidden } : {}),
356
473
  });
357
474
  print({
358
475
  status: 'APPROVER_ADDED',
@@ -379,6 +496,23 @@ async function runRoot(sub, parsed, now) {
379
496
  });
380
497
  return 0;
381
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),
513
+ });
514
+ return 0;
515
+ }
382
516
  if (sub === 'show') {
383
517
  allow(parsed, ['--trust-root', '--root-fingerprint'], 0);
384
518
  const trustRoot = verifyTrustRoot(await readRegularFile(one(parsed, '--trust-root'), 'Trust root', 4 * 1024 * 1024), validateKeyId(one(parsed, '--root-fingerprint'), '--root-fingerprint'), now);
@@ -389,7 +523,28 @@ async function runRoot(sub, parsed, now) {
389
523
  });
390
524
  return 0;
391
525
  }
392
- 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');
393
548
  }
394
549
  async function runRevoke(sub, parsed, now) {
395
550
  const common = ['--root-key', '--revocations', '--out', '--expires'];
@@ -444,12 +599,166 @@ async function loadCliPolicy(parsed) {
444
599
  throw error;
445
600
  }
446
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
+ });
704
+ return 0;
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
+ }
447
747
  async function runVerify(parsed, now) {
448
748
  allow(parsed, ['--policy', '--name', '--certificate'], 1);
449
749
  const policy = await loadCliPolicy(parsed);
450
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
+ }
451
759
  const result = await verifyWithPolicy(policy, skillDir, {
452
760
  now,
761
+ context: trust.context,
453
762
  ...(optional(parsed, '--name') ? { skillName: one(parsed, '--name') } : {}),
454
763
  ...(optional(parsed, '--certificate') ? { certificate: one(parsed, '--certificate') } : {}),
455
764
  });
@@ -464,12 +773,20 @@ async function runVerifyAll(parsed, now) {
464
773
  throw new UsageError('Policy has no skill_dirs to scan');
465
774
  const { skillDirs, tooDeep } = await findSkillDirs(policy.skillDirs);
466
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
+ }
467
786
  let failures = 0;
468
787
  const results = [];
469
788
  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));
789
+ results.push(await verifyWithPolicy(policy, skillDir, { now, context: trust.context }));
473
790
  }
474
791
  for (const directory of tooDeep)
475
792
  results.push(tooDeepResult(directory, now));
@@ -504,7 +821,7 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
504
821
  process.stdout.write(`${text}\n`);
505
822
  return 0;
506
823
  }
507
- const hasSub = command === 'root' || command === 'revoke';
824
+ const hasSub = ['root', 'revoke', 'recovery', 'root-events', 'timestamp', 'policy'].includes(command);
508
825
  const parsed = parseArgs(argv.slice(hasSub ? 2 : 1));
509
826
  switch (command) {
510
827
  case 'keygen': {
@@ -518,6 +835,14 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
518
835
  return await runRoot(maybeSub, parsed, now);
519
836
  case 'revoke':
520
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);
521
846
  case 'approve': {
522
847
  allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out', '--expect-digest'], 1);
523
848
  const result = await approveSkill({
@@ -10,8 +10,21 @@ export declare function resolveOutside(filePath: string, root: string, label: st
10
10
  }): Promise<string>;
11
11
  /** Creates a new file; refuses to overwrite anything that already exists. */
12
12
  export declare function writeNewFile(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
13
- /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
14
- export declare function writeFileAtomic(filePath: string, bytes: Uint8Array, mode?: number): Promise<string>;
13
+ /** The file a write was meant to replace was no longer the one that was read (see `writeFileAtomic`'s `expectSha256`). */
14
+ export declare class FileChangedError extends Error {
15
+ constructor(message?: string);
16
+ }
17
+ /**
18
+ * Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one.
19
+ *
20
+ * `options.expectSha256`: `undefined` checks nothing. A `sha256:<hex>` string requires the existing path to be a regular
21
+ * file with that SHA-256, `null` requires the path not to exist. The check runs after the temporary file is written and
22
+ * immediately before the rename; a mismatch removes the temporary file and throws `FileChangedError`. A process that can
23
+ * write the folder can still swap the file between that check and the rename.
24
+ */
25
+ export declare function writeFileAtomic(filePath: string, bytes: Uint8Array, mode?: number, options?: {
26
+ expectSha256?: string | null;
27
+ }): Promise<string>;
15
28
  /** Canonical path of `target`, resolving symlinks on the longest existing prefix. A dangling link on the way is an error. */
16
29
  export declare function realpathAllowingMissing(target: string): Promise<string>;
17
30
  /**
@@ -1,4 +1,4 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { createHash, randomBytes } from 'node:crypto';
2
2
  import { constants as fsConstants } from 'node:fs';
3
3
  import { lstat, open, realpath, rename, unlink } from 'node:fs/promises';
4
4
  import path from 'node:path';
@@ -120,8 +120,35 @@ export async function writeNewFile(filePath, bytes, mode = DEFAULT_FILE_MODE) {
120
120
  await writeHandle(target, bytes, mode, flags);
121
121
  return target;
122
122
  }
123
- /** Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one. */
124
- export async function writeFileAtomic(filePath, bytes, mode = DEFAULT_FILE_MODE) {
123
+ /** The file a write was meant to replace was no longer the one that was read (see `writeFileAtomic`'s `expectSha256`). */
124
+ export class FileChangedError extends Error {
125
+ constructor(message = 'File changed before it could be replaced') {
126
+ super(message);
127
+ this.name = 'FileChangedError';
128
+ }
129
+ }
130
+ /** `sha256:<hex>` of the regular file at `target`, or `null` when it does not exist. Anything else throws. */
131
+ async function currentSha256(target) {
132
+ let bytes;
133
+ try {
134
+ bytes = await readRegularFile(target, 'Document', Number.MAX_SAFE_INTEGER);
135
+ }
136
+ catch (error) {
137
+ if (error?.code === 'ENOENT')
138
+ return null;
139
+ throw new FileChangedError();
140
+ }
141
+ return `sha256:${createHash('sha256').update(bytes).digest('hex')}`;
142
+ }
143
+ /**
144
+ * Writes via a temporary sibling and rename, so readers see the old or the new file, never a partial one.
145
+ *
146
+ * `options.expectSha256`: `undefined` checks nothing. A `sha256:<hex>` string requires the existing path to be a regular
147
+ * file with that SHA-256, `null` requires the path not to exist. The check runs after the temporary file is written and
148
+ * immediately before the rename; a mismatch removes the temporary file and throws `FileChangedError`. A process that can
149
+ * write the folder can still swap the file between that check and the rename.
150
+ */
151
+ export async function writeFileAtomic(filePath, bytes, mode = DEFAULT_FILE_MODE, options = {}) {
125
152
  const target = path.resolve(filePath);
126
153
  const randomHex = randomBytes(TEMP_RANDOM_BYTES).toString('hex');
127
154
  const temporary = path.join(path.dirname(target), `.${path.basename(target)}.${randomHex}.tmp`);
@@ -137,6 +164,8 @@ export async function writeFileAtomic(filePath, bytes, mode = DEFAULT_FILE_MODE)
137
164
  }
138
165
  await writeHandle(temporary, bytes, mode, flags);
139
166
  try {
167
+ if (options.expectSha256 !== undefined && (await currentSha256(target)) !== options.expectSha256)
168
+ throw new FileChangedError();
140
169
  await rename(temporary, target);
141
170
  }
142
171
  catch (error) {
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,4 @@
1
+ // Entry point of the Claude Code hook: `env -i node --no-addons claude-code-hook.js <config.json> <enforce|shadow>`.
2
+ // The config, socket directory and socket must be root-owned; see claude-code.ts.
3
+ import { hookMain } from "./hook-main.js";
4
+ await hookMain(process.argv.slice(2, 4));
@@ -0,0 +1,13 @@
1
+ import type { Mode } from '../../policy.ts';
2
+ export interface ClaudeCodeSettingsInput {
3
+ mode: Mode;
4
+ nodePath: string;
5
+ hookEntry: string;
6
+ configPath: string;
7
+ hookTimeoutSec: number;
8
+ /** Must match the hook config's self_deadline_ms; the host timeout has to outlast it by at least 1 s. */
9
+ selfDeadlineMs: number;
10
+ /** Absolute path of env(1); default /usr/bin/env. */
11
+ envPath?: string;
12
+ }
13
+ export declare function claudeCodeManagedSettings(input: ClaudeCodeSettingsInput): Record<string, unknown>;
@@ -0,0 +1,49 @@
1
+ // Managed-settings generator for the Claude Code hook adapter. Pure: no file access.
2
+ // EVIDENCE: every field marked [cc0.4] is copied from .agent/reviews/cc0.4-fixtures/setup.sh as tested on Claude Code CLI
3
+ // 2.1.296 / Linux (cc0.3-b2b-enforcement-check.md, cc0.4-enforcement-verification.md). The generated settings were also
4
+ // run live on 2.1.318 (-p mode) with the real service and hook: the locks hid every project, user and bundled Skill
5
+ // (tests/live/claude-code-gate.live.ts, docs/spikes/claude-code-gate-live.md). Unverified for any other version;
6
+ // the native locks are bounded spike observations, not a broad host-level guarantee.
7
+ // ENDPOINT REQUIREMENTS (founder-accepted deployment requirements, NOT enforced by this file): the hook command is
8
+ // started with `env -i`, which scrubs NODE_OPTIONS/NODE_PATH/PYTHONPATH etc. for the interpreter, but loader-time
9
+ // variables act BEFORE `env` runs: LD_PRELOAD on the shell Claude Code uses to run the hook, and BASH_ENV if that shell
10
+ // is bash. Same-UID ptrace of the hook or host also stays an endpoint requirement.
11
+ import path from 'node:path';
12
+ const SAFE_PATH = /^\/[A-Za-z0-9._/-]+$/u; // the command is parsed by a shell: no spaces, quotes or metacharacters
13
+ export function claudeCodeManagedSettings(input) {
14
+ const { mode, nodePath, hookEntry, configPath, hookTimeoutSec, selfDeadlineMs } = input;
15
+ const envPath = input.envPath ?? '/usr/bin/env';
16
+ for (const p of [envPath, nodePath, hookEntry, configPath])
17
+ if (!path.isAbsolute(p) || !SAFE_PATH.test(p))
18
+ throw new Error('paths must be absolute and shell-safe');
19
+ if (mode !== 'enforce' && mode !== 'shadow')
20
+ throw new Error('mode must be enforce or shadow');
21
+ if (!Number.isInteger(hookTimeoutSec) || hookTimeoutSec < 1)
22
+ throw new Error('hookTimeoutSec must be a positive integer');
23
+ if (!Number.isInteger(selfDeadlineMs) || selfDeadlineMs < 1 || hookTimeoutSec * 1000 < selfDeadlineMs + 1000)
24
+ throw new Error('hookTimeoutSec * 1000 must be at least selfDeadlineMs + 1000');
25
+ // env -i: the interpreter starts with an empty environment (the adapter needs none), so NODE_OPTIONS etc. cannot hijack it.
26
+ const command = `${envPath} -i ${nodePath} --no-addons ${hookEntry} ${configPath} ${mode}`;
27
+ const gate = { type: 'command', command, timeout: hookTimeoutSec, ...(mode === 'enforce' ? { onFailure: 'block' } : {}) }; // [cc0.4] onFailure
28
+ const hooks = {
29
+ PreToolUse: [{ matcher: 'Skill', hooks: [gate] }], // [cc0.4]
30
+ UserPromptExpansion: [{ hooks: [gate] }], // [cc0.4]
31
+ SessionStart: [{ hooks: [{ type: 'command', command, timeout: hookTimeoutSec }] }], // never blocks
32
+ };
33
+ if (mode === 'shadow')
34
+ return { hooks }; // shadow must not change behaviour: no native locks
35
+ return {
36
+ strictPluginOnlyCustomization: ['skills', 'hooks', 'agents', 'mcp'], // [cc0.4]
37
+ strictKnownMarketplaces: [], // [cc0.4]
38
+ disableSideloadFlags: true, // [cc0.4]
39
+ allowManagedHooksOnly: true, // [cc0.4]
40
+ requiredMinimumVersion: '2.1.296', // [cc0.4] the tested version
41
+ // Built-in / bundled Skills: [cc0.4] setup.sh removes them so only managed-directory Skills exist. Keys and names are
42
+ // copied from that fixture; unverified for other CLI versions (the built-in plugin ids may differ).
43
+ disableBundledSkills: true, // [cc0.4]
44
+ skillOverrides: { design: 'off', doctor: 'off', 'plugin-authoring': 'off' }, // [cc0.4]
45
+ enabledPlugins: Object.fromEntries(// [cc0.4]
46
+ ['cc-plugin-sec-default', 'cc-plugin-agents-md', 'cc-plugin-telemetry', 'cc-plugin-plugin-authoring'].map((x) => [`${x}@builtin`, false])),
47
+ hooks,
48
+ };
49
+ }