@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.
- package/README.md +30 -3
- package/dist/hosts/github/run.d.ts +3 -1
- package/dist/hosts/github/run.js +29 -9
- package/dist/hosts/pi/index.js +48 -5
- package/dist/src/admin.d.ts +136 -1
- package/dist/src/admin.js +221 -84
- package/dist/src/cli.js +335 -10
- package/dist/src/fs-safe.d.ts +15 -2
- package/dist/src/fs-safe.js +32 -3
- package/dist/src/gate/adapters/claude-code-hook.d.ts +1 -0
- package/dist/src/gate/adapters/claude-code-hook.js +4 -0
- package/dist/src/gate/adapters/claude-code-settings.d.ts +13 -0
- package/dist/src/gate/adapters/claude-code-settings.js +49 -0
- package/dist/src/gate/adapters/claude-code.d.ts +33 -0
- package/dist/src/gate/adapters/claude-code.js +193 -0
- package/dist/src/gate/adapters/client.d.ts +13 -0
- package/dist/src/gate/adapters/client.js +57 -0
- package/dist/src/gate/adapters/codex-hook.d.ts +1 -0
- package/dist/src/gate/adapters/codex-hook.js +5 -0
- package/dist/src/gate/adapters/codex-requirements.d.ts +19 -0
- package/dist/src/gate/adapters/codex-requirements.js +56 -0
- package/dist/src/gate/adapters/codex.d.ts +16 -0
- package/dist/src/gate/adapters/codex.js +574 -0
- package/dist/src/gate/adapters/hook-main.d.ts +7 -0
- package/dist/src/gate/adapters/hook-main.js +35 -0
- package/dist/src/gate/adapters/host-pid.d.ts +1 -0
- package/dist/src/gate/adapters/host-pid.js +20 -0
- package/dist/src/gate/admission.d.ts +54 -0
- package/dist/src/gate/admission.js +490 -0
- package/dist/src/gate/contract.d.ts +51 -0
- package/dist/src/gate/contract.js +94 -0
- package/dist/src/gate/decision-log.d.ts +38 -0
- package/dist/src/gate/decision-log.js +251 -0
- package/dist/src/gate/generations.d.ts +67 -0
- package/dist/src/gate/generations.js +518 -0
- package/dist/src/gate/proc.d.ts +31 -0
- package/dist/src/gate/proc.js +79 -0
- package/dist/src/gate/refresh.d.ts +11 -0
- package/dist/src/gate/refresh.js +30 -0
- package/dist/src/gate/run-verifier.d.ts +23 -0
- package/dist/src/gate/run-verifier.js +89 -0
- package/dist/src/gate/service.d.ts +80 -0
- package/dist/src/gate/service.js +722 -0
- package/dist/src/gate/strict-json.d.ts +11 -0
- package/dist/src/gate/strict-json.js +190 -0
- package/dist/src/gate/trust-store.d.ts +36 -0
- package/dist/src/gate/trust-store.js +251 -0
- package/dist/src/gate/verifier-worker.d.ts +8 -0
- package/dist/src/gate/verifier-worker.js +66 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +2 -0
- package/dist/src/keys.d.ts +4 -0
- package/dist/src/keys.js +23 -14
- package/dist/src/policy.d.ts +145 -0
- package/dist/src/policy.js +554 -35
- package/dist/src/recovery-admin.d.ts +173 -0
- package/dist/src/recovery-admin.js +400 -0
- package/dist/src/root-events.d.ts +107 -0
- package/dist/src/root-events.js +376 -0
- package/dist/src/timestamp.d.ts +61 -0
- package/dist/src/timestamp.js +107 -0
- package/dist/src/tree-digest.d.ts +1 -0
- package/dist/src/tree-digest.js +1 -1
- package/dist/src/verify.d.ts +33 -0
- package/dist/src/verify.js +4 -2
- package/docs/hosts/adapter-interface.md +8 -2
- package/docs/hosts/github-action.md +1 -1
- package/docs/hosts/pi.md +2 -0
- package/docs/spec/gui-admin-rack-v1.md +289 -0
- package/docs/spec/root-recovery-v1.md +33 -12
- package/docs/spec/trust-documents-v1.md +8 -2
- package/docs/spec/verification.md +9 -2
- package/docs/threat-model.md +4 -2
- package/package.json +3 -1
|
@@ -0,0 +1,574 @@
|
|
|
1
|
+
// Codex hook adapter (E3 packet 9b). Pure of process I/O: codex-hook.ts feeds it stdin via hook-main.ts.
|
|
2
|
+
//
|
|
3
|
+
// WHAT IS ENFORCED AND WHAT IS NOT. Codex has no admin-only Skill lock (cx0.1/cx0.2, Codex 0.163.0 / Linux; unverified for
|
|
4
|
+
// other versions) and its hooks fail OPEN on crash, timeout or any exit other than 2. The primary control is therefore
|
|
5
|
+
// the requirements file (codex-requirements.ts: managed hooks only, deny_read on fixed user Skill roots) plus the
|
|
6
|
+
// service uninstalling revoked Skills. This adapter is the explicit-use gate on top of that and is partly best-effort:
|
|
7
|
+
// * UserPromptSubmit: parser-independent rule. We do NOT parse Skill names: Codex qualifies names with a plugin
|
|
8
|
+
// namespace from the nearest .codex-plugin/.claude-plugin/.cursor-plugin plugin.json (an untrusted repo can add one,
|
|
9
|
+
// so `$acme:foo` can select a Skill we never listed) and reads frontmatter with a full YAML parser (flow mappings,
|
|
10
|
+
// escapes, anchors, bare \r breaks), which a line scan cannot match. Instead the non-admin roots are walked like
|
|
11
|
+
// Codex only to answer "does ANY SKILL.md exist there?" (plus `incomplete`: unreadable entry, symlinked SKILL.md,
|
|
12
|
+
// FIFO, cap hit, bad root, ancestor cap hit, missing/relative cwd, unreadable host environment). If any exists or the
|
|
13
|
+
// walk is incomplete, EVERY `$token` is treated as possibly naming a non-admin Skill (see MASKING below); a token that
|
|
14
|
+
// is not a valid engine Skill name is blocked without asking; anything not VERIFIED is blocked in enforce.
|
|
15
|
+
// Independent of the walk: a token with a plugin namespace (`$acme:search`, `:` followed by a non-colon) is always
|
|
16
|
+
// blocked (NOT_ADMIN), and a link is checked first: only a link that resolves (realpath, `skill://` and `file://` accepted)
|
|
17
|
+
// to an approved `<admin_root>/<name>/SKILL.md` is asked; every other link is blocked (NOT_ADMIN), because Codex selects
|
|
18
|
+
// a linked mention by path (design docs/design/codex-gate-findings.md, Y1/X1: L1-L3, T1).
|
|
19
|
+
// On a clean machine only tokens equal to an admin-root directory name are asked, so `$5` in prose passes. RESIDUAL
|
|
20
|
+
// OVER-BLOCKING: on a machine with any user/repo Skill, `$word` prose is blocked in enforce. KNOWN LIMIT (live test):
|
|
21
|
+
// admin Skills are named here by the engine's frontmatter rule, Codex uses YAML; a mismatch can only affect
|
|
22
|
+
// admin-approved bytes, which the service uninstalls on revoke.
|
|
23
|
+
// * MASKING. Codex keeps same-name Skills; in rust-v0.163.0 a plain name shared by several Skills selects none
|
|
24
|
+
// (selection.rs skill_name_counts), but other versions or selectors may pick the repo one, so a bare `$alpha` is not
|
|
25
|
+
// trusted to mean the approved admin Skill `alpha`. Therefore, when a
|
|
26
|
+
// non-admin Skill exists or the walk is incomplete, a bare `$name` that equals an admin Skill name is BLOCKED; only a
|
|
27
|
+
// linked mention `[$alpha](<admin_root>/alpha/SKILL.md)` whose path resolves (realpath) to exactly that file is checked
|
|
28
|
+
// with the service. USABILITY COST: in a repo that ships its own Skills, admin Skills must be invoked by link (or the
|
|
29
|
+
// repo Skills removed). LIVE TEST (0.163.0 and 0.166.0, docs/spikes/codex-gate-live.md): Codex writes its bundled
|
|
30
|
+
// Skills to <codex_home>/skills/.system at startup, so a non-admin Skill always exists and EVERY bare mention of an
|
|
31
|
+
// admin Skill is blocked; in practice only the linked form works.
|
|
32
|
+
// * PreToolUse (any tool whose tool_input.command is a string; repeated slashes are collapsed; any `.agents`/`.codex` or
|
|
33
|
+
// SKILL.md text outside an admin Skill path is blocked): matching command text is BYPASSABLE (globs, variables, scripts) = defence in depth only.
|
|
34
|
+
// * Non-admin roots are walked like Codex (depth 6, hidden dirs skipped, directory symlinks followed with loop
|
|
35
|
+
// detection, cap 2000 dirs). A Skill created after
|
|
36
|
+
// the walk is a race the filesystem deny is meant to cover.
|
|
37
|
+
// * Repo roots: `.codex/skills` and `.agents/skills` in EVERY ancestor of cwd up to `/` (at most 64 levels, more =
|
|
38
|
+
// incomplete). Project-root markers are NOT used: `project_root_markers` is employee-controllable (user config.toml,
|
|
39
|
+
// CLI flags), so any marker-bounded scan could be moved above the adapter's bound. Over-blocking only.
|
|
40
|
+
// * User roots follow the host's environment, which the employee controls. The adapter runs with an empty environment
|
|
41
|
+
// but as the same user as the host, so it reads /proc/<host pid>/environ (bounded to 256 KiB) for CODEX_HOME and HOME
|
|
42
|
+
// and scans <CODEX_HOME or HOME/.codex>/skills, .../skills/.system and <HOME>/.agents/skills, in addition to the
|
|
43
|
+
// configured `skill_roots`. environ shows the environment at the host's exec time, which is what Codex reads at
|
|
44
|
+
// startup, except that Codex then loads <codex_home>/.env and may set HOME from it (not CODEX_*); so a .env that
|
|
45
|
+
// contains the bytes "HOME", or that is not a plain readable file, makes the walk incomplete. Both values must be
|
|
46
|
+
// absolute; an unreadable or invalid environment, or a missing HOME, makes the walk incomplete (fail closed). Values
|
|
47
|
+
// are never logged.
|
|
48
|
+
// * In enforce, mentions of system Skills are blocked unless installed as admin Skills.
|
|
49
|
+
// * Other tools than Bash (and Bash used indirectly) are allowed unasked.
|
|
50
|
+
//
|
|
51
|
+
// RESIDUALS (not fixable inside this hook):
|
|
52
|
+
// (a) Structured Skill selection (`UserInput::Skill`, `skill://` mentions sent by non-TUI clients or the app-server API)
|
|
53
|
+
// and the app-server `skills/extraRoots/set` call are not visible to the UserPromptSubmit hook; the adapter cannot
|
|
54
|
+
// gate them. Endpoint requirement: restrict app-server and non-TUI Codex clients.
|
|
55
|
+
// (b) Codex scans each text item separately while the hook sees them joined, so a token split across items can differ
|
|
56
|
+
// (needs a multi-text client).
|
|
57
|
+
// (c) The PreToolUse shell check is best-effort.
|
|
58
|
+
// (d) In enforce mode Codex coverage is weaker than Claude Code. The live test showed that deny_read does not hide user
|
|
59
|
+
// Skills from Codex's catalog, so the repo and user routes are both hook-only: audit-level.
|
|
60
|
+
// (e) Startup state (founder decision 2026-11-03, accepted limit): Codex fixes HOME, CODEX_HOME (canonicalised) and
|
|
61
|
+
// `<codex_home>/.env` once at startup; the hook only sees their state now. An employee can start Codex pointed at
|
|
62
|
+
// unapproved Skills (via .env HOME, or a CODEX_HOME symlink) and undo it before prompting. Needs an endpoint control
|
|
63
|
+
// (e.g. an admin-owned, employee-unwritable CODEX_HOME) before the user routes can be called enforced.
|
|
64
|
+
//
|
|
65
|
+
// HOST SCHEMA (Codex rust-v0.163.0, hooks/src/schema.rs): stdin JSON with `hook_event_name` = "SessionStart" |
|
|
66
|
+
// "UserPromptSubmit" (+ `prompt`, `cwd`, schema.rs:566-583) | "PreToolUse" (+ `tool_name`, `tool_input`, `cwd`,
|
|
67
|
+
// schema.rs:280-295; Bash reports `tool_input.command`, cx0.1). Other fields (session_id, turn_id, model, ...) are
|
|
68
|
+
// ignored: never used, never logged. Block = exit 2 with a non-empty stderr reason (events/pre_tool_use.rs:262-270;
|
|
69
|
+
// live-verified for PreToolUse and UserPromptSubmit in cx0.1). Allow = exit 0, no output. Any other exit code or an
|
|
70
|
+
// empty stderr with exit 2 is NOT a block in Codex, so the adapter always writes a reason with its 2.
|
|
71
|
+
// MODE/CONFIG/OWNERSHIP rules are the Claude adapter's (claude-code.ts): argv[1] is the mode, enforce wins, config and
|
|
72
|
+
// socket must be root-owned, the adapter's own environment is not read. Extra config keys: `admin_root` (default
|
|
73
|
+
// /etc/codex/skills; must be the gate service's `managedDir`) and `skill_roots` (extra absolute non-admin roots).
|
|
74
|
+
import { lstat, open, readdir, readFile, realpath, stat } from 'node:fs/promises';
|
|
75
|
+
import path from 'node:path';
|
|
76
|
+
import { isRecord } from "../../canonical-json.js";
|
|
77
|
+
import { validateSkillName } from "../../names.js";
|
|
78
|
+
import { decideAction } from "../contract.js";
|
|
79
|
+
import { parseStrictJson } from "../strict-json.js";
|
|
80
|
+
import { askService, newRequestId } from "./client.js";
|
|
81
|
+
import { loadConfig, MAX_STDIN_BYTES } from "./claude-code.js";
|
|
82
|
+
import { findHostPid } from "./host-pid.js";
|
|
83
|
+
const DEFAULT_SELF_DEADLINE_MS = 3000;
|
|
84
|
+
const INPUT_LIMITS = { maxBytes: MAX_STDIN_BYTES, maxDepth: 16, maxMembers: 256, maxStringLength: 128 * 1024 };
|
|
85
|
+
export const DEFAULT_ADMIN_ROOT = '/etc/codex/skills';
|
|
86
|
+
const MAX_ANCESTORS = 64;
|
|
87
|
+
const MAX_ADMIN_NAMES = 16;
|
|
88
|
+
const MAX_ENVIRON_BYTES = 256 * 1024;
|
|
89
|
+
const COULD_NOT_VERIFY = 'mago-ski could not verify this Skill; it is blocked until verification works.';
|
|
90
|
+
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
|
+
const notAdmin = (adminRoot) => `This Skill is not one of your organisation's approved Skills, so it is blocked. Approved Skills are installed in ${adminRoot}.`;
|
|
92
|
+
const notApproved = (verdict) => `This Skill is not approved by your organisation (mago-ski: ${verdict}). If it was updated, restart the session to use the new version.`;
|
|
93
|
+
const KINDS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse'];
|
|
94
|
+
// --- `$name` mention grammar: a port of codex-rs/skills/src/mentions.rs (rust-v0.163.0) --------------------------------
|
|
95
|
+
// Name bytes are [A-Za-z0-9_:-] (is_mention_name_char, :226); `$name` is a mention unless the upper-cased name is one of
|
|
96
|
+
// the common env vars (is_common_env_var, :208-224); `[$name](path)` (parse_linked_tool_mention, :151-206) is a mention
|
|
97
|
+
// of `name` unless the path starts with app://, mcp:// or plugin:// (extract_tool_mentions_with_sigil, :88-149).
|
|
98
|
+
// Addition (not in Codex): for a skill-kind path (skill:// or a SKILL.md file name, :43-60) the Skill folder name in the
|
|
99
|
+
// path is also a candidate, because Codex matches linked mentions by path.
|
|
100
|
+
const ENV_VARS = new Set(['PATH', 'HOME', 'USER', 'SHELL', 'PWD', 'TMPDIR', 'TEMP', 'TMP', 'LANG', 'TERM', 'XDG_CONFIG_HOME']);
|
|
101
|
+
const isNameChar = (c) => c !== undefined && /^[A-Za-z0-9_:-]$/u.test(c);
|
|
102
|
+
function nameAt(text, start) {
|
|
103
|
+
let end = start;
|
|
104
|
+
while (isNameChar(text[end]))
|
|
105
|
+
end += 1;
|
|
106
|
+
return end;
|
|
107
|
+
}
|
|
108
|
+
export function extractMentions(text, links, plain, linkNames) {
|
|
109
|
+
const names = new Set();
|
|
110
|
+
let i = 0;
|
|
111
|
+
while (i < text.length) {
|
|
112
|
+
if (text[i] === '[' && text[i + 1] === '$') {
|
|
113
|
+
const nameEnd = nameAt(text, i + 2);
|
|
114
|
+
let p = nameEnd + 1;
|
|
115
|
+
if (nameEnd > i + 2 && text[nameEnd] === ']') {
|
|
116
|
+
while (p < text.length && ' \t\n\f\r'.includes(text[p]))
|
|
117
|
+
p += 1; // ASCII whitespace only
|
|
118
|
+
const close = text[p] === '(' ? text.indexOf(')', p + 1) : -1;
|
|
119
|
+
const link = close >= 0 ? text.slice(p + 1, close).trim() : '';
|
|
120
|
+
if (link !== '') {
|
|
121
|
+
const name = text.slice(i + 2, nameEnd);
|
|
122
|
+
links?.push(link);
|
|
123
|
+
linkNames?.push(name); // the link text's name, env-var names included (parallel to `links`)
|
|
124
|
+
if (!ENV_VARS.has(name.toUpperCase())) {
|
|
125
|
+
if (!/^(app|mcp|plugin):\/\//u.test(link))
|
|
126
|
+
names.add(name);
|
|
127
|
+
const stem = link.replace(/^skill:\/\//u, '').split(/[/\\]/u);
|
|
128
|
+
if (/^skill:\/\//u.test(link) || /^skill\.md$/iu.test(stem.at(-1) ?? '')) {
|
|
129
|
+
if (/^skill\.md$/iu.test(stem.at(-1) ?? ''))
|
|
130
|
+
stem.pop();
|
|
131
|
+
const dir = stem.at(-1);
|
|
132
|
+
if (dir)
|
|
133
|
+
names.add(dir);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
i = close + 1;
|
|
137
|
+
continue;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (text[i] !== '$') {
|
|
142
|
+
i += 1;
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
const end = nameAt(text, i + 1);
|
|
146
|
+
if (end === i + 1) {
|
|
147
|
+
i += 1;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
const name = text.slice(i + 1, end);
|
|
151
|
+
if (!ENV_VARS.has(name.toUpperCase())) {
|
|
152
|
+
names.add(name);
|
|
153
|
+
plain?.add(name);
|
|
154
|
+
}
|
|
155
|
+
i = end;
|
|
156
|
+
}
|
|
157
|
+
return names;
|
|
158
|
+
}
|
|
159
|
+
// --- Skill roots -------------------------------------------------------------------------------------------------------
|
|
160
|
+
// ADMIN root: directory names only (the service installs it; a directory name is the Skill name there).
|
|
161
|
+
// NON-ADMIN roots (config skill_roots plus repo roots) mirror Codex's discovery (ext/skills/src/loader/discovery.rs +
|
|
162
|
+
// exec-server/src/local_file_system.rs walk, rust-v0.163.0): breadth-first from the root, root = depth 0; a directory
|
|
163
|
+
// entry is expanded only while the depth of the directory being read is < MAX_SCAN_DEPTH (loader/mod.rs:31 = 6), so a
|
|
164
|
+
// SKILL.md up to 6 directories below the root is found and one at 7 is not (the tests pin this); hidden directories
|
|
165
|
+
// (name starts with '.') are listed but not entered (local_file_system.rs:827; the root itself may be hidden, e.g. an
|
|
166
|
+
// explicitly listed `.system`); directory symlinks are followed for user/repo/admin scope (host.rs:165) with loops cut
|
|
167
|
+
// by realpath (:830-850). Only existence is recorded; file contents are never read. The file name is matched
|
|
168
|
+
// case-insensitively (conservative; Codex's exact-case rule is not verified here, over-matching only over-blocks).
|
|
169
|
+
// FAIL CLOSED: anything unreadable or over the caps sets `incomplete` (see runHook).
|
|
170
|
+
const MAX_SCAN_DEPTH = 6;
|
|
171
|
+
const MAX_DIRS = 2000;
|
|
172
|
+
const gone = (e) => ['ENOENT', 'ENOTDIR'].includes(e.code ?? '');
|
|
173
|
+
async function scanRoot(root, scan) {
|
|
174
|
+
let real;
|
|
175
|
+
try {
|
|
176
|
+
const st = await lstat(root);
|
|
177
|
+
if (!st.isDirectory()) {
|
|
178
|
+
scan.incomplete = true;
|
|
179
|
+
return;
|
|
180
|
+
} // symlinked or non-directory root: not followed, fail closed
|
|
181
|
+
real = await realpath(root);
|
|
182
|
+
}
|
|
183
|
+
catch (e) {
|
|
184
|
+
if (!gone(e))
|
|
185
|
+
scan.incomplete = true;
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
if (real.includes('\uFFFD')) {
|
|
189
|
+
scan.incomplete = true;
|
|
190
|
+
return;
|
|
191
|
+
} // non-UTF-8 real path: cannot be compared reliably
|
|
192
|
+
scan.realRoots.push(real);
|
|
193
|
+
const seen = new Set([real]);
|
|
194
|
+
const queue = [{ dir: root, depth: 0 }];
|
|
195
|
+
scan.dirs += 1;
|
|
196
|
+
for (let q = 0; q < queue.length; q += 1) {
|
|
197
|
+
const { dir, depth } = queue[q];
|
|
198
|
+
let entries;
|
|
199
|
+
try {
|
|
200
|
+
entries = (await readdir(dir)).sort();
|
|
201
|
+
}
|
|
202
|
+
catch {
|
|
203
|
+
scan.incomplete = true;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
for (const name of entries) {
|
|
207
|
+
if (name.includes('\uFFFD')) {
|
|
208
|
+
scan.incomplete = true;
|
|
209
|
+
continue;
|
|
210
|
+
} // non-UTF-8 name: lstat would miss it (lossy decode)
|
|
211
|
+
const p = path.join(dir, name);
|
|
212
|
+
let isDir;
|
|
213
|
+
try {
|
|
214
|
+
const ls = await lstat(p);
|
|
215
|
+
isDir = ls.isDirectory();
|
|
216
|
+
if (/^skill\.md$/iu.test(name) && !isDir) {
|
|
217
|
+
scan.found = true;
|
|
218
|
+
if (!ls.isFile())
|
|
219
|
+
scan.incomplete = true; // symlink, FIFO, ...: present but not a plain file
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (ls.isSymbolicLink())
|
|
223
|
+
isDir = (await stat(p)).isDirectory();
|
|
224
|
+
}
|
|
225
|
+
catch (e) {
|
|
226
|
+
if (!gone(e))
|
|
227
|
+
scan.incomplete = true;
|
|
228
|
+
continue;
|
|
229
|
+
} // a dangling link is ignored, as in Codex
|
|
230
|
+
if (!isDir || name.startsWith('.') || depth >= MAX_SCAN_DEPTH)
|
|
231
|
+
continue;
|
|
232
|
+
try {
|
|
233
|
+
const r = await realpath(p);
|
|
234
|
+
if (r.includes('\uFFFD')) {
|
|
235
|
+
scan.incomplete = true;
|
|
236
|
+
continue;
|
|
237
|
+
} // lossy: distinct targets would share one key
|
|
238
|
+
if (seen.has(r))
|
|
239
|
+
continue;
|
|
240
|
+
seen.add(r);
|
|
241
|
+
}
|
|
242
|
+
catch {
|
|
243
|
+
scan.incomplete = true;
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
if (scan.dirs >= MAX_DIRS) {
|
|
247
|
+
scan.incomplete = true;
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
scan.dirs += 1;
|
|
251
|
+
queue.push({ dir: p, depth: depth + 1 });
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** Every ancestor of cwd up to "/" (cwd first). Markers are ignored: they are employee-controlled. */
|
|
256
|
+
function ancestors(cwd, scan) {
|
|
257
|
+
const chain = [];
|
|
258
|
+
for (let d = path.normalize(cwd); chain.length < MAX_ANCESTORS; d = path.dirname(d)) {
|
|
259
|
+
chain.push(d);
|
|
260
|
+
if (path.dirname(d) === d)
|
|
261
|
+
return chain;
|
|
262
|
+
}
|
|
263
|
+
scan.incomplete = true; // deeper than the cap: the rest of the chain is not scanned
|
|
264
|
+
return chain;
|
|
265
|
+
}
|
|
266
|
+
/** Reads CODEX_HOME and HOME from /proc/<pid>/environ (first occurrence, as getenv). Throws on any problem. */
|
|
267
|
+
export async function readProcEnviron(pid) {
|
|
268
|
+
const fh = await open(`/proc/${pid}/environ`, 'r');
|
|
269
|
+
let buf;
|
|
270
|
+
try {
|
|
271
|
+
buf = Buffer.alloc(MAX_ENVIRON_BYTES + 1);
|
|
272
|
+
const { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
273
|
+
if (bytesRead > MAX_ENVIRON_BYTES)
|
|
274
|
+
throw new Error('environ too large');
|
|
275
|
+
buf = buf.subarray(0, bytesRead);
|
|
276
|
+
}
|
|
277
|
+
finally {
|
|
278
|
+
await fh.close();
|
|
279
|
+
}
|
|
280
|
+
const env = {};
|
|
281
|
+
for (const entry of buf.toString('utf8').split('\0')) {
|
|
282
|
+
if (entry.startsWith('CODEX_HOME=') && env.codexHome === undefined)
|
|
283
|
+
env.codexHome = entry.slice(11);
|
|
284
|
+
else if (entry.startsWith('HOME=') && env.home === undefined)
|
|
285
|
+
env.home = entry.slice(5);
|
|
286
|
+
}
|
|
287
|
+
return env;
|
|
288
|
+
}
|
|
289
|
+
/**
|
|
290
|
+
* Codex loads `<codex_home>/.env` at startup (arg0/src/lib.rs load_dotenv, rust-v0.163.0) and sets every key except
|
|
291
|
+
* CODEX_*, so it can change HOME after exec, which /proc/<pid>/environ does not show. dotenvy keys are bare identifiers
|
|
292
|
+
* (no escapes), so a file without the bytes "HOME" cannot set it. True = cannot rule it out (fail closed).
|
|
293
|
+
*/
|
|
294
|
+
async function dotenvMayMoveHome(codexHome) {
|
|
295
|
+
const file = `${codexHome}/.env`;
|
|
296
|
+
try {
|
|
297
|
+
const st = await lstat(file);
|
|
298
|
+
if (!st.isFile() || st.size > MAX_ENVIRON_BYTES)
|
|
299
|
+
return true; // symlink, FIFO, directory, huge: not inspected
|
|
300
|
+
return (await readFile(file)).includes('HOME');
|
|
301
|
+
}
|
|
302
|
+
catch (e) {
|
|
303
|
+
return e.code !== 'ENOENT';
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
async function findSkills(cfg, cwd, env) {
|
|
307
|
+
const scan = { found: false, realRoots: [], incomplete: false, dirs: 0 };
|
|
308
|
+
const admin = new Map((await listRoot(cfg.adminRoot)).map((e) => [e.toLowerCase(), e]));
|
|
309
|
+
const adminReal = await realpath(cfg.adminRoot).catch(() => undefined);
|
|
310
|
+
const roots = new Set(cfg.skillRoots);
|
|
311
|
+
// 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
|
+
// scanned at a name that does not exist. Fail closed instead.
|
|
313
|
+
const usable = (v) => v !== undefined && v !== '' && path.isAbsolute(v) && !/[\0\uFFFD]/u.test(v);
|
|
314
|
+
const absDir = (v) => usable(v) ? path.normalize(v).replace(/(?<=.)\/+$/u, '') : undefined;
|
|
315
|
+
const home = absDir(env?.home);
|
|
316
|
+
// 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 === ''
|
|
318
|
+
? (home === undefined ? undefined : `${home}/.codex`)
|
|
319
|
+
: usable(env.codexHome) ? await realpath(env.codexHome).then((r) => (usable(r) ? r : undefined), () => undefined) : undefined;
|
|
320
|
+
if (env === undefined || home === undefined || codexHome === undefined)
|
|
321
|
+
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);
|
|
327
|
+
const validCwd = usable(cwd);
|
|
328
|
+
if (!validCwd)
|
|
329
|
+
scan.incomplete = true;
|
|
330
|
+
else
|
|
331
|
+
for (const d of ancestors(cwd, scan))
|
|
332
|
+
for (const sub of ['.codex/skills', '.agents/skills'])
|
|
333
|
+
roots.add(path.join(d, sub));
|
|
334
|
+
for (const r of roots)
|
|
335
|
+
await scanRoot(r, scan);
|
|
336
|
+
return { admin, adminReal, anySkill: scan.found, roots: [...roots, ...scan.realRoots], incomplete: scan.incomplete, cwd: validCwd ? cwd : undefined };
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* The admin Skill (actual directory name) that a link `[$x](path)` resolves to by realpath, exactly `<admin>/<name>/SKILL.md`
|
|
340
|
+
* (rule L2). A leading `skill://` or `file://` is stripped; a `file://` with a host part, a relative link without a usable
|
|
341
|
+
* cwd, any other scheme and anything that does not resolve all give undefined (rule L3: not an approved Skill file).
|
|
342
|
+
*/
|
|
343
|
+
async function adminLinkName(link, f) {
|
|
344
|
+
if (f.adminReal === undefined || /^[a-z][a-z0-9+.-]*:\/\//iu.test(link) && !/^(file|skill):\/\//iu.test(link))
|
|
345
|
+
return undefined;
|
|
346
|
+
const stripped = link.replace(/^(file|skill):\/\//iu, '');
|
|
347
|
+
if (/^file:\/\//iu.test(link) && !stripped.startsWith('/'))
|
|
348
|
+
return undefined; // file://host/...
|
|
349
|
+
if (!path.isAbsolute(stripped) && f.cwd === undefined)
|
|
350
|
+
return undefined;
|
|
351
|
+
try {
|
|
352
|
+
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)
|
|
357
|
+
return name;
|
|
358
|
+
return undefined;
|
|
359
|
+
}
|
|
360
|
+
catch {
|
|
361
|
+
return undefined;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
async function listRoot(root) {
|
|
365
|
+
let st;
|
|
366
|
+
try {
|
|
367
|
+
st = await lstat(root);
|
|
368
|
+
}
|
|
369
|
+
catch (e) {
|
|
370
|
+
if (e.code === 'ENOENT')
|
|
371
|
+
return [];
|
|
372
|
+
throw e;
|
|
373
|
+
}
|
|
374
|
+
if (!st.isDirectory())
|
|
375
|
+
throw new Error('Skill root is not a real directory'); // a symlinked root is not followed: fail closed
|
|
376
|
+
return readdir(root);
|
|
377
|
+
}
|
|
378
|
+
// --- Bash command text (best-effort) -----------------------------------------------------------------------------------
|
|
379
|
+
function inspectCommand(raw, cfg) {
|
|
380
|
+
const command = raw.replace(/\/{2,}/gu, '/'); // `.agents//skills` is the same path
|
|
381
|
+
const collapse = (v) => v.replace(/\/{2,}/gu, '/');
|
|
382
|
+
const esc = collapse(cfg.adminRoot).replace(/[.*+?^${}()|[\]\\]/gu, '\\$&');
|
|
383
|
+
// Any mention of a user/repo Skill location in any spelling (~, $HOME, relative), or of a SKILL.md file other than an
|
|
384
|
+
// admin Skill's own `<admin_root>/<name>/SKILL.md`.
|
|
385
|
+
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'), '');
|
|
387
|
+
const rogue = /\.(agents|codex)(?![A-Za-z0-9_-])/u.test(command) || /skill\.md/iu.test(outsideAdmin)
|
|
388
|
+
|| cfg.skillRoots.some((r) => command.includes(collapse(r)));
|
|
389
|
+
const admin = new Set();
|
|
390
|
+
for (const m of command.matchAll(new RegExp(`${esc}/([A-Za-z0-9][A-Za-z0-9._-]*)`, 'gu')))
|
|
391
|
+
admin.add(m[1]);
|
|
392
|
+
// An admin path that does not start a word (`-I/etc/codex/skills/a`, `<other>/etc/codex/...`) is not trusted: block.
|
|
393
|
+
const anywhere = [...command.matchAll(new RegExp(esc, 'gu'))].length;
|
|
394
|
+
const atStart = [...command.matchAll(new RegExp(`${start}${esc}`, 'gu'))].length;
|
|
395
|
+
if (anywhere !== atStart)
|
|
396
|
+
return { rogue: true, admin: [...admin] };
|
|
397
|
+
return { rogue, admin: [...admin] };
|
|
398
|
+
}
|
|
399
|
+
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;
|
|
402
|
+
const abs = (v) => typeof v === 'string' && path.isAbsolute(v) && !v.includes('\0');
|
|
403
|
+
if (!abs(admin) || !Array.isArray(roots) || roots.length > 64 || !roots.every(abs))
|
|
404
|
+
throw new Error('bad Skill roots');
|
|
405
|
+
return { ...cfg, adminRoot: admin.replace(/\/+$/u, ''), skillRoots: roots.map((r) => r.replace(/\/+$/u, '')) };
|
|
406
|
+
}
|
|
407
|
+
function parseHookInput(bytes, peek) {
|
|
408
|
+
const raw = parseStrictJson(bytes, INPUT_LIMITS);
|
|
409
|
+
if (!isRecord(raw))
|
|
410
|
+
throw new Error('input must be an object');
|
|
411
|
+
const name = raw['hook_event_name'];
|
|
412
|
+
if (typeof name !== 'string' || !KINDS.includes(name))
|
|
413
|
+
throw new Error('unknown event');
|
|
414
|
+
peek(name);
|
|
415
|
+
if (name === 'SessionStart')
|
|
416
|
+
return { kind: 'start' };
|
|
417
|
+
const cwd = raw['cwd'];
|
|
418
|
+
if (cwd !== undefined && typeof cwd !== 'string')
|
|
419
|
+
throw new Error('bad cwd');
|
|
420
|
+
if (name === 'UserPromptSubmit') {
|
|
421
|
+
if (typeof raw['prompt'] !== 'string')
|
|
422
|
+
throw new Error('missing prompt');
|
|
423
|
+
return { kind: 'prompt', prompt: raw['prompt'], ...(cwd !== undefined ? { cwd } : {}) };
|
|
424
|
+
}
|
|
425
|
+
if (typeof raw['tool_name'] !== 'string' || !isRecord(raw['tool_input']))
|
|
426
|
+
throw new Error('bad tool call');
|
|
427
|
+
const command = raw['tool_input']['command'];
|
|
428
|
+
if (typeof command === 'string')
|
|
429
|
+
return { kind: 'bash', command }; // any tool with a string command is a shell command
|
|
430
|
+
if (Array.isArray(command) && command.length > 0 && command.every((c) => typeof c === 'string'))
|
|
431
|
+
return { kind: 'bash', command: command.join(' ') }; // argv-style commands are inspected the same way
|
|
432
|
+
if (raw['tool_name'] === 'Bash')
|
|
433
|
+
throw new Error('missing command');
|
|
434
|
+
return { kind: 'other-tool' };
|
|
435
|
+
}
|
|
436
|
+
const OK = { code: 0, stdout: '', stderr: '' };
|
|
437
|
+
const block = (message) => ({ code: 2, stdout: '', stderr: message });
|
|
438
|
+
/** Never throws and never outlives the self-deadline. */
|
|
439
|
+
export async function runHook(argv, deps) {
|
|
440
|
+
let mode = 'enforce';
|
|
441
|
+
const out = await runHookInner(argv, deps, (m) => { mode = m; });
|
|
442
|
+
return { ...out, mode };
|
|
443
|
+
}
|
|
444
|
+
async function runHookInner(argv, deps, setMode) {
|
|
445
|
+
const uid = deps.rootUid ?? 0; // never from argv
|
|
446
|
+
let mode = argv[1] === 'shadow' ? 'shadow' : 'enforce';
|
|
447
|
+
let kind;
|
|
448
|
+
let cfg;
|
|
449
|
+
try {
|
|
450
|
+
cfg = await loadCodexConfig(argv[0] ?? '', uid);
|
|
451
|
+
}
|
|
452
|
+
catch {
|
|
453
|
+
cfg = undefined;
|
|
454
|
+
}
|
|
455
|
+
if (cfg?.mode === 'enforce')
|
|
456
|
+
mode = 'enforce';
|
|
457
|
+
setMode(mode);
|
|
458
|
+
const fail = (message) => (mode === 'shadow' || kind === 'SessionStart' ? OK : block(message));
|
|
459
|
+
const work = async () => {
|
|
460
|
+
const bytes = await deps.readStdin();
|
|
461
|
+
if (!bytes)
|
|
462
|
+
return fail(COULD_NOT_VERIFY);
|
|
463
|
+
let parsed;
|
|
464
|
+
try {
|
|
465
|
+
parsed = parseHookInput(bytes, (k) => { kind = k; });
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
return fail(COULD_NOT_VERIFY);
|
|
469
|
+
}
|
|
470
|
+
if (!cfg)
|
|
471
|
+
return fail(COULD_NOT_VERIFY);
|
|
472
|
+
// The host pid is needed both for the environment read (prompts with mentions) and for the service session.
|
|
473
|
+
let hostPid;
|
|
474
|
+
const host = () => (hostPid ??= (deps.findHost ?? findHostPid)(cfg.hostExes));
|
|
475
|
+
// What to ask the service about: [skill, event]. Nothing to ask for an ordinary prompt or command.
|
|
476
|
+
const asks = [];
|
|
477
|
+
if (parsed.kind === 'prompt') {
|
|
478
|
+
const links = [];
|
|
479
|
+
const plain = new Set();
|
|
480
|
+
const linkNames = [];
|
|
481
|
+
const names = extractMentions(parsed.prompt, links, plain, linkNames);
|
|
482
|
+
if (names.size > 0 || links.length > 0) { // a link decides even when its name is an env var
|
|
483
|
+
let env;
|
|
484
|
+
try {
|
|
485
|
+
env = await (deps.readHostEnv ?? readProcEnviron)(await host());
|
|
486
|
+
}
|
|
487
|
+
catch {
|
|
488
|
+
env = undefined;
|
|
489
|
+
} // fail closed in findSkills
|
|
490
|
+
const f = await findSkills(cfg, parsed.cwd, env);
|
|
491
|
+
const wide = f.anySkill || f.incomplete; // a non-admin Skill may exist: any token could name it
|
|
492
|
+
// Links first, in prompt order (design Y1/X1): L1 ignored, L2 resolves to an admin Skill file (asked), L3 blocked.
|
|
493
|
+
for (const [i, l] of links.entries()) {
|
|
494
|
+
if (/^(app|mcp|plugin):\/\//u.test(l))
|
|
495
|
+
continue; // L1 (exact lower-case schemes, as Codex matches them)
|
|
496
|
+
const a = await adminLinkName(l, f);
|
|
497
|
+
// 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()) {
|
|
500
|
+
if (mode === 'enforce')
|
|
501
|
+
return block(notAdmin(cfg.adminRoot)); // L3
|
|
502
|
+
continue;
|
|
503
|
+
}
|
|
504
|
+
asks.push({ skill: validateSkillName(a), event: 'prompt-expansion' });
|
|
505
|
+
}
|
|
506
|
+
// Then the plain tokens in prompt order (T1-T6, "wide" form).
|
|
507
|
+
for (const n of plain) {
|
|
508
|
+
if (/:[^:]/u.test(n)) { // T1: a plugin-namespaced token can select a Skill the walk never lists
|
|
509
|
+
if (mode === 'enforce')
|
|
510
|
+
return block(notAdmin(cfg.adminRoot));
|
|
511
|
+
continue;
|
|
512
|
+
}
|
|
513
|
+
const adminName = f.admin.get(n.toLowerCase());
|
|
514
|
+
if (adminName === undefined && !wide)
|
|
515
|
+
continue; // T6
|
|
516
|
+
// T2: under wide, an admin name may really select a same-name repo/user Skill.
|
|
517
|
+
if (wide && adminName !== undefined && mode === 'enforce')
|
|
518
|
+
return block(MASKED);
|
|
519
|
+
let skill;
|
|
520
|
+
try {
|
|
521
|
+
skill = validateSkillName(adminName ?? n);
|
|
522
|
+
}
|
|
523
|
+
catch {
|
|
524
|
+
if (mode === 'enforce')
|
|
525
|
+
return block(notAdmin(cfg.adminRoot)); // T4: e.g. `alpha:` under wide
|
|
526
|
+
continue;
|
|
527
|
+
}
|
|
528
|
+
asks.push({ skill, event: 'prompt-expansion' });
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
else if (parsed.kind === 'bash') {
|
|
533
|
+
const c = inspectCommand(parsed.command, cfg);
|
|
534
|
+
if (c.rogue && mode === 'enforce')
|
|
535
|
+
return block(notAdmin(cfg.adminRoot));
|
|
536
|
+
if (c.admin.length > MAX_ADMIN_NAMES)
|
|
537
|
+
return fail(COULD_NOT_VERIFY);
|
|
538
|
+
for (const skill of c.admin)
|
|
539
|
+
asks.push({ skill: validateSkillName(skill), event: 'skill-invoke' });
|
|
540
|
+
}
|
|
541
|
+
if (parsed.kind !== 'start' && asks.length === 0)
|
|
542
|
+
return OK;
|
|
543
|
+
let pid;
|
|
544
|
+
try {
|
|
545
|
+
pid = await host();
|
|
546
|
+
}
|
|
547
|
+
catch {
|
|
548
|
+
return fail(COULD_NOT_VERIFY);
|
|
549
|
+
}
|
|
550
|
+
const session = `pid:${pid}`;
|
|
551
|
+
const ask = async (request) => (deps.ask ?? askService)(cfg.socket, { v: 1, request_id: newRequestId(), session, ...request }, cfg.clientDeadlineMs, cfg.rootUid);
|
|
552
|
+
if (parsed.kind === 'start') {
|
|
553
|
+
await ask({ event: 'session-start' });
|
|
554
|
+
return OK;
|
|
555
|
+
} // never blocks
|
|
556
|
+
for (const a of asks) {
|
|
557
|
+
const answer = await ask({ event: a.event, skill: a.skill });
|
|
558
|
+
const result = answer.ok ? answer.result : { kind: 'parse-failure' };
|
|
559
|
+
if (decideAction(result, mode) === 'deny')
|
|
560
|
+
return block(result.kind === 'verdict' && result.verdict !== 'UNVERIFIABLE' ? notApproved(result.verdict) : COULD_NOT_VERIFY);
|
|
561
|
+
}
|
|
562
|
+
return OK;
|
|
563
|
+
};
|
|
564
|
+
let timer;
|
|
565
|
+
const timeout = new Promise((resolve) => {
|
|
566
|
+
timer = setTimeout(() => resolve(fail(COULD_NOT_VERIFY)), cfg?.selfDeadlineMs ?? DEFAULT_SELF_DEADLINE_MS);
|
|
567
|
+
});
|
|
568
|
+
try {
|
|
569
|
+
return await Promise.race([work().catch(() => fail(COULD_NOT_VERIFY)), timeout]);
|
|
570
|
+
}
|
|
571
|
+
finally {
|
|
572
|
+
clearTimeout(timer);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { type HookDeps } from './claude-code.ts';
|
|
2
|
+
export declare function hookMain(argv: readonly string[], extra?: Omit<HookDeps, 'readStdin'>, run?: (argv: readonly string[], deps: HookDeps) => Promise<{
|
|
3
|
+
code: number;
|
|
4
|
+
stdout: string;
|
|
5
|
+
stderr: string;
|
|
6
|
+
mode?: string;
|
|
7
|
+
}>): Promise<never>;
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Shared process wrapper for the Claude Code hook: reads bounded stdin, runs the adapter, writes its outcome, exits.
|
|
2
|
+
import { MAX_STDIN_BYTES, runHook } from "./claude-code.js";
|
|
3
|
+
async function readStdin() {
|
|
4
|
+
const chunks = [];
|
|
5
|
+
let size = 0;
|
|
6
|
+
for await (const chunk of process.stdin) {
|
|
7
|
+
size += chunk.length;
|
|
8
|
+
if (size > MAX_STDIN_BYTES)
|
|
9
|
+
return null;
|
|
10
|
+
chunks.push(chunk);
|
|
11
|
+
}
|
|
12
|
+
return Buffer.concat(chunks);
|
|
13
|
+
}
|
|
14
|
+
export async function hookMain(argv, extra = {}, run = runHook) {
|
|
15
|
+
let outcome = { code: 2, stdout: '', stderr: 'mago-ski could not verify this Skill; it is blocked until verification works.' };
|
|
16
|
+
try {
|
|
17
|
+
outcome = await run(argv, { ...extra, readStdin });
|
|
18
|
+
}
|
|
19
|
+
catch { /* keeps the explicit block above */ }
|
|
20
|
+
const shadow = outcome.mode === 'shadow';
|
|
21
|
+
if (outcome.stderr)
|
|
22
|
+
process.stderr.write(outcome.stderr);
|
|
23
|
+
// A broken stdout must not turn an intended deny into an allow: exit 2 with a stderr reason (shadow: exit 0).
|
|
24
|
+
// Exit 2 as a block is unverified (live check pending).
|
|
25
|
+
process.stdout.on('error', () => { });
|
|
26
|
+
return new Promise(() => {
|
|
27
|
+
process.stdout.write(outcome.stdout, (err) => {
|
|
28
|
+
if (!err)
|
|
29
|
+
return process.exit(outcome.code);
|
|
30
|
+
if (!shadow)
|
|
31
|
+
process.stderr.write('mago-ski could not deliver its decision; this Skill is blocked.');
|
|
32
|
+
process.exit(shadow ? 0 : 2);
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function findHostPid(hostExes: readonly string[], startPid?: number): Promise<number>;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// Names the host process (claude) that spawned a hook: walks the parent chain and returns the first ancestor whose
|
|
2
|
+
// /proc/<pid>/exe is allowlisted. Only a pointer for the service, which re-verifies the pid from the kernel.
|
|
3
|
+
import { readFile, readlink } from 'node:fs/promises';
|
|
4
|
+
const MAX_LEVELS = 8;
|
|
5
|
+
export async function findHostPid(hostExes, startPid = process.ppid) {
|
|
6
|
+
let pid = startPid;
|
|
7
|
+
for (let level = 0; level < MAX_LEVELS && pid > 1; level += 1) {
|
|
8
|
+
let exe = await readlink(`/proc/${pid}/exe`).catch(() => '');
|
|
9
|
+
if (exe.endsWith(' (deleted)'))
|
|
10
|
+
exe = exe.slice(0, -' (deleted)'.length); // same acceptance as service.ts
|
|
11
|
+
if (hostExes.includes(exe))
|
|
12
|
+
return pid;
|
|
13
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8').catch(() => '');
|
|
14
|
+
// comm may hold spaces and ')': fields start behind the LAST ')'; rest[0] is the state, rest[1] the ppid.
|
|
15
|
+
pid = Number(stat.slice(stat.lastIndexOf(')') + 2).split(' ')[1]);
|
|
16
|
+
if (!Number.isSafeInteger(pid))
|
|
17
|
+
break;
|
|
18
|
+
}
|
|
19
|
+
throw new Error('host process not found');
|
|
20
|
+
}
|