@mago-foundation/mago-ski 0.3.0 → 0.4.1

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 (54) hide show
  1. package/README.md +34 -10
  2. package/action.yml +21 -2
  3. package/dist/hosts/github/run.d.ts +9 -0
  4. package/dist/hosts/github/run.js +30 -16
  5. package/dist/hosts/pi/index.js +40 -18
  6. package/dist/src/admin.d.ts +2 -1
  7. package/dist/src/admin.js +3 -2
  8. package/dist/src/canonical-json.d.ts +6 -0
  9. package/dist/src/canonical-json.js +11 -0
  10. package/dist/src/cli.d.ts +13 -1
  11. package/dist/src/cli.js +426 -8
  12. package/dist/src/diff.d.ts +5 -0
  13. package/dist/src/diff.js +2 -1
  14. package/dist/src/dsse.js +2 -2
  15. package/dist/src/experimental/sigstore.d.ts +6 -0
  16. package/dist/src/experimental/sigstore.js +13 -5
  17. package/dist/src/gate/adapters/claude-code-settings.js +1 -1
  18. package/dist/src/gate/adapters/claude-code.js +1 -0
  19. package/dist/src/gate/adapters/codex-names.d.ts +1 -0
  20. package/dist/src/gate/adapters/codex-names.js +56 -0
  21. package/dist/src/gate/adapters/codex-requirements.d.ts +11 -0
  22. package/dist/src/gate/adapters/codex-requirements.js +56 -29
  23. package/dist/src/gate/adapters/codex.d.ts +3 -0
  24. package/dist/src/gate/adapters/codex.js +147 -20
  25. package/dist/src/gate/admin-client.d.ts +19 -0
  26. package/dist/src/gate/admin-client.js +62 -0
  27. package/dist/src/gate/generations.js +2 -0
  28. package/dist/src/gate/instance.d.ts +57 -0
  29. package/dist/src/gate/instance.js +97 -0
  30. package/dist/src/gate/proc.d.ts +6 -0
  31. package/dist/src/gate/proc.js +14 -3
  32. package/dist/src/gate/service.d.ts +13 -0
  33. package/dist/src/gate/service.js +344 -37
  34. package/dist/src/gate/setup.d.ts +210 -0
  35. package/dist/src/gate/setup.js +1038 -0
  36. package/dist/src/gate/trust-store.d.ts +14 -0
  37. package/dist/src/gate/trust-store.js +66 -0
  38. package/dist/src/index.d.ts +2 -1
  39. package/dist/src/index.js +3 -1
  40. package/dist/src/policy.d.ts +7 -0
  41. package/dist/src/policy.js +19 -2
  42. package/dist/src/recovery-admin.js +7 -4
  43. package/dist/src/root-events.d.ts +2 -0
  44. package/dist/src/root-events.js +61 -4
  45. package/dist/src/tree-digest.d.ts +6 -0
  46. package/dist/src/tree-digest.js +8 -0
  47. package/docs/hosts/adapter-interface.md +1 -1
  48. package/docs/hosts/claude-code.md +108 -0
  49. package/docs/hosts/codex.md +181 -0
  50. package/docs/spec/gui-admin-rack-v1.md +1 -1
  51. package/docs/spec/root-recovery-v1.md +3 -2
  52. package/docs/spec/trust-documents-v1.md +1 -1
  53. package/docs/threat-model.md +13 -1
  54. package/package.json +3 -1
package/dist/src/cli.js CHANGED
@@ -11,7 +11,7 @@ import { appendDecision, decisionRecord, defaultPolicyPath, effectiveMode, findS
11
11
  import { adoptTrustDocuments, appendRootEvent, buildRecoverySet, currentRootState, describeRootEvent, initRootEventLog, prepareRootEvent, recoverySetJson, showRootEvent, signPolicyTimestamp, signRootEvent, } from "./recovery-admin.js";
12
12
  import { isMainModule } from "./main-module.js";
13
13
  import { formatTimestamp } from "./time.js";
14
- import { collectSkillTree, TREE_PROFILE } from "./tree-digest.js";
14
+ import { collectSkillTree, pathsNotCovered, TREE_PROFILE } from "./tree-digest.js";
15
15
  import { verifyTrustRoot } from "./trust-root.js";
16
16
  import { resolveSkillName, unverifiable } from "./verify.js";
17
17
  import { createRequire } from 'node:module';
@@ -50,6 +50,18 @@ CHECKING SKILLS
50
50
  inspect CERTIFICATE Print a certificate's contents
51
51
  policy check Check a policy the way a host does
52
52
 
53
+ COMPANY GATE (Linux, run as root)
54
+ gate init Write the gate's config, unit and host settings
55
+ gate run Run the gate service in the foreground (systemd)
56
+ gate trust Give the running gate the trust documents
57
+ gate install Install an approved Skill through the gate
58
+ gate uninstall Remove a Skill from the gate
59
+ gate refresh Re-read the inbox's trust documents
60
+ gate prune-removed Drop old entries from the Codex removed-names file
61
+ gate status Show the running gate's state
62
+ gate doctor Check an installation, read-only
63
+ Run "mago-ski gate" for the details.
64
+
53
65
  POLICY
54
66
  --policy FILE, else $MAGO_SKI_POLICY, else
55
67
  ~/.mago-ski/policy.json (never the current directory)
@@ -61,7 +73,8 @@ VERDICTS
61
73
  EXIT CODES
62
74
  0 success, or VERIFIED
63
75
  1 any other verdict, or re-certification required
64
- 2 usage or input error
76
+ (gate: a doctor FAIL, or the service refused the request)
77
+ 2 usage or input error (gate: also a transport error)
65
78
 
66
79
  Run "mago-ski <command> --help" for a command's options,
67
80
  and "mago-ski --version" for the version.
@@ -82,6 +95,105 @@ Creates an Ed25519 key pair for a root key or an approver key.
82
95
 
83
96
  Keep private keys secret and outside every Skill directory; keygen refuses to write inside one.
84
97
  Prints the key id (sha256:...), which identifies the key in trust roots and revocations.`,
98
+ /* ****************************************************************************************** */
99
+ /** Per-command: gate (the company gate, Linux, root) */
100
+ /* ****************************************************************************************** */
101
+ gate: `Usage: mago-ski gate <command> [options] (Linux only)
102
+
103
+ The company gate is a root service that installs approved Skills and answers the Claude Code and Codex hooks.
104
+ Each host (claude-code, codex) has its own instance, named by host.
105
+
106
+ init Write the instance config, hook config, systemd unit and the host's managed settings
107
+ run Run the service in the foreground (what the systemd unit starts)
108
+ trust Send the trust root and revocation list to the running gate
109
+ install Install an approved Skill (a folder and its certificate) through the gate
110
+ uninstall Remove a Skill from the gate
111
+ refresh Make the gate re-read its inbox of trust documents
112
+ prune-removed Drop old entries from the Codex removed-names file
113
+ status Show the running gate's state
114
+ doctor Read-only checks of one installation
115
+
116
+ Every command except status and doctor needs root ("sudo mago-ski gate ..."); status needs root too, because the
117
+ admin socket is 0600. Run "mago-ski gate <command> --help" for a command's options.
118
+
119
+ Exit codes: 0 success; 1 a doctor FAIL, or the gate answered that it refused; 2 usage, input or transport error.
120
+
121
+ Codex enforcement depends on organisation controls; read docs/hosts/codex.md before enabling enforce.`,
122
+ 'gate init': `Usage: mago-ski gate init --host claude-code|codex --root-fingerprint ID [options]
123
+
124
+ Writes everything an instance needs and creates its folders. Run it again to change the mode or the host binary.
125
+ It does not run systemctl; it prints the commands to run.
126
+
127
+ --host H claude-code or codex
128
+ --root-fingerprint ID the organisation's root key id (sha256:<64 hex>), as printed by "root init"
129
+ --mode shadow|enforce default shadow (decisions are logged, nothing is blocked). enforce also applies Claude Code's
130
+ managed locks to every user of this machine. Codex enforce depends on organisation controls
131
+ (docs/hosts/codex.md).
132
+ --host-exe PATH the real host binary (repeatable). Default: claude or codex on the invoking user's login PATH
133
+ (SUDO_USER) or root's PATH. It must be a root-owned ELF binary.
134
+ --inbox DIR a folder the gate reads trust-root.json and revocations.json from
135
+ --user-home DIR Codex: a user's home the profile covers (repeatable). Default: every home in /etc/passwd with
136
+ uid 1000 or above and a login shell. Each home's Skill roots get deny_read, and its
137
+ .codex/skills/.system moves to <home>/.codex/mago-ski-backup/system-<UTC>.
138
+ --codex-home DIR Codex: a non-default CODEX_HOME the profile covers (repeatable)
139
+ --no-deny-read Codex: leave deny_read out of requirements.toml
140
+ --lock-user-skill-folders Codex: make ~/.agents, ~/.agents/skills and ~/.codex/skills empty, root-owned and immutable
141
+ (chattr +i) in every listed home. Stops if the attribute cannot be set.
142
+ --new-root move an installed gate to a new root key (after a root rotation). Needed whenever
143
+ --root-fingerprint differs from the installed one; without it init refuses. The old root's
144
+ stored documents are kept, unused. Then restart the service and run gate trust with the
145
+ documents signed by the new root.
146
+ --force move aside (to <file>.mago-ski-bak-<time>) host files that mago-ski did not write, then replace them
147
+ --print print every file that would be written and write nothing (no root needed)
148
+ --json machine-readable output
149
+
150
+ Writes (root-owned): /etc/mago-ski/gate/<host>.json, <host>-hook.json, <host>.manifest.json, shared.manifest.json,
151
+ /etc/systemd/system/mago-ski-gate@.service and mago-ski-gate@<host>.service.d/paths.conf, and the host's settings
152
+ (Claude Code: /etc/claude-code/managed-settings.json; Codex: /etc/codex/requirements.toml and
153
+ /etc/codex/managed_config.toml). Creates the state,
154
+ generations and managed Skill folders.
155
+
156
+ Refuses when the installed package, the node that runs the hooks or a host binary could be edited by a user: an
157
+ editable hook would let a user bypass the gate. Node must be installed system-wide (a per-user nvm or volta node is refused).
158
+ Exit 0 written; 2 refused or failed.`,
159
+ 'gate run': `Usage: mago-ski gate run --host claude-code|codex
160
+
161
+ Runs the gate service for one instance in the foreground, from /etc/mago-ski/gate/<host>.json. This is what the systemd
162
+ unit starts. Stops on SIGTERM or SIGINT. If the stores cannot be opened the service stays up and not ready (status says
163
+ why; the reason is printed once to stderr). Exits 1 when the service cannot start at all.`,
164
+ 'gate trust': `Usage: mago-ski gate trust --host H --trust-root FILE --revocations FILE
165
+
166
+ Sends the organisation's trust root and revocation list to the running gate (the admin socket). Run it after init, and
167
+ whenever either document is renewed (or use an inbox: gate init --inbox DIR, then gate refresh).
168
+ Exit 0 accepted or unchanged; 1 the gate refused them (the reason is printed); 2 usage or transport error.`,
169
+ 'gate install': `Usage: mago-ski gate install --host H SKILL_DIR --certificate FILE [--name NAME]
170
+
171
+ Installs an approved Skill version through the running gate: the gate verifies the folder against the certificate,
172
+ publishes it and links it into the host's managed Skill folder. NAME defaults to the folder's name.
173
+ Prints the digest and the managed path. Exit 0 installed; 1 the gate refused; 2 usage or transport error.`,
174
+ 'gate uninstall': `Usage: mago-ski gate uninstall --host H NAME
175
+
176
+ Hides the Skill from the host and removes it from the gate's records. Exit 0; 1 the gate refused; 2 usage or transport error.`,
177
+ 'gate refresh': `Usage: mago-ski gate refresh --host H
178
+
179
+ Makes the gate re-read its inbox (trust-root.json and revocations.json) now. Needs an instance made with --inbox;
180
+ otherwise it prints "no inbox configured" and exits 2. Exit 0; 1 the gate refused; 2 usage or transport error.`,
181
+ 'gate prune-removed': `Usage: mago-ski gate prune-removed --host codex [--older-than-days N]
182
+
183
+ The gate records the Skills it removed in <managed folder>/.mago-ski-removed-names.json (at most 4096 entries; the oldest
184
+ go first). This drops entries older than N days (default 90, at least 7), so the file stays below its cap. Blocking rests
185
+ on the removed link, so pruning only loses the clear message for an old name.
186
+ Exit 0; 1 the gate refused; 2 usage or transport error.`,
187
+ 'gate status': `Usage: mago-ski gate status --host H [--json]
188
+
189
+ Asks the running gate for its state: mode, readiness, trust, revocation-list expiry and decision-log health.
190
+ Needs root (the admin socket is 0600). Exit 0; 1 the gate answered that it is not ready; 2 usage or transport error.`,
191
+ 'gate doctor': `Usage: mago-ski gate doctor --host H [--json]
192
+
193
+ Read-only checks of one installation: platform, instance config, host binaries, hook entry and node, folders, the host's
194
+ settings (the exact content gate init would write), the service, trust, mode, and two kernel settings. Prints one line per
195
+ check: PASS, FAIL, SKIP or WARN. SKIP and WARN never fail the run. Without root the service and trust checks are skipped.
196
+ Exit 0 when nothing FAILs; 1 when a check FAILs; 2 usage error.`,
85
197
  /* ****************************************************************************************** */
86
198
  /** Per-command: root */
87
199
  /* ****************************************************************************************** */
@@ -346,7 +458,9 @@ function readVersion() {
346
458
  class UsageError extends Error {
347
459
  }
348
460
  /* The actual boolean flags that should take no value. */
349
- const BOOLEAN_FLAGS = new Set(['--json', '--explain', '--help']);
461
+ const BOOLEAN_FLAGS = new Set(['--json', '--explain', '--help', '--force', '--print', '--no-deny-read', '--lock-user-skill-folders', '--new-root']);
462
+ /* Only `gate init` takes these; everywhere else they are refused, as before 0.4.0. */
463
+ const GATE_INIT_ONLY = new Set(['--force', '--print', '--no-deny-read', '--lock-user-skill-folders', '--new-root']);
350
464
  /* flags Map: A map of flags to their values. */
351
465
  function addFlag(flags, flag, value) {
352
466
  const values = flags.get(flag) ?? [];
@@ -390,7 +504,7 @@ function allow(parsed, allowed = [], positional = 0, repeatable = []) {
390
504
  }
391
505
  /* Check boolean flags for validity. */
392
506
  for (const flag of parsed.booleans)
393
- if (!BOOLEAN_FLAGS.has(flag) && !allowed.includes(flag))
507
+ if (!allowed.includes(flag) && (GATE_INIT_ONLY.has(flag) || !BOOLEAN_FLAGS.has(flag)))
394
508
  throw new UsageError(`Unsupported option ${flag}`);
395
509
  /* Check positional arguments count. */
396
510
  const count = parsed.positional.length;
@@ -432,7 +546,23 @@ function printResult(result, json) {
432
546
  return;
433
547
  }
434
548
  const mark = result.verdict === 'VERIFIED' ? 'ok' : 'FAIL';
435
- process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${result.skillName} ${result.reason}\n`);
549
+ // A VERIFIED line must not read as "everything in this folder is approved" when the Skill excludes files from its digest.
550
+ const notCovered = result.verdict === 'VERIFIED' ? pathsNotCovered(result.excluded) : [];
551
+ const note = notCovered.length > 0 ? ` (${notCovered.length} path${notCovered.length === 1 ? '' : 's'} not covered by the certificate: ${shownPaths(notCovered)})` : '';
552
+ // The name can be a folder's name when SKILL.md could not be read, and a reason can quote paths: neither may carry a
553
+ // line break or a terminal escape that would draw a second, made-up result line.
554
+ process.stdout.write(`${mark.padEnd(4)} ${result.verdict.padEnd(17)} ${terminalSafe(result.skillName)} ${terminalSafe(result.reason)}${note}\n`);
555
+ }
556
+ /** Text from a Skill or its folder, for one terminal line: control, line-separator and bidirectional characters are escaped. */
557
+ export function terminalSafe(value) {
558
+ return value.replace(/[\u0000-\u001f\u007f-\u009f\u200e\u200f\u2028-\u202e\u2066-\u2069]/gu, (c) => `\\u${c.codePointAt(0).toString(16).padStart(4, '0')}`);
559
+ }
560
+ /** Up to three paths, escaped for the terminal (the names come from the Skill). */
561
+ function shownPaths(paths) {
562
+ return `${paths.slice(0, 3).map(terminalSafe).join(', ')}${paths.length > 3 ? ', ...' : ''}`;
563
+ }
564
+ function notCoveredNote(paths) {
565
+ return `${paths.length} path${paths.length === 1 ? ' is' : 's are'} excluded from the digest by .skilldigestignore (${shownPaths(paths)}).`;
436
566
  }
437
567
  /* ****************************************************************************************** */
438
568
  async function runRoot(sub, parsed, now) {
@@ -741,7 +871,12 @@ async function runPolicyCheck(sub, parsed, now) {
741
871
  report.verdict = trust.verdict;
742
872
  report.reason = trust.reason;
743
873
  }
874
+ // Without a state file a host remembers nothing between runs, so an older, still valid trust root, revocation list,
875
+ // root event log or timestamp is accepted again. The policy loads, so this is said here, where a setup is checked.
876
+ report.rollback_protection = policy.statePath !== null;
744
877
  print(report);
878
+ if (policy.statePath === null)
879
+ process.stderr.write('warning: the policy has no state_file, so this host does not remember the versions it has seen: an older, still valid trust root or revocation list would be accepted again. Add "state_file" to the policy.\n');
745
880
  return trust.ok ? 0 : 1;
746
881
  }
747
882
  async function runVerify(parsed, now) {
@@ -800,7 +935,278 @@ async function runVerifyAll(parsed, now) {
800
935
  process.stdout.write(`${results.length - failures}/${results.length} Skills verified (mode: ${policy.mode})\n`);
801
936
  return failures === 0 ? 0 : 1;
802
937
  }
803
- export async function runCli(argv = process.argv.slice(2), now = new Date()) {
938
+ const GATE_SUBS = ['init', 'run', 'trust', 'install', 'uninstall', 'refresh', 'prune-removed', 'status', 'doctor'];
939
+ /* Only the listed boolean flags are accepted (--help is handled before). */
940
+ function onlyBooleans(parsed, accepted) {
941
+ for (const flag of parsed.booleans)
942
+ if (!accepted.includes(flag))
943
+ throw new UsageError(`Unsupported option ${flag}`);
944
+ }
945
+ function gateHost(parsed) {
946
+ const host = one(parsed, '--host');
947
+ if (host !== 'claude-code' && host !== 'codex')
948
+ throw new UsageError('--host must be claude-code or codex');
949
+ return host;
950
+ }
951
+ async function runGate(sub, parsed, seams) {
952
+ if (!sub || !GATE_SUBS.includes(sub))
953
+ throw new UsageError(`Unknown gate command: ${sub ?? '(none)'}. Run "mago-ski gate --help".`);
954
+ const { assertGatePlatform } = await import("./gate/proc.js");
955
+ assertGatePlatform(seams.platform);
956
+ const isRoot = (seams.uid ?? process.getuid?.() ?? -1) === (seams.rootUid ?? 0);
957
+ const needRoot = () => {
958
+ if (!isRoot)
959
+ throw new Error('the gate is administered as root; run this with sudo');
960
+ };
961
+ const json = parsed.booleans.has('--json');
962
+ const out = (line) => { process.stdout.write(`${line}\n`); };
963
+ const setup = await import("./gate/setup.js");
964
+ const inst = await import("./gate/instance.js");
965
+ const { askAdmin, checkAdminSocket } = await import("./gate/admin-client.js");
966
+ /* The real client first checks that the admin socket folder and the socket are root's (item 5). */
967
+ const ask = seams.ask ?? (async (socketPath, command, deadlineMs) => {
968
+ await checkAdminSocket(path.dirname(socketPath), seams.rootUid ?? 0);
969
+ return await askAdmin(socketPath, command, deadlineMs);
970
+ });
971
+ const base = seams.base ?? '/';
972
+ const uid = seams.rootUid ?? 0;
973
+ /* The instance config; a missing one is a usage error (exit 2) with the command that makes it. */
974
+ const loadInstance = async (host) => {
975
+ try {
976
+ return await inst.readInstanceConfig(inst.instancePaths(host, base).instance, uid);
977
+ }
978
+ catch (error) {
979
+ if (error?.code === 'ENOENT')
980
+ throw new Error(inst.missingInstanceMessage(host));
981
+ throw error;
982
+ }
983
+ };
984
+ switch (sub) {
985
+ case 'init': {
986
+ allow(parsed, ['--host', '--root-fingerprint', '--mode', '--host-exe', '--inbox', '--user-home', '--codex-home', '--force', '--print', '--no-deny-read', '--lock-user-skill-folders', '--new-root'], 0, ['--host-exe', '--user-home', '--codex-home']);
987
+ onlyBooleans(parsed, ['--force', '--print', '--json', '--no-deny-read', '--lock-user-skill-folders', '--new-root']);
988
+ const mode = optional(parsed, '--mode');
989
+ if (mode !== undefined && mode !== 'shadow' && mode !== 'enforce')
990
+ throw new UsageError('--mode must be shadow or enforce');
991
+ const printOnly = parsed.booleans.has('--print');
992
+ if (!printOnly)
993
+ needRoot();
994
+ const inbox = optional(parsed, '--inbox');
995
+ const plan = await setup.planInit({
996
+ host: gateHost(parsed), rootFingerprint: one(parsed, '--root-fingerprint'),
997
+ ...(mode ? { mode } : {}), ...(parsed.flags.get('--host-exe') ? { hostExes: parsed.flags.get('--host-exe') } : {}),
998
+ ...(inbox ? { inbox } : {}),
999
+ ...(parsed.flags.get('--user-home') ? { userHomes: parsed.flags.get('--user-home') } : {}),
1000
+ ...(parsed.flags.get('--codex-home') ? { codexHomes: parsed.flags.get('--codex-home') } : {}),
1001
+ ...(parsed.booleans.has('--no-deny-read') ? { noDenyRead: true } : {}),
1002
+ ...(parsed.booleans.has('--lock-user-skill-folders') ? { lockUserSkillFolders: true } : {}),
1003
+ ...(parsed.booleans.has('--new-root') ? { newRoot: true } : {}),
1004
+ ...(seams.chattr ? { chattr: seams.chattr } : {}), ...(seams.isImmutable ? { isImmutable: seams.isImmutable } : {}),
1005
+ ...(seams.base !== undefined ? { base: seams.base } : {}), ...(seams.rootUid !== undefined ? { rootUid: seams.rootUid } : {}),
1006
+ ...(seams.platform ? { platform: seams.platform } : {}), ...(seams.installRoot ? { installRoot: seams.installRoot } : {}),
1007
+ ...(seams.nodePath ? { nodePath: seams.nodePath } : {}), ...(seams.envPath ? { envPath: seams.envPath } : {}),
1008
+ ...(seams.checkExec !== undefined ? { checkExec: seams.checkExec } : {}),
1009
+ ...(seams.resolveHostExe ? { resolveHostExe: seams.resolveHostExe } : {}),
1010
+ });
1011
+ if (printOnly) {
1012
+ if (json)
1013
+ print(plan.files.map((f) => ({ path: f.path, mode: f.mode.toString(8).padStart(4, '0'), content: f.content })));
1014
+ else
1015
+ for (const f of plan.files)
1016
+ out(`# ${f.path} (mode ${f.mode.toString(8).padStart(4, '0')})\n${f.content}`);
1017
+ for (const problem of plan.problems)
1018
+ process.stderr.write(`warning: ${problem}\n`);
1019
+ for (const foreign of plan.foreign)
1020
+ process.stderr.write(`note: ${foreign} exists and was not written by mago-ski; init would refuse unless --force is given\n`);
1021
+ if (plan.rootChange)
1022
+ process.stderr.write(`note: init would move this gate from root ${plan.rootChange.from} to ${plan.rootChange.to}\n`);
1023
+ for (const a of plan.actions)
1024
+ process.stderr.write(a.kind === 'move-system' ? `note: init would move ${a.from} to ${a.to}\n` : `note: init would lock the user Skill folders of ${a.home} (empty, root-owned, chattr +i)\n`);
1025
+ return plan.problems.length > 0 ? 1 : 0; // init would refuse these: everything is printed first, then the exit code says so
1026
+ }
1027
+ for (const a of plan.actions)
1028
+ if (!json)
1029
+ out(a.kind === 'move-system' ? `will move ${a.from} -> ${a.to}` : `will lock the user Skill folders of ${a.home} (empty, root-owned, chattr +i)`);
1030
+ const result = await setup.applyInit(plan, { force: parsed.booleans.has('--force'), base, rootUid: uid, ...(seams.chattr ? { chattr: seams.chattr } : {}), ...(seams.isImmutable ? { isImmutable: seams.isImmutable } : {}) });
1031
+ if (json)
1032
+ print({ host: plan.host, mode: plan.mode, ...(plan.rootChange ? { root_change: plan.rootChange } : {}), host_exes: plan.hostExes, written: result.written, created: result.dirs, moved_aside: result.backups, moved_system: result.movedSystem, locked: result.locked, next: plan.next });
1033
+ else {
1034
+ for (const b of result.backups)
1035
+ out(`moved ${b.from} -> ${b.to}`);
1036
+ for (const d of result.dirs)
1037
+ out(`created ${d}`);
1038
+ for (const w of result.written)
1039
+ out(`wrote ${w}`);
1040
+ for (const m of result.movedSystem)
1041
+ out(`moved ${m.from} -> ${m.to}`);
1042
+ for (const l of result.locked)
1043
+ out(`locked ${l}`);
1044
+ out(`host binaries: ${plan.hostExes.join(', ')}`);
1045
+ if (plan.rootChange)
1046
+ out(`root: moved from ${plan.rootChange.from} to ${plan.rootChange.to}. The old root's stored documents are kept and no longer used. After the restart, nothing is accepted until gate trust sends the new root's documents${plan.mode === 'enforce' ? '; until then every Skill is blocked' : ''}.`);
1047
+ out(`mode: ${plan.mode}${plan.mode === 'shadow' ? ' (nothing is blocked; re-run with --mode enforce to enforce)' : ''}`);
1048
+ if (plan.host === 'codex' && plan.mode === 'enforce')
1049
+ out(setup.CODEX_ENFORCE_NOTE);
1050
+ out('next:');
1051
+ for (const n of plan.next)
1052
+ out(` ${n}`);
1053
+ }
1054
+ return 0;
1055
+ }
1056
+ case 'run': {
1057
+ allow(parsed, ['--host'], 0);
1058
+ onlyBooleans(parsed, []);
1059
+ needRoot();
1060
+ const host = gateHost(parsed);
1061
+ const p = inst.instancePaths(host, base);
1062
+ const cfg = await loadInstance(host);
1063
+ if (cfg.host !== host)
1064
+ throw new Error(`${p.instance} is for host ${cfg.host}`);
1065
+ const { createGateService } = await import("./gate/service.js");
1066
+ const service = createGateService(inst.instanceToServiceConfig(cfg, uid));
1067
+ try {
1068
+ await service.start();
1069
+ }
1070
+ catch (error) {
1071
+ process.stderr.write(`mago-ski gate: cannot start: ${error?.message ?? 'failed'}\n`);
1072
+ await service.stop().catch(() => { }); // a listener that did start must not keep the process alive
1073
+ return 1;
1074
+ }
1075
+ if (service.startError)
1076
+ process.stderr.write(`mago-ski gate: running but not ready: ${service.startError}\n`);
1077
+ process.stderr.write(`mago-ski gate: ${host} (${cfg.mode}) listening on ${service.sockets.decision}\n`);
1078
+ await (seams.stop ?? new Promise((resolve) => { process.once('SIGTERM', () => resolve()); process.once('SIGINT', () => resolve()); }));
1079
+ await service.stop();
1080
+ return 0;
1081
+ }
1082
+ case 'doctor': {
1083
+ allow(parsed, ['--host'], 0);
1084
+ onlyBooleans(parsed, ['--json']);
1085
+ const checks = await setup.doctor(gateHost(parsed), {
1086
+ base, rootUid: uid, ...(seams.ask ? { ask: seams.ask } : {}),
1087
+ ...(seams.uid !== undefined ? { uid: seams.uid } : {}),
1088
+ ...(seams.platform ? { platform: seams.platform } : {}), ...(seams.installRoot ? { installRoot: seams.installRoot } : {}),
1089
+ ...(seams.nodePath ? { nodePath: seams.nodePath } : {}), ...(seams.envPath ? { envPath: seams.envPath } : {}),
1090
+ ...(seams.checkExec !== undefined ? { checkExec: seams.checkExec } : {}),
1091
+ ...(seams.doctor ?? {}),
1092
+ });
1093
+ if (json)
1094
+ print(checks);
1095
+ else
1096
+ for (const c of checks)
1097
+ out(`${c.result} ${c.check}: ${c.detail}`);
1098
+ return checks.some((c) => c.result === 'FAIL') ? 1 : 0;
1099
+ }
1100
+ }
1101
+ // The remaining commands talk to the running service's admin socket.
1102
+ const talk = async (host, command) => {
1103
+ const cfg = await loadInstance(host);
1104
+ if (cfg.host !== host)
1105
+ throw new Error(`the instance config is for host ${cfg.host}`);
1106
+ return { cfg, reply: await ask(`${cfg.admin_socket_dir}/admin.sock`, command) };
1107
+ };
1108
+ const refused = (error) => {
1109
+ process.stderr.write(`mago-ski gate: the gate refused: ${error}\n`);
1110
+ return 1;
1111
+ };
1112
+ const b64 = async (file, label) => (await readRegularFile(file, label, 4 * 1024 * 1024)).toString('base64');
1113
+ switch (sub) {
1114
+ case 'trust': {
1115
+ allow(parsed, ['--host', '--trust-root', '--revocations'], 0);
1116
+ onlyBooleans(parsed, []);
1117
+ needRoot();
1118
+ const { reply } = await talk(gateHost(parsed), {
1119
+ cmd: 'accept-trust', trust_root_b64: await b64(one(parsed, '--trust-root'), 'Trust root'), revocations_b64: await b64(one(parsed, '--revocations'), 'Revocation list'),
1120
+ });
1121
+ if (!reply.ok)
1122
+ return refused(reply.error);
1123
+ out(reply['changed'] === false ? 'trust: unchanged' : 'trust: accepted');
1124
+ return 0;
1125
+ }
1126
+ case 'install': {
1127
+ allow(parsed, ['--host', '--certificate', '--name'], 1);
1128
+ onlyBooleans(parsed, []);
1129
+ needRoot();
1130
+ const dir = path.resolve(parsed.positional[0]);
1131
+ const name = optional(parsed, '--name') ?? path.basename(dir);
1132
+ const { cfg, reply } = await talk(gateHost(parsed), {
1133
+ cmd: 'install', skill_name: name, source_dir: dir, certificate_b64: await b64(one(parsed, '--certificate'), 'Certificate'),
1134
+ });
1135
+ if (!reply.ok)
1136
+ return refused(reply.error);
1137
+ out(`installed ${name} digest=${String(reply['digest'])} path=${path.join(cfg.managed_dir, name)}`);
1138
+ return 0;
1139
+ }
1140
+ case 'uninstall': {
1141
+ allow(parsed, ['--host'], 1);
1142
+ onlyBooleans(parsed, []);
1143
+ needRoot();
1144
+ const { reply } = await talk(gateHost(parsed), { cmd: 'uninstall', skill_name: parsed.positional[0] });
1145
+ if (!reply.ok)
1146
+ return refused(reply.error);
1147
+ out(`uninstalled ${parsed.positional[0]}`);
1148
+ return 0;
1149
+ }
1150
+ case 'prune-removed': {
1151
+ allow(parsed, ['--host', '--older-than-days'], 0);
1152
+ onlyBooleans(parsed, []);
1153
+ needRoot();
1154
+ const raw = optional(parsed, '--older-than-days');
1155
+ if (raw !== undefined && !/^[0-9]{1,5}$/u.test(raw))
1156
+ throw new UsageError('--older-than-days must be a whole number of days');
1157
+ const { reply } = await talk(gateHost(parsed), { cmd: 'prune-removed', ...(raw !== undefined ? { older_than_days: Number(raw) } : {}) });
1158
+ if (!reply.ok)
1159
+ return refused(reply.error);
1160
+ out(`pruned ${String(reply['pruned'])} removed name(s); ${String(reply['remaining'])} remain`);
1161
+ return 0;
1162
+ }
1163
+ case 'refresh': {
1164
+ allow(parsed, ['--host'], 0);
1165
+ onlyBooleans(parsed, []);
1166
+ needRoot();
1167
+ const { reply } = await talk(gateHost(parsed), { cmd: 'refresh' });
1168
+ if (!reply.ok) {
1169
+ if (reply.error === 'no inbox configured') {
1170
+ process.stderr.write('mago-ski gate: no inbox configured (re-run gate init with --inbox DIR)\n');
1171
+ return 2;
1172
+ }
1173
+ return refused(reply.error);
1174
+ }
1175
+ out(`refresh: ${String(reply['result'])}`);
1176
+ return 0;
1177
+ }
1178
+ default: { // status
1179
+ allow(parsed, ['--host'], 0);
1180
+ onlyBooleans(parsed, ['--json']);
1181
+ if (!isRoot)
1182
+ throw new Error('gate status needs root: the admin socket is readable only by root; run this with sudo');
1183
+ const { reply } = await talk(gateHost(parsed), { cmd: 'status' });
1184
+ if (!reply.ok)
1185
+ return refused(reply.error);
1186
+ const exit = reply['ready'] === true ? 0 : 1;
1187
+ if (json) {
1188
+ print(reply);
1189
+ return exit;
1190
+ }
1191
+ const log = (reply['log'] ?? {});
1192
+ out(`mode: ${String(reply['mode'])}`);
1193
+ out(`ready: ${String(reply['ready'])}`);
1194
+ out(`trust: ${String(reply['trust'])}`);
1195
+ out(`revocation list valid until: ${String(reply['revocationsExpiresAt'])}`);
1196
+ out(`decision log: ${String(log['state'])}`);
1197
+ // Shown only when present: what hosts can still see although it should not be served.
1198
+ const names = (v) => (Array.isArray(v) ? v.map((x) => (typeof x === 'string' ? x : String(x?.['name']))) : []);
1199
+ if (typeof reply['reconcileError'] === 'string')
1200
+ out(`reconcile error: ${reply['reconcileError']}`);
1201
+ if (names(reply['unrecorded']).length > 0)
1202
+ out(`no install record (hosts can load these): ${names(reply['unrecorded']).join(', ')}`);
1203
+ if (names(reply['wouldUninstall']).length > 0)
1204
+ out(`would uninstall in enforce mode (expired or no longer matching): ${names(reply['wouldUninstall']).join(', ')}`);
1205
+ return exit;
1206
+ }
1207
+ }
1208
+ }
1209
+ export async function runCli(argv = process.argv.slice(2), now = new Date(), gateSeams = {}) {
804
1210
  if (argv[0] === '--version' || argv[0] === '-V' || argv[0] === 'version') {
805
1211
  process.stdout.write(`mago-ski ${readVersion()}\n`);
806
1212
  return 0;
@@ -813,6 +1219,10 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
813
1219
  return 0;
814
1220
  }
815
1221
  const [command, maybeSub] = argv;
1222
+ if (command === 'gate' && argv.length === 1) {
1223
+ process.stdout.write(`${COMMAND_HELP['gate']}\n`);
1224
+ return 0;
1225
+ }
816
1226
  if (argv.slice(1).some((arg) => arg === '--help' || arg === '-h')) {
817
1227
  const sub = maybeSub && !maybeSub.startsWith('-') ? `${command} ${maybeSub}` : undefined;
818
1228
  const text = (sub && COMMAND_HELP[sub]) ?? COMMAND_HELP[command];
@@ -821,7 +1231,7 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
821
1231
  process.stdout.write(`${text}\n`);
822
1232
  return 0;
823
1233
  }
824
- const hasSub = ['root', 'revoke', 'recovery', 'root-events', 'timestamp', 'policy'].includes(command);
1234
+ const hasSub = ['root', 'revoke', 'recovery', 'root-events', 'timestamp', 'policy', 'gate'].includes(command);
825
1235
  const parsed = parseArgs(argv.slice(hasSub ? 2 : 1));
826
1236
  switch (command) {
827
1237
  case 'keygen': {
@@ -843,6 +1253,8 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
843
1253
  return await runTimestamp(maybeSub, parsed, now);
844
1254
  case 'policy':
845
1255
  return await runPolicyCheck(maybeSub, parsed, now);
1256
+ case 'gate':
1257
+ return await runGate(maybeSub, parsed, gateSeams);
846
1258
  case 'approve': {
847
1259
  allow(parsed, ['--key', '--expires', '--reason', '--name', '--previous', '--out', '--expect-digest'], 1);
848
1260
  const result = await approveSkill({
@@ -862,8 +1274,11 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
862
1274
  digest: result.digest,
863
1275
  certificate_id: result.certificateId,
864
1276
  expires_at: formatTimestamp(result.expiresAt),
865
- certificate: result.path
1277
+ certificate: result.path,
1278
+ ...(result.notCovered.length > 0 ? { not_covered: result.notCovered } : {}),
866
1279
  });
1280
+ if (result.notCovered.length > 0)
1281
+ process.stderr.write(`warning: ${notCoveredNote(result.notCovered)} This approval does not cover them: they can change without invalidating it.\n`);
867
1282
  return 0;
868
1283
  }
869
1284
  case 'verify':
@@ -885,6 +1300,9 @@ export async function runCli(argv = process.argv.slice(2), now = new Date()) {
885
1300
  allow(parsed, ['--base', '--candidate'], 0);
886
1301
  const result = await diffSkillTrees(one(parsed, '--base'), one(parsed, '--candidate'));
887
1302
  print(result);
1303
+ const skipped = [...new Set([...result.not_compared.base, ...result.not_compared.candidate])];
1304
+ if (skipped.length > 0)
1305
+ process.stderr.write(`warning: ${notCoveredNote(skipped)} They were not compared.\n`);
888
1306
  return result.recertification_required ? 1 : 0;
889
1307
  }
890
1308
  case 'inspect': {
@@ -22,5 +22,10 @@ export interface DiffResult {
22
22
  };
23
23
  diff_truncated: boolean;
24
24
  files: FileChange[];
25
+ /** Paths each side's `.skilldigestignore` keeps out of the digest. They are not compared: UNCHANGED says nothing about them. */
26
+ not_compared: {
27
+ base: string[];
28
+ candidate: string[];
29
+ };
25
30
  }
26
31
  export declare function diffSkillTrees(baseRoot: string, candidateRoot: string): Promise<DiffResult>;
package/dist/src/diff.js CHANGED
@@ -1,4 +1,4 @@
1
- import { collectSkillTree, compareTreePaths, sha256Hex } from "./tree-digest.js";
1
+ import { collectSkillTree, compareTreePaths, pathsNotCovered, sha256Hex } from "./tree-digest.js";
2
2
  const textDecoder = new TextDecoder('utf-8', { fatal: true });
3
3
  const MAX_ANALYZED_TEXT_BYTES = 2 * 1024 * 1024;
4
4
  /** Before + after bytes, summed over every file: per-file limits alone allow ~500 MiB of parsing. */
@@ -400,5 +400,6 @@ export async function diffSkillTrees(baseRoot, candidateRoot) {
400
400
  },
401
401
  diff_truncated: diff.truncated,
402
402
  files: diff.files,
403
+ not_compared: { base: pathsNotCovered(base.excluded), candidate: pathsNotCovered(candidate.excluded) },
403
404
  };
404
405
  }
package/dist/src/dsse.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // DSSE (Dead Simple Signing Envelope) v1 with exactly one Ed25519 signature.
2
2
  // https://github.com/secure-systems-lab/dsse/blob/master/protocol.md
3
3
  import { sign, verify } from 'node:crypto';
4
- import { canonicalBytes, exactKeys, parseCanonicalJsonBytes, requireArray, requireString } from "./canonical-json.js";
4
+ import { exactKeys, parseCanonicalJsonBytes, readableCanonicalBytes, requireArray, requireString } from "./canonical-json.js";
5
5
  import { validateKeyId } from "./keys.js";
6
6
  const BASE64_PATTERN = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u;
7
7
  /** Pre-Authentication Encoding: "DSSEv1" SP LEN(type) SP type SP LEN(body) SP body, lengths in bytes. */
@@ -26,7 +26,7 @@ export function signEnvelope(payloadType, payload, keyId, privateKey) {
26
26
  };
27
27
  }
28
28
  export function envelopeBytes(envelope) {
29
- return canonicalBytes(envelope);
29
+ return readableCanonicalBytes(envelope, 'The signed document');
30
30
  }
31
31
  function decodeBase64(value, label, maxLength) {
32
32
  if (typeof value !== 'string' || value.length === 0 || value.length > maxLength || !BASE64_PATTERN.test(value)) {
@@ -4,6 +4,12 @@ export declare class CosignVerificationError extends Error {
4
4
  readonly exitCode = 1;
5
5
  constructor(message?: string);
6
6
  }
7
+ /**
8
+ * The environment for a verification: without the variables cosign and its libraries read as configuration
9
+ * (COSIGN_*, SIGSTORE_*, TUF_*), which can replace the trust material or relax checks. Signing keeps them: it needs the
10
+ * caller's identity token.
11
+ */
12
+ export declare function verificationEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
7
13
  export declare function assertPinnedCosignBinary(binaryPath: string): Promise<string>;
8
14
  export declare function buildCosignSignArgs(bundlePath: string, payloadPath: string): string[];
9
15
  export declare function buildCosignVerifyArgs(bundlePath: string, trustedRootPath: string, identity: string, issuer: string, payloadPath: string): string[];
@@ -66,10 +66,18 @@ async function hashFile(filePath) {
66
66
  await handle.close();
67
67
  }
68
68
  }
69
- async function runProcess(binaryPath, args, timeout) {
69
+ /**
70
+ * The environment for a verification: without the variables cosign and its libraries read as configuration
71
+ * (COSIGN_*, SIGSTORE_*, TUF_*), which can replace the trust material or relax checks. Signing keeps them: it needs the
72
+ * caller's identity token.
73
+ */
74
+ export function verificationEnv(env) {
75
+ return Object.fromEntries(Object.entries(env).filter(([name]) => !/^(COSIGN|SIGSTORE|TUF)_/iu.test(name)));
76
+ }
77
+ async function runProcess(binaryPath, args, timeout, env = process.env) {
70
78
  try {
71
79
  const { stdout, stderr } = await execFileAsync(binaryPath, args, {
72
- timeout, maxBuffer: 1024 * 1024, windowsHide: true, encoding: 'utf8', shell: false, env: process.env,
80
+ timeout, maxBuffer: 1024 * 1024, windowsHide: true, encoding: 'utf8', shell: false, env,
73
81
  });
74
82
  return { stdout, stderr };
75
83
  }
@@ -114,9 +122,9 @@ export function buildCosignVerifyArgs(bundlePath, trustedRootPath, identity, iss
114
122
  '--certificate-identity', identity, '--certificate-oidc-issuer', issuer, payloadPath,
115
123
  ];
116
124
  }
117
- async function runCosign(binaryPath, args, timeout) {
125
+ async function runCosign(binaryPath, args, timeout, env) {
118
126
  const canonical = await assertPinnedCosignBinary(binaryPath);
119
- await runProcess(canonical, args, timeout);
127
+ await runProcess(canonical, args, timeout, env);
120
128
  if (await hashFile(canonical) !== COSIGN_BINARY_SHA256[platformKey()]) {
121
129
  throw new CosignVerificationError('Pinned Cosign binary changed during the operation');
122
130
  }
@@ -148,6 +156,6 @@ export async function verifySigstoreBlob(options) {
148
156
  throw new Error('A configured Sigstore certificate identity is required');
149
157
  if (!options.certificateOidcIssuer)
150
158
  throw new Error('A configured Sigstore OIDC issuer is required');
151
- await runCosign(options.binaryPath, buildCosignVerifyArgs(bundle, trustedRoot, options.certificateIdentity, options.certificateOidcIssuer, payload), 60_000);
159
+ await runCosign(options.binaryPath, buildCosignVerifyArgs(bundle, trustedRoot, options.certificateIdentity, options.certificateOidcIssuer, payload), 60_000, verificationEnv(process.env));
152
160
  return { valid: true };
153
161
  }
@@ -9,7 +9,7 @@
9
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
10
  // is bash. Same-UID ptrace of the hook or host also stays an endpoint requirement.
11
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
12
+ const SAFE_PATH = /^\/[A-Za-z0-9._/@-]+$/u; // the command is parsed by a shell: no spaces, quotes or metacharacters
13
13
  export function claudeCodeManagedSettings(input) {
14
14
  const { mode, nodePath, hookEntry, configPath, hookTimeoutSec, selfDeadlineMs } = input;
15
15
  const envPath = input.envPath ?? '/usr/bin/env';
@@ -47,6 +47,7 @@ export async function loadConfig(file, rootUid = 0, extraKeys = []) {
47
47
  const st = await lstat(file);
48
48
  if (!st.isFile() || (st.mode & 0o022) !== 0 || st.uid !== rootUid)
49
49
  throw new Error('config must be a regular, root-owned, non-writable file');
50
+ // nosemgrep: mago-no-raw-read-of-signed-input -- the hook config, checked just above as a root-owned regular file that only root can write
50
51
  const raw = parseStrictJson(await readFile(file));
51
52
  if (!isRecord(raw))
52
53
  throw new Error('config must be an object');