@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
@@ -0,0 +1 @@
1
+ export declare function plainNameLine(bytes: Uint8Array): string | null;
@@ -0,0 +1,56 @@
1
+ // `plainNameLine`: the whitelist that decides whether mago-ski can name a Codex Skill from its SKILL.md without a YAML parser
2
+ // (design docs/design/codex-profile.md D4, E5, F6.5). It returns the `name:` value only when the file is in a tiny, unambiguous
3
+ // subset of the frontmatter syntax, in which Codex's own parser (parse_skill_frontmatter_metadata, skills/src/parser.rs,
4
+ // rust-v0.166.0) is known to give the same name. Anything else returns null. Refusing is always allowed; accepting a file whose
5
+ // Codex name differs is never allowed. The oracle test (tests/gate-codex-names.test.ts, tests/fixtures/codex-names/) pins it.
6
+ import { validateSkillName } from "../../names.js";
7
+ const decoder = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true });
8
+ const KEY_LINE = /^([a-z][a-z0-9_-]*): ([A-Za-z0-9 ._/,()-]*)$/u;
9
+ const NAME_VALUE = /^[A-Za-z][A-Za-z0-9._-]*$/u;
10
+ const RESERVED = new Set(['null', '~', 'true', 'false', 'yes', 'no', 'on', 'off', 'y', 'n']);
11
+ export function plainNameLine(bytes) {
12
+ let text;
13
+ try {
14
+ text = decoder.decode(bytes);
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ if (text.charCodeAt(0) === 0xfeff)
20
+ return null;
21
+ const lines = text.split('\n').map((l) => (l.endsWith('\r') ? l.slice(0, -1) : l));
22
+ if (lines[0] !== '---')
23
+ return null;
24
+ const end = lines.indexOf('---', 1);
25
+ if (end < 0)
26
+ return null;
27
+ const seen = new Map();
28
+ for (const line of lines.slice(1, end)) {
29
+ if (line === '')
30
+ continue;
31
+ if (/[^\x20-\x7e]/u.test(line))
32
+ return null; // non-ASCII, tab, a bare \r or any control byte
33
+ const m = KEY_LINE.exec(line);
34
+ if (!m)
35
+ return null;
36
+ const [, key, value] = m;
37
+ if (seen.has(key))
38
+ return null; // a duplicate key of any kind
39
+ seen.set(key, value);
40
+ }
41
+ const name = seen.get('name');
42
+ const description = seen.get('description');
43
+ if (name === undefined || description === undefined)
44
+ return null;
45
+ if (!NAME_VALUE.test(name) || RESERVED.has(name.toLowerCase()))
46
+ return null;
47
+ try {
48
+ validateSkillName(name);
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ if (description.trim() === '' || RESERVED.has(description.trim().toLowerCase()))
54
+ return null;
55
+ return name;
56
+ }
@@ -17,3 +17,14 @@ export interface CodexRequirementsInput {
17
17
  userSkillRoots: string[];
18
18
  }
19
19
  export declare function codexRequirementsToml(input: CodexRequirementsInput): string;
20
+ /**
21
+ * /etc/codex/managed_config.toml (codex-profile.md C1): the managed config outranks user config, project config, profiles and
22
+ * `-c`. It removes Skill sources and keeps Skill descriptions out of the prompt; nothing here blocks by itself, so shadow mode
23
+ * gets the same file. Takes no input. Keys (research spike, codex-cli rust-v0.166.0 / Linux):
24
+ * project_root_markers = [] the repo Skill scan covers the working directory only (a repo .codex/config.toml is not loaded
25
+ * when Codex starts in a subdirectory);
26
+ * [skills] include_instructions = false Skill descriptions are not injected;
27
+ * [skills.bundled] enabled = false no bundled .system Skills;
28
+ * [cloud.skills] enabled = false no cloud Skills.
29
+ */
30
+ export declare function codexManagedConfigToml(): string;
@@ -1,29 +1,24 @@
1
- // Generator of /etc/codex/requirements.toml for the Codex hook adapter. Pure: no file access.
2
- // EVIDENCE: every setting marked [cx0.1]/[cx0.2] was exercised on codex-cli 0.163.0 / Linux (.agent/reviews/
3
- // cx0.1-codex-surface-spike.md and its cx0.2 addendum, cx0.1-fixtures/evidence.txt, cx0.2-evidence.txt). Unverified for
4
- // other Codex versions; not a broad host-level guarantee.
1
+ // Generators of the two Codex managed files: /etc/codex/requirements.toml (codexRequirementsToml) and
2
+ // /etc/codex/managed_config.toml (codexManagedConfigToml). Pure: no file access. Design: docs/design/codex-profile.md (C1, C6).
3
+ // EVIDENCE: the keys marked [cx0.1]/[cx0.2] were exercised on codex-cli 0.163.0 / Linux (.agent/reviews/cx0.1-codex-surface-spike.md and
4
+ // its cx0.2 addendum); the managed_config.toml keys and the two executor feature pins come from the research spike against Codex
5
+ // rust-v0.166.0 (docs/spikes/codex-full-research.md). Unverified for other Codex versions; not a broad host-level guarantee.
5
6
  //
6
- // KNOWN GAPS (also written into the generated header):
7
- // * Repo-scope Skills (<repo>/.codex/skills, .agents/skills) cannot be hidden natively: hook-only, best-effort,
8
- // audit-level. Codex hooks also fail OPEN on crash/timeout, so the hook is not a lock; the lock is deny_read plus
9
- // uninstall-on-revoke.
10
- // * deny_read does NOT hide the user roots from Codex's Skill catalog: in the live test (codex-cli 0.163.0 and 0.166.0,
11
- // as root and as an unprivileged user with bwrap; docs/spikes/codex-gate-live.md) a Skill under a denied root was
12
- // still listed with its path. Using it is blocked by the hook only, so the user route is hook-only like the repo route.
7
+ // WHAT THE PROFILE LEAVES TO THE ORGANISATION (also written into the generated header):
8
+ // * A Skill picked from Codex's menu, or sent as structured input (UserInput::Skill) by an IDE or app-server client, reaches the
9
+ // model with no hook involved. The control is that no non-admin Skill is LISTED (`gate doctor` FAILs when a listed home has
10
+ // one; the GitHub Action checks repositories; optional `--lock-user-skill-folders`). Detected, not prevented.
11
+ // * Hooks fail OPEN when the hook process crashes, times out or is killed (a hook that runs but cannot reach the service blocks).
12
+ // * Repo-scope Skills (<repo>/.codex/skills, .agents/skills) cannot be hidden natively.
13
+ // * deny_read blocks sandboxed shell reads of the listed user roots; it does NOT hide them from the Skill catalog and does not
14
+ // stop mention injection (live test, codex-cli 0.163.0 and 0.166.0).
13
15
  // * deny_read works only for the fixed absolute roots listed in `userSkillRoots` (not for ** or /home/* globs, cx0.2).
14
- // * Codex's sandbox needs unprivileged user namespaces, so the max_user_namespaces=0 hardening used for Claude Code
15
- // breaks Codex (cx0.2: bwrap ENOSPC). Packet 10 resolves this.
16
- // * The hook adapter finds the employee's user roots itself from the host's CODEX_HOME/HOME (read from /proc/<host pid>/
17
- // environ); the roots below only feed the native deny_read. The adapter scans every cwd ancestor for repo roots.
18
- // * Not gateable by the UserPromptSubmit hook: structured Skill selection (UserInput::Skill, skill:// mentions from
19
- // non-TUI clients or the app-server API) and app-server `skills/extraRoots/set`. Endpoint requirement: restrict
20
- // app-server and non-TUI Codex clients. A token split across text items can differ from what the hook sees; the
21
- // PreToolUse shell check is best-effort. In enforce, Codex coverage is weaker than Claude Code; the live test confirmed
22
- // that the repo and user routes are audit-level.
23
- // * Startup state: Codex fixes HOME, CODEX_HOME and ~/.codex/.env at startup; the hook sees only the current state, so
24
- // an employee can start Codex pointed at other Skills and undo it (accepted limit; needs an admin-owned CODEX_HOME).
16
+ // * Codex's sandbox needs unprivileged user namespaces, so the max_user_namespaces=0 hardening used for Claude Code breaks it.
17
+ // * The hook adapter finds the employee's user roots itself from the host's CODEX_HOME/HOME; a HOME or CODEX_HOME that the
18
+ // instance does not list makes bare mentions blocked.
19
+ // * Startup state: Codex fixes HOME, CODEX_HOME and <codex_home>/.env at startup (needs an admin-owned CODEX_HOME).
25
20
  import path from 'node:path';
26
- const SAFE_PATH = /^\/[A-Za-z0-9._/-]+$/u; // also valid inside a TOML basic string and a shell command: nothing to escape
21
+ const SAFE_PATH = /^\/[A-Za-z0-9._/@-]+$/u; // also valid inside a TOML basic string and a shell command: nothing to escape
27
22
  const q = (s) => `"${s}"`;
28
23
  export function codexRequirementsToml(input) {
29
24
  const { mode, nodePath, hookEntry, configPath, hookTimeoutSec, selfDeadlineMs, userSkillRoots } = input;
@@ -39,18 +34,50 @@ export function codexRequirementsToml(input) {
39
34
  throw new Error('hookTimeoutSec * 1000 must be at least selfDeadlineMs + 1000');
40
35
  const command = q(`${envPath} -i ${nodePath} --no-addons ${hookEntry} ${configPath} ${mode}`); // env -i: no NODE_OPTIONS etc.
41
36
  const lines = [
42
- '# mago-ski Codex requirements (generated). Evidence: codex-cli 0.163.0 / Linux only; unverified for other versions.',
43
- '# Known gaps: repo-scope Skills cannot be hidden in Codex (hook-only, best-effort, audit-level); deny_read covers only',
44
- '# the fixed roots listed below; hooks fail OPEN on crash/timeout; Codex sandboxing needs unprivileged user namespaces,',
45
- '# so max_user_namespaces=0 (used for Claude Code) breaks it.',
37
+ '# mago-ski Codex requirements (generated). Evidence: codex-cli 0.163.0 and 0.166.0 / Linux; unverified for other versions.',
38
+ '# Limits: a Skill picked from the menu or sent by an IDE/app-server client reaches the model with no hook (detected by',
39
+ '# gate doctor, not prevented); hooks fail OPEN when the hook process crashes, times out or is killed;',
40
+ '# repo-scope Skills cannot be hidden; deny_read covers only the fixed roots listed below; Codex sandboxing needs',
41
+ '# unprivileged user namespaces, so max_user_namespaces=0 (used for Claude Code) breaks it.',
46
42
  ];
47
43
  if (mode === 'enforce') {
48
- lines.push('# [cx0.1] managed hooks only: user/repo/project hooks are ignored.', 'allow_managed_hooks_only = true', '# [cx0.2] keeps the sandbox on; no danger-full-access.', 'allowed_sandbox_modes = ["read-only", "workspace-write"]', '', '# [cx0.2] feature pins: hooks on; plugins, remote plugins and apps off.', '[features]', 'hooks = true', 'plugins = false', 'remote_plugin = false', 'apps = false');
44
+ lines.push('# [cx0.1] managed hooks only: user/repo/project hooks are ignored.', 'allow_managed_hooks_only = true', '# [cx0.2] keeps the sandbox on; no danger-full-access.', 'allowed_sandbox_modes = ["read-only", "workspace-write"]', '', '# [cx0.2] feature pins: hooks on; plugins, remote plugins, apps and executor capability discovery off.', '[features]', 'hooks = true', 'plugins = false', 'remote_plugin = false', 'apps = false', 'executor_capability_discovery = false', 'executor_capability_discovery_v2 = false');
49
45
  if (userSkillRoots.length > 0)
50
- lines.push('', '# [cx0.2] meant to block sandboxed reads of these fixed user roots. It does NOT hide them from the Skill catalog', '# (live test, codex-cli 0.163.0 and 0.166.0); their use is blocked by the hooks only.', '[permissions.filesystem]', `deny_read = [${userSkillRoots.map((r) => q(`${r}/**`)).join(', ')}]`);
46
+ lines.push('', '# [cx0.2] blocks sandboxed shell reads of these fixed user roots. It does NOT hide them from the Skill catalog and does not', '# stop mention injection (live test, codex-cli 0.163.0 and 0.166.0); typed use is blocked by the hooks.', '[permissions.filesystem]', `deny_read = [${userSkillRoots.map((r) => q(`${r}/**`)).join(', ')}]`);
51
47
  }
52
48
  lines.push('', '# [cx0.1] managed hooks; Codex needs managed_dir (without it the hooks are ignored).', '[hooks]', `managed_dir = ${q(path.dirname(hookEntry))}`);
53
49
  for (const [event, matcher] of [['SessionStart', false], ['UserPromptSubmit', false], ['PreToolUse', true]])
54
50
  lines.push('', `[[hooks.${event}]]`, ...(matcher ? ['matcher = "*"'] : []), `[[hooks.${event}.hooks]]`, 'type = "command"', `command = ${command}`, `timeout = ${hookTimeoutSec}`);
55
51
  return `${lines.join('\n')}\n`;
56
52
  }
53
+ /**
54
+ * /etc/codex/managed_config.toml (codex-profile.md C1): the managed config outranks user config, project config, profiles and
55
+ * `-c`. It removes Skill sources and keeps Skill descriptions out of the prompt; nothing here blocks by itself, so shadow mode
56
+ * gets the same file. Takes no input. Keys (research spike, codex-cli rust-v0.166.0 / Linux):
57
+ * project_root_markers = [] the repo Skill scan covers the working directory only (a repo .codex/config.toml is not loaded
58
+ * when Codex starts in a subdirectory);
59
+ * [skills] include_instructions = false Skill descriptions are not injected;
60
+ * [skills.bundled] enabled = false no bundled .system Skills;
61
+ * [cloud.skills] enabled = false no cloud Skills.
62
+ */
63
+ export function codexManagedConfigToml() {
64
+ return [
65
+ '# mago-ski Codex profile (generated). Evidence: codex-cli 0.166.0 / Linux.',
66
+ '# Outranks user config, project config, profiles and -c. It removes Skill sources; it does not block by itself.',
67
+ '# project_root_markers = []: the repo Skill scan covers the working directory only.',
68
+ 'project_root_markers = []',
69
+ '',
70
+ '# Skill descriptions are not injected into the prompt.',
71
+ '[skills]',
72
+ 'include_instructions = false',
73
+ '',
74
+ '# No bundled (.system) Skills.',
75
+ '[skills.bundled]',
76
+ 'enabled = false',
77
+ '',
78
+ '# No cloud Skills.',
79
+ '[cloud.skills]',
80
+ 'enabled = false',
81
+ '',
82
+ ].join('\n');
83
+ }
@@ -1,5 +1,8 @@
1
1
  import { type HookDeps, type HookOutcome } from './claude-code.ts';
2
2
  export declare const DEFAULT_ADMIN_ROOT = "/etc/codex/skills";
3
+ export declare const REMOVED_NAMES_FILE = ".mago-ski-removed-names.json";
4
+ export declare const REMOVED_NAMES_TYPE = "mago-ski.gate.removed-names.v1";
5
+ export declare const MAX_REMOVED_NAMES = 4096;
3
6
  export declare function extractMentions(text: string, links?: string[], plain?: Set<string>, linkNames?: string[]): Set<string>;
4
7
  /** What the adapter learns of the host's environment (values are never logged). */
5
8
  export interface HostEnv {
@@ -74,10 +74,12 @@
74
74
  import { lstat, open, readdir, readFile, realpath, stat } from 'node:fs/promises';
75
75
  import path from 'node:path';
76
76
  import { isRecord } from "../../canonical-json.js";
77
+ import { readRegularFile } from "../../fs-safe.js";
77
78
  import { validateSkillName } from "../../names.js";
78
79
  import { decideAction } from "../contract.js";
79
80
  import { parseStrictJson } from "../strict-json.js";
80
81
  import { askService, newRequestId } from "./client.js";
82
+ import { plainNameLine } from "./codex-names.js";
81
83
  import { loadConfig, MAX_STDIN_BYTES } from "./claude-code.js";
82
84
  import { findHostPid } from "./host-pid.js";
83
85
  const DEFAULT_SELF_DEADLINE_MS = 3000;
@@ -86,6 +88,12 @@ export const DEFAULT_ADMIN_ROOT = '/etc/codex/skills';
86
88
  const MAX_ANCESTORS = 64;
87
89
  const MAX_ADMIN_NAMES = 16;
88
90
  const MAX_ENVIRON_BYTES = 256 * 1024;
91
+ const MAX_SKILL_MD_BYTES = 64 * 1024;
92
+ export const REMOVED_NAMES_FILE = '.mago-ski-removed-names.json';
93
+ export const REMOVED_NAMES_TYPE = 'mago-ski.gate.removed-names.v1';
94
+ export const MAX_REMOVED_NAMES = 4096;
95
+ const MAX_REMOVED_BYTES = 1024 * 1024;
96
+ const REMOVED_LIMITS = { maxBytes: MAX_REMOVED_BYTES, maxDepth: 4, maxMembers: MAX_REMOVED_NAMES + 4, maxStringLength: 1024 };
89
97
  const COULD_NOT_VERIFY = 'mago-ski could not verify this Skill; it is blocked until verification works.';
90
98
  const MASKED = 'A Skill with this name also exists outside your organisation\'s approved Skills, so a plain mention is blocked. Mention the approved Skill by its link, or remove the other Skill.';
91
99
  const notAdmin = (adminRoot) => `This Skill is not one of your organisation's approved Skills, so it is blocked. Approved Skills are installed in ${adminRoot}.`;
@@ -227,8 +235,8 @@ async function scanRoot(root, scan) {
227
235
  scan.incomplete = true;
228
236
  continue;
229
237
  } // a dangling link is ignored, as in Codex
230
- if (!isDir || name.startsWith('.') || depth >= MAX_SCAN_DEPTH)
231
- continue;
238
+ if (!isDir || depth >= MAX_SCAN_DEPTH)
239
+ continue; // dot-prefixed folders are entered too (F7.5: fail closed until a live run shows Codex skips them)
232
240
  try {
233
241
  const r = await realpath(p);
234
242
  if (r.includes('\uFFFD')) {
@@ -297,16 +305,97 @@ async function dotenvMayMoveHome(codexHome) {
297
305
  const st = await lstat(file);
298
306
  if (!st.isFile() || st.size > MAX_ENVIRON_BYTES)
299
307
  return true; // symlink, FIFO, directory, huge: not inspected
308
+ // nosemgrep: mago-no-raw-read-of-signed-input -- /proc/<pid>/environ of the host process, size checked above; only searched for HOME
300
309
  return (await readFile(file)).includes('HOME');
301
310
  }
302
311
  catch (e) {
303
312
  return e.code !== 'ENOENT';
304
313
  }
305
314
  }
315
+ /** Keys every admin entry under the names Codex can give it (D2, E4). Any problem sets `incomplete`. */
316
+ async function keyAdmin(adminRoot, adminReal, scan) {
317
+ const admin = new Map();
318
+ const files = new Map();
319
+ const entries = (await listRoot(adminRoot)).filter((e) => !e.startsWith('.')).sort();
320
+ for (const e of entries) { // directory names first: they win a collision
321
+ const k = e.toLowerCase();
322
+ if (admin.has(k))
323
+ scan.incomplete = true;
324
+ else
325
+ admin.set(k, e);
326
+ }
327
+ for (const e of entries) {
328
+ let real;
329
+ try {
330
+ real = await realpath(path.join(adminRoot, e));
331
+ }
332
+ catch {
333
+ scan.incomplete = true;
334
+ continue;
335
+ }
336
+ try {
337
+ files.set(e, await realpath(path.join(real, 'SKILL.md')));
338
+ }
339
+ catch {
340
+ scan.incomplete = true;
341
+ }
342
+ const keys = [path.basename(real).toLowerCase()];
343
+ try {
344
+ const name = plainNameLine(await readRegularFile(path.join(real, 'SKILL.md'), 'SKILL.md', MAX_SKILL_MD_BYTES));
345
+ if (name === null)
346
+ scan.incomplete = true;
347
+ else
348
+ keys.push(name.toLowerCase());
349
+ }
350
+ catch {
351
+ scan.incomplete = true;
352
+ }
353
+ for (const k of keys) {
354
+ const have = admin.get(k);
355
+ if (have === undefined)
356
+ admin.set(k, e);
357
+ else if (have !== e)
358
+ scan.incomplete = true; // two admin entries claim one name
359
+ }
360
+ }
361
+ void adminReal;
362
+ return { admin, files };
363
+ }
364
+ /** The removed-names file in the admin root (D7). Missing = empty; unreadable or malformed = incomplete. */
365
+ async function readRemoved(adminRoot, scan) {
366
+ const out = new Set();
367
+ const file = path.join(adminRoot, REMOVED_NAMES_FILE);
368
+ let bytes;
369
+ try {
370
+ bytes = await readRegularFile(file, 'removed names', MAX_REMOVED_BYTES);
371
+ }
372
+ catch (e) {
373
+ if (gone(e))
374
+ return out;
375
+ scan.incomplete = true;
376
+ return out;
377
+ }
378
+ try {
379
+ const raw = parseStrictJson(bytes, REMOVED_LIMITS);
380
+ if (!isRecord(raw) || raw['type'] !== REMOVED_NAMES_TYPE || !Array.isArray(raw['entries']) || raw['entries'].length > MAX_REMOVED_NAMES)
381
+ throw new Error('bad file');
382
+ for (const e of raw['entries']) {
383
+ if (!isRecord(e) || typeof e['name'] !== 'string' || typeof e['digest'] !== 'string')
384
+ throw new Error('bad entry');
385
+ out.add(e['name'].toLowerCase());
386
+ out.add(e['digest'].toLowerCase());
387
+ }
388
+ }
389
+ catch {
390
+ scan.incomplete = true;
391
+ }
392
+ return out;
393
+ }
306
394
  async function findSkills(cfg, cwd, env) {
307
395
  const scan = { found: false, realRoots: [], incomplete: false, dirs: 0 };
308
- const admin = new Map((await listRoot(cfg.adminRoot)).map((e) => [e.toLowerCase(), e]));
309
396
  const adminReal = await realpath(cfg.adminRoot).catch(() => undefined);
397
+ const { admin, files } = await keyAdmin(cfg.adminRoot, adminReal, scan);
398
+ const removed = await readRemoved(cfg.adminRoot, scan);
310
399
  const roots = new Set(cfg.skillRoots);
311
400
  // U+FFFD: Codex hands the hook a lossily decoded cwd, and environ is decoded here as UTF-8, so a non-UTF-8 path would be
312
401
  // scanned at a name that does not exist. Fail closed instead.
@@ -314,16 +403,21 @@ async function findSkills(cfg, cwd, env) {
314
403
  const absDir = (v) => usable(v) ? path.normalize(v).replace(/(?<=.)\/+$/u, '') : undefined;
315
404
  const home = absDir(env?.home);
316
405
  // Codex canonicalises a set CODEX_HOME (utils/home-dir find_codex_home), so `..` after a symlink resolves physically.
317
- const codexHome = env?.codexHome === undefined || env.codexHome === ''
406
+ const explicitHome = !(env?.codexHome === undefined || env.codexHome === '');
407
+ const codexHome = !explicitHome
318
408
  ? (home === undefined ? undefined : `${home}/.codex`)
319
409
  : usable(env.codexHome) ? await realpath(env.codexHome).then((r) => (usable(r) ? r : undefined), () => undefined) : undefined;
320
410
  if (env === undefined || home === undefined || codexHome === undefined)
321
411
  scan.incomplete = true; // fail closed
322
- else if (await dotenvMayMoveHome(codexHome))
323
- scan.incomplete = true;
324
- else
325
- for (const r of [`${codexHome}/skills`, `${codexHome}/skills/.system`, `${home}/.agents/skills`])
326
- roots.add(r);
412
+ else {
413
+ if (!(await homesListed(cfg, home, codexHome, explicitHome)))
414
+ scan.incomplete = true; // F4: not a home the profile covers
415
+ if (await dotenvMayMoveHome(codexHome))
416
+ scan.incomplete = true;
417
+ else
418
+ for (const r of [`${codexHome}/skills`, `${codexHome}/skills/.system`, `${home}/.agents/skills`])
419
+ roots.add(r);
420
+ }
327
421
  const validCwd = usable(cwd);
328
422
  if (!validCwd)
329
423
  scan.incomplete = true;
@@ -333,7 +427,25 @@ async function findSkills(cfg, cwd, env) {
333
427
  roots.add(path.join(d, sub));
334
428
  for (const r of roots)
335
429
  await scanRoot(r, scan);
336
- return { admin, adminReal, anySkill: scan.found, roots: [...roots, ...scan.realRoots], incomplete: scan.incomplete, cwd: validCwd ? cwd : undefined };
430
+ return { admin, adminFiles: files, removed, adminReal, anySkill: scan.found, roots: [...roots, ...scan.realRoots], incomplete: scan.incomplete, cwd: validCwd ? cwd : undefined };
431
+ }
432
+ /** F4: with `user_homes` configured, the host's HOME must be listed, and its CODEX_HOME must be `<home>/.codex` or listed. */
433
+ async function homesListed(cfg, home, codexHome, explicitHome) {
434
+ if (cfg.userHomes === undefined)
435
+ return true; // a config without the key (older or hand-written): not checked
436
+ const same = async (a, b) => path.normalize(a) === path.normalize(b) || (await realpath(a).catch(() => a)) === (await realpath(b).catch(() => b));
437
+ let homeOk = false;
438
+ for (const h of cfg.userHomes)
439
+ if (await same(h, home))
440
+ homeOk = true;
441
+ if (!homeOk)
442
+ return false;
443
+ if (!explicitHome || await same(codexHome, `${home}/.codex`))
444
+ return true;
445
+ for (const h of cfg.codexHomes ?? [])
446
+ if (await same(h, codexHome))
447
+ return true;
448
+ return false;
337
449
  }
338
450
  /**
339
451
  * The admin Skill (actual directory name) that a link `[$x](path)` resolves to by realpath, exactly `<admin>/<name>/SKILL.md`
@@ -350,10 +462,10 @@ async function adminLinkName(link, f) {
350
462
  return undefined;
351
463
  try {
352
464
  const real = await realpath(path.resolve(f.cwd ?? '/', stripped));
353
- // The service publishes each admin entry as a symlink to its generation (service.ts HOST-VISIBLE SKILLS), so the link
354
- // is compared with the resolved `<admin>/<name>/SKILL.md` of each admin entry, not with a path under the admin root.
355
- for (const name of f.admin.values())
356
- if (await realpath(path.join(f.adminReal, name, 'SKILL.md')).catch(() => undefined) === real)
465
+ // F3: the realpath of the linked file must be `<real of a CURRENT admin entry>/SKILL.md`. The service publishes each admin
466
+ // entry as a symlink to its generation, so another generation, an uninstalled Skill's generation or a hidden entry never match.
467
+ for (const [name, file] of f.adminFiles)
468
+ if (file === real)
357
469
  return name;
358
470
  return undefined;
359
471
  }
@@ -383,7 +495,9 @@ function inspectCommand(raw, cfg) {
383
495
  // Any mention of a user/repo Skill location in any spelling (~, $HOME, relative), or of a SKILL.md file other than an
384
496
  // admin Skill's own `<admin_root>/<name>/SKILL.md`.
385
497
  const start = '(?<=^|[\\s\'"`=;|&()<>])'; // the admin path must start a word: `<other>/<admin>/x/SKILL.md` is not admin
386
- const outsideAdmin = command.replace(new RegExp(`${start}${esc}/[A-Za-z0-9][A-Za-z0-9._-]*/SKILL\\.md`, 'giu'), '');
498
+ // Case-sensitive, like the admin-name match below: a spelling such as `<admin_root>` in another case is a different path.
499
+ // It must not be removed here (it would then be neither rogue nor checked by the gate).
500
+ const outsideAdmin = command.replace(new RegExp(`${start}${esc}/[A-Za-z0-9][A-Za-z0-9._-]*/SKILL\\.md`, 'gu'), '');
387
501
  const rogue = /\.(agents|codex)(?![A-Za-z0-9_-])/u.test(command) || /skill\.md/iu.test(outsideAdmin)
388
502
  || cfg.skillRoots.some((r) => command.includes(collapse(r)));
389
503
  const admin = new Set();
@@ -397,12 +511,19 @@ function inspectCommand(raw, cfg) {
397
511
  return { rogue, admin: [...admin] };
398
512
  }
399
513
  async function loadCodexConfig(file, uid) {
400
- const cfg = await loadConfig(file, uid, ['admin_root', 'skill_roots']);
401
- const { admin_root: admin = DEFAULT_ADMIN_ROOT, skill_roots: roots = [] } = cfg.raw;
514
+ const cfg = await loadConfig(file, uid, ['admin_root', 'skill_roots', 'user_homes', 'codex_homes']);
515
+ const { admin_root: admin = DEFAULT_ADMIN_ROOT, skill_roots: roots = [], user_homes: homes, codex_homes: cHomes } = cfg.raw;
402
516
  const abs = (v) => typeof v === 'string' && path.isAbsolute(v) && !v.includes('\0');
403
517
  if (!abs(admin) || !Array.isArray(roots) || roots.length > 64 || !roots.every(abs))
404
518
  throw new Error('bad Skill roots');
405
- return { ...cfg, adminRoot: admin.replace(/\/+$/u, ''), skillRoots: roots.map((r) => r.replace(/\/+$/u, '')) };
519
+ const list = (v) => {
520
+ if (v === undefined)
521
+ return undefined;
522
+ if (!Array.isArray(v) || v.length > 256 || !v.every(abs))
523
+ throw new Error('bad home list');
524
+ return v.map((r) => r.replace(/(?<=.)\/+$/u, ''));
525
+ };
526
+ return { ...cfg, adminRoot: admin.replace(/\/+$/u, ''), skillRoots: roots.map((r) => r.replace(/\/+$/u, '')), userHomes: list(homes), codexHomes: list(cHomes) };
406
527
  }
407
528
  function parseHookInput(bytes, peek) {
408
529
  const raw = parseStrictJson(bytes, INPUT_LIMITS);
@@ -495,8 +616,8 @@ async function runHookInner(argv, deps, setMode) {
495
616
  continue; // L1 (exact lower-case schemes, as Codex matches them)
496
617
  const a = await adminLinkName(l, f);
497
618
  // L2 also needs the link text to name that same admin Skill; `[$rogue](<admin>/alpha/SKILL.md)` is L3.
498
- const text = linkNames[i] ?? '';
499
- if (a === undefined || text.toLowerCase() !== a.toLowerCase()) {
619
+ const text = (linkNames[i] ?? '').toLowerCase();
620
+ if (a === undefined || f.admin.get(text) !== a) {
500
621
  if (mode === 'enforce')
501
622
  return block(notAdmin(cfg.adminRoot)); // L3
502
623
  continue;
@@ -511,6 +632,12 @@ async function runHookInner(argv, deps, setMode) {
511
632
  continue;
512
633
  }
513
634
  const adminName = f.admin.get(n.toLowerCase());
635
+ // C2.2: a removed name (or digest) that is no current admin key is never asked.
636
+ if (adminName === undefined && f.removed.has(n.toLowerCase())) {
637
+ if (mode === 'enforce')
638
+ return block(notAdmin(cfg.adminRoot));
639
+ continue;
640
+ }
514
641
  if (adminName === undefined && !wide)
515
642
  continue; // T6
516
643
  // T2: under wide, an admin name may really select a same-name repo/user Skill.
@@ -0,0 +1,19 @@
1
+ /** The service's admin processing deadline is 60 s; the client waits a little longer (design G10). */
2
+ export declare const ADMIN_DEADLINE_MS = 65000;
3
+ export type AdminReply = {
4
+ v: 1;
5
+ ok: true;
6
+ [key: string]: unknown;
7
+ } | {
8
+ v: 1;
9
+ ok: false;
10
+ error: string;
11
+ };
12
+ export type AskAdmin = (socketPath: string, command: Record<string, unknown>, deadlineMs?: number) => Promise<AdminReply>;
13
+ export declare const TIMEOUT_MESSAGE = "the gate did not answer in time; run mago-ski gate status";
14
+ export declare const askAdmin: AskAdmin;
15
+ /**
16
+ * Before connecting: the admin socket's folder is a real folder owned by `uid` with mode 0700, and the socket in it is a
17
+ * socket owned by `uid`. A folder or socket someone else could replace is not trusted with a trust root or a Skill.
18
+ */
19
+ export declare function checkAdminSocket(adminDir: string, uid: number): Promise<void>;
@@ -0,0 +1,62 @@
1
+ // Client of the gate service's admin socket: one JSON request line out, one JSON reply line back (mirrors `serveOnce`
2
+ // in service.ts). Transport problems throw; an `ok: false` reply is returned as data.
3
+ import { lstat } from 'node:fs/promises';
4
+ import net from 'node:net';
5
+ import path from 'node:path';
6
+ import { parseStrictJson } from "./strict-json.js";
7
+ /** The service's admin processing deadline is 60 s; the client waits a little longer (design G10). */
8
+ export const ADMIN_DEADLINE_MS = 65_000;
9
+ const MAX_REPLY_BYTES = 1024 * 1024;
10
+ export const TIMEOUT_MESSAGE = 'the gate did not answer in time; run mago-ski gate status';
11
+ export const askAdmin = (socketPath, command, deadlineMs = ADMIN_DEADLINE_MS) => new Promise((resolve, reject) => {
12
+ const sock = net.connect(socketPath);
13
+ const chunks = [];
14
+ let size = 0;
15
+ let settled = false;
16
+ const finish = (fn) => { if (settled)
17
+ return; settled = true; clearTimeout(timer); sock.destroy(); fn(); };
18
+ const timer = setTimeout(() => finish(() => reject(new Error(TIMEOUT_MESSAGE))), deadlineMs);
19
+ sock.on('error', (e) => finish(() => reject(new Error(e.code === 'ENOENT' || e.code === 'ECONNREFUSED' ? `cannot reach the gate at ${socketPath} (${e.code}); is the service running?`
20
+ : e.code === 'EACCES' ? `cannot open ${socketPath}: permission denied (the admin socket is for root)` : `gate socket error: ${e.message}`))));
21
+ sock.on('connect', () => sock.write(`${JSON.stringify({ v: 1, ...command })}\n`));
22
+ sock.on('data', (chunk) => {
23
+ const nl = chunk.indexOf(0x0a);
24
+ size += nl < 0 ? chunk.length : nl;
25
+ if (size > MAX_REPLY_BYTES)
26
+ return finish(() => reject(new Error('the gate reply is too large')));
27
+ chunks.push(nl < 0 ? chunk : chunk.subarray(0, nl));
28
+ if (nl < 0)
29
+ return;
30
+ finish(() => {
31
+ try {
32
+ const bytes = Buffer.concat(chunks);
33
+ parseStrictJson(bytes, { maxBytes: MAX_REPLY_BYTES, maxDepth: 16, maxMembers: 256, maxStringLength: MAX_REPLY_BYTES }); // duplicate keys, depth
34
+ const reply = JSON.parse(bytes.toString('utf8')); // the same text, as ordinary objects
35
+ if (typeof reply !== 'object' || reply === null || typeof reply.ok !== 'boolean')
36
+ throw new Error('shape');
37
+ resolve(reply);
38
+ }
39
+ catch {
40
+ reject(new Error('the gate sent a reply that is not valid JSON'));
41
+ }
42
+ });
43
+ });
44
+ sock.on('close', () => finish(() => reject(new Error('the gate closed the connection without a reply'))));
45
+ });
46
+ /**
47
+ * Before connecting: the admin socket's folder is a real folder owned by `uid` with mode 0700, and the socket in it is a
48
+ * socket owned by `uid`. A folder or socket someone else could replace is not trusted with a trust root or a Skill.
49
+ */
50
+ export async function checkAdminSocket(adminDir, uid) {
51
+ const dir = await lstat(adminDir).catch((e) => { throw new Error(`cannot reach the gate: ${adminDir}: ${e.code ?? 'error'}; is the service running?`); });
52
+ if (dir.isSymbolicLink() || !dir.isDirectory())
53
+ throw new Error(`${adminDir} must be a real folder`);
54
+ if (dir.uid !== uid || (dir.mode & 0o777) !== 0o700)
55
+ throw new Error(`${adminDir} must be owned by root with mode 0700; the admin socket is not trusted`);
56
+ const sock = path.join(adminDir, 'admin.sock');
57
+ const info = await lstat(sock).catch((e) => { throw new Error(`cannot reach the gate: ${sock}: ${e.code ?? 'error'}; is the service running?`); });
58
+ if (!info.isSocket())
59
+ throw new Error(`${sock} is not a socket; the admin socket is not trusted`);
60
+ if (info.uid !== uid)
61
+ throw new Error(`${sock} must be owned by root; the admin socket is not trusted`);
62
+ }
@@ -437,10 +437,12 @@ export async function readGeneration(generationsRoot, name, digest) {
437
437
  async function seal(dir, files) {
438
438
  const dirs = new Set(['']);
439
439
  for (const f of files) {
440
+ // nosemgrep: mago-no-path-chown-chmod -- sealing a generation inside the service's root-owned generation store; no user can write there
440
441
  await chmod(path.join(dir, f.path), f.exec ? 0o555 : 0o444);
441
442
  for (let d = path.posix.dirname(f.path); d !== '.'; d = path.posix.dirname(d))
442
443
  dirs.add(d);
443
444
  }
445
+ // nosemgrep: mago-no-path-chown-chmod -- sealing a generation inside the service's root-owned generation store; no user can write there
444
446
  for (const d of [...dirs].sort((a, b) => b.length - a.length))
445
447
  await chmod(path.join(dir, d), 0o555);
446
448
  }
@@ -0,0 +1,57 @@
1
+ import type { Mode } from '../policy.ts';
2
+ import type { GateServiceConfig } from './service.ts';
3
+ export declare const HOSTS: readonly ["claude-code", "codex"];
4
+ export type Host = (typeof HOSTS)[number];
5
+ export declare const isHost: (value: unknown) => value is Host;
6
+ /** The instance config file (canonical JSON), exactly these keys. */
7
+ export interface InstanceConfig {
8
+ v: 1;
9
+ host: Host;
10
+ mode: Mode;
11
+ root_fingerprint: string;
12
+ host_exes: string[];
13
+ state_dir: string;
14
+ generations_dir: string;
15
+ managed_dir: string;
16
+ /** Holds `decision.sock`; the unit's RuntimeDirectory (systemd creates it). */
17
+ decision_socket_dir: string;
18
+ /** Holds `admin.sock`; `start()` creates it at 0700. */
19
+ admin_socket_dir: string;
20
+ inbox_dir: string | null;
21
+ build_id: string;
22
+ }
23
+ export interface InstancePaths {
24
+ /** `<base>/etc/mago-ski/gate` */
25
+ configDir: string;
26
+ instance: string;
27
+ hook: string;
28
+ manifest: string;
29
+ sharedManifest: string;
30
+ /** `<base>/var/lib/mago-ski/gate/<host>`, the parent of the state and generations folders. */
31
+ stateRoot: string;
32
+ stateDir: string;
33
+ generationsDir: string;
34
+ decisionSocketDir: string;
35
+ adminSocketDir: string;
36
+ /** The folder the host loads admin Skills from. */
37
+ managedDir: string;
38
+ /** The host's own configuration file (Claude Code managed-settings.json, Codex requirements.toml). */
39
+ hostConfig: string;
40
+ /** Codex only: `/etc/codex/managed_config.toml`, the second managed file of the Codex profile. */
41
+ managedConfig: string | undefined;
42
+ /** The shared systemd template unit. */
43
+ unit: string;
44
+ dropinDir: string;
45
+ dropin: string;
46
+ }
47
+ /** Every path of one instance. `base` is `/` in production; tests pass a temporary folder. */
48
+ export declare function instancePaths(host: Host, base?: string): InstancePaths;
49
+ /** `mago-ski <version>` from package.json, not a constant. */
50
+ export declare function buildId(): string;
51
+ export declare const missingInstanceMessage: (host: Host) => string;
52
+ /** Strict validation of a parsed instance config: unknown keys, missing keys and wrong types are refused. */
53
+ export declare function parseInstanceConfig(raw: unknown): InstanceConfig;
54
+ /** Reads the instance config. It must be a regular file owned by `rootUid` and not writable by group or others. */
55
+ export declare function readInstanceConfig(file: string, rootUid?: number): Promise<InstanceConfig>;
56
+ /** The service's own config for an instance. */
57
+ export declare function instanceToServiceConfig(cfg: InstanceConfig, rootUid?: number): GateServiceConfig;