@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,33 @@
|
|
|
1
|
+
import type { Mode } from '../../policy.ts';
|
|
2
|
+
import { type GateRequest } from '../contract.ts';
|
|
3
|
+
import { type AskResult } from './client.ts';
|
|
4
|
+
import { findHostPid } from './host-pid.ts';
|
|
5
|
+
export declare const MAX_STDIN_BYTES: number;
|
|
6
|
+
export interface HookConfig {
|
|
7
|
+
socket: string;
|
|
8
|
+
mode: Mode;
|
|
9
|
+
hostExes: string[];
|
|
10
|
+
clientDeadlineMs: number;
|
|
11
|
+
selfDeadlineMs: number;
|
|
12
|
+
rootUid: number;
|
|
13
|
+
/** The validated config object, for adapters that add their own keys (see `extraKeys`). */
|
|
14
|
+
raw: Record<string, unknown>;
|
|
15
|
+
}
|
|
16
|
+
export interface HookOutcome {
|
|
17
|
+
code: number;
|
|
18
|
+
stdout: string;
|
|
19
|
+
stderr: string;
|
|
20
|
+
mode?: Mode;
|
|
21
|
+
}
|
|
22
|
+
export interface HookDeps {
|
|
23
|
+
/** Resolves the whole stdin, or null if it exceeded MAX_STDIN_BYTES. */
|
|
24
|
+
readStdin: () => Promise<Buffer | null>;
|
|
25
|
+
findHost?: typeof findHostPid;
|
|
26
|
+
ask?: (socket: string, request: GateRequest, deadlineMs: number, rootUid: number) => Promise<AskResult>;
|
|
27
|
+
/** Uid that must own the config, socket directory and socket. Production: always 0 (tests inject their own). */
|
|
28
|
+
rootUid?: number;
|
|
29
|
+
}
|
|
30
|
+
/** Strict, closed config: root-owned in production (a deployment requirement; here only "not group/other writable"). */
|
|
31
|
+
export declare function loadConfig(file: string, rootUid?: number, extraKeys?: readonly string[]): Promise<HookConfig>;
|
|
32
|
+
/** Never throws and never outlives the self-deadline. */
|
|
33
|
+
export declare function runHook(argv: readonly string[], deps: HookDeps): Promise<HookOutcome>;
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// Claude Code hook adapter (E3 packet 9a, profile 1: plain managed-directory Skill names only). Pure of process I/O:
|
|
2
|
+
// claude-code-hook.ts feeds it stdin and writes its outcome.
|
|
3
|
+
//
|
|
4
|
+
// HOST SCHEMA (the one place). These shapes are what the cc0.3/cc0.4 spikes observed on Claude Code CLI 2.1.296 / Linux
|
|
5
|
+
// (.agent/reviews/cc0.4-fixtures/gate.py and cc0.4-enforcement-verification.md). They are NOT a verified complete host
|
|
6
|
+
// API and are unverified for any other version; re-check them before widening the supported matrix.
|
|
7
|
+
// stdin PreToolUse: { hook_event_name: "PreToolUse", tool_name: "Skill", tool_input: { skill: "<name>", ... }, ... }
|
|
8
|
+
// UserPromptExpansion: { hook_event_name: "UserPromptExpansion", command_name: "<name or /name>", ... }
|
|
9
|
+
// SessionStart: { hook_event_name: "SessionStart", ... }
|
|
10
|
+
// Other outer fields (session_id, cwd, transcript_path, ...) are ignored: never used, never logged.
|
|
11
|
+
// UNVERIFIED: whether command_name carries a leading "/" (a single one is stripped), whether built-in slash
|
|
12
|
+
// commands (/help, ...) also reach UserPromptExpansion (they would be denied in enforce: NO_CERTIFICATE).
|
|
13
|
+
// block PreToolUse: stdout {"hookSpecificOutput":{"hookEventName":"PreToolUse","permissionDecision":"deny",
|
|
14
|
+
// "permissionDecisionReason":<msg>}}, exit 0 (observed to block in cc0.4)
|
|
15
|
+
// UserPromptExpansion: stdout {"decision":"block","reason":<msg>}, exit 0 (observed to block in cc0.4)
|
|
16
|
+
// Primary block mechanism = these JSON answers with exit 0, because they are the only ones the evidence shows
|
|
17
|
+
// working. Exit 2 + stderr is used ONLY when the event cannot be told (unparseable stdin, unknown event); it is
|
|
18
|
+
// the host's generic block but UNVERIFIED here (live check pending; that exit 2 blocks is not evidenced).
|
|
19
|
+
// If the strict parse fails but a lenient byte scan still finds a known blockable event name, that event's
|
|
20
|
+
// deny body is emitted (a spoofed name can only produce a deny). SessionStart is never blocked.
|
|
21
|
+
// allow exit 0, no output.
|
|
22
|
+
//
|
|
23
|
+
// MODE. The managed settings pass the mode as argv[1] (`enforce`|`shadow`) as well as in the config file: if the
|
|
24
|
+
// config is unreadable or invalid, argv decides, and anything but exactly `shadow` is enforce. Enforce wins if either
|
|
25
|
+
// source says enforce (decideAction additionally never lets a service answer downgrade it).
|
|
26
|
+
// The adapter reads no environment variables. The config, its socket directory and the socket must be owned by root
|
|
27
|
+
// (uid 0); argv cannot change that (tests inject a uid through HookDeps via their own entry point).
|
|
28
|
+
import { lstat, readFile } from 'node:fs/promises';
|
|
29
|
+
import path from 'node:path';
|
|
30
|
+
import { isRecord } from "../../canonical-json.js";
|
|
31
|
+
import { validateSkillName } from "../../names.js";
|
|
32
|
+
import { decideAction } from "../contract.js";
|
|
33
|
+
import { parseStrictJson } from "../strict-json.js";
|
|
34
|
+
import { askService, DEFAULT_CLIENT_DEADLINE_MS, newRequestId } from "./client.js";
|
|
35
|
+
import { findHostPid } from "./host-pid.js";
|
|
36
|
+
export const MAX_STDIN_BYTES = 256 * 1024;
|
|
37
|
+
const DEFAULT_SELF_DEADLINE_MS = 3000;
|
|
38
|
+
// Matched to the stdin cap (the default 64 KiB / 16 KiB limits would deny legitimate long prompts).
|
|
39
|
+
const INPUT_LIMITS = { maxBytes: MAX_STDIN_BYTES, maxDepth: 16, maxMembers: 256, maxStringLength: 128 * 1024 };
|
|
40
|
+
const KINDS = ['PreToolUse', 'UserPromptExpansion', 'SessionStart'];
|
|
41
|
+
const COULD_NOT_VERIFY = 'mago-ski could not verify this Skill; it is blocked until verification works.';
|
|
42
|
+
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.`;
|
|
43
|
+
/** Strict, closed config: root-owned in production (a deployment requirement; here only "not group/other writable"). */
|
|
44
|
+
export async function loadConfig(file, rootUid = 0, extraKeys = []) {
|
|
45
|
+
if (!path.isAbsolute(file))
|
|
46
|
+
throw new Error('config path must be absolute');
|
|
47
|
+
const st = await lstat(file);
|
|
48
|
+
if (!st.isFile() || (st.mode & 0o022) !== 0 || st.uid !== rootUid)
|
|
49
|
+
throw new Error('config must be a regular, root-owned, non-writable file');
|
|
50
|
+
const raw = parseStrictJson(await readFile(file));
|
|
51
|
+
if (!isRecord(raw))
|
|
52
|
+
throw new Error('config must be an object');
|
|
53
|
+
const allowed = ['v', 'socket', 'mode', 'host_exes', 'client_deadline_ms', 'self_deadline_ms', ...extraKeys];
|
|
54
|
+
if (Object.keys(raw).some((k) => !allowed.includes(k)) || raw['v'] !== 1)
|
|
55
|
+
throw new Error('config has unknown fields or version');
|
|
56
|
+
const { socket, mode, host_exes: exes } = raw;
|
|
57
|
+
if (typeof socket !== 'string' || !path.isAbsolute(socket) || socket.length > 107)
|
|
58
|
+
throw new Error('bad socket');
|
|
59
|
+
if (mode !== 'enforce' && mode !== 'shadow')
|
|
60
|
+
throw new Error('bad mode');
|
|
61
|
+
const dir = await lstat(path.dirname(socket)); // the socket directory must not be replaceable by other users
|
|
62
|
+
if (!dir.isDirectory() || dir.isSymbolicLink() || (dir.mode & 0o022) !== 0 || dir.uid !== rootUid)
|
|
63
|
+
throw new Error('bad socket directory');
|
|
64
|
+
if (!Array.isArray(exes) || exes.length === 0 || !exes.every((e) => typeof e === 'string' && path.isAbsolute(e)))
|
|
65
|
+
throw new Error('bad host_exes');
|
|
66
|
+
const ms = (v, dflt) => {
|
|
67
|
+
if (v === undefined)
|
|
68
|
+
return dflt;
|
|
69
|
+
if (typeof v !== 'number' || !Number.isInteger(v) || v < 50 || v > 60_000)
|
|
70
|
+
throw new Error('bad deadline');
|
|
71
|
+
return v;
|
|
72
|
+
};
|
|
73
|
+
return {
|
|
74
|
+
socket, mode, hostExes: exes, rootUid, raw,
|
|
75
|
+
clientDeadlineMs: ms(raw['client_deadline_ms'], DEFAULT_CLIENT_DEADLINE_MS),
|
|
76
|
+
selfDeadlineMs: ms(raw['self_deadline_ms'], DEFAULT_SELF_DEADLINE_MS),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** Closed per-event schemas; `peek` receives the event kind as soon as it is known, even if the rest is invalid. */
|
|
80
|
+
function parseHookInput(bytes, peek) {
|
|
81
|
+
const raw = parseStrictJson(bytes, INPUT_LIMITS);
|
|
82
|
+
if (!isRecord(raw))
|
|
83
|
+
throw new Error('input must be an object');
|
|
84
|
+
const name = raw['hook_event_name'];
|
|
85
|
+
if (typeof name !== 'string' || !KINDS.includes(name))
|
|
86
|
+
throw new Error('unknown event');
|
|
87
|
+
peek(name);
|
|
88
|
+
if (name === 'SessionStart')
|
|
89
|
+
return { kind: 'session-start' };
|
|
90
|
+
let skill;
|
|
91
|
+
if (name === 'PreToolUse') {
|
|
92
|
+
const input = raw['tool_input'];
|
|
93
|
+
if (raw['tool_name'] !== 'Skill' || !isRecord(input))
|
|
94
|
+
throw new Error('not a Skill call');
|
|
95
|
+
skill = input['skill'];
|
|
96
|
+
}
|
|
97
|
+
else {
|
|
98
|
+
skill = raw['command_name'];
|
|
99
|
+
}
|
|
100
|
+
if (typeof skill !== 'string')
|
|
101
|
+
throw new Error('missing Skill name');
|
|
102
|
+
// A plugin-namespaced name (`plugin:name`) fails validateSkillName: unsupported in profile 1, so denied.
|
|
103
|
+
return {
|
|
104
|
+
kind: 'skill', event: name === 'PreToolUse' ? 'skill-invoke' : 'prompt-expansion',
|
|
105
|
+
skill: validateSkillName(skill.startsWith('/') ? skill.slice(1) : skill),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
function block(kind, message) {
|
|
109
|
+
if (kind === 'PreToolUse')
|
|
110
|
+
return { code: 0, stderr: '', stdout: JSON.stringify({ hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: message } }) };
|
|
111
|
+
if (kind === 'UserPromptExpansion')
|
|
112
|
+
return { code: 0, stderr: '', stdout: JSON.stringify({ decision: 'block', reason: message }) };
|
|
113
|
+
if (kind === 'SessionStart')
|
|
114
|
+
return { code: 0, stdout: '', stderr: '' };
|
|
115
|
+
return { code: 2, stdout: '', stderr: message }; // event unknown: the host's generic block (unverified)
|
|
116
|
+
}
|
|
117
|
+
/** Lenient scan for a blockable event name in bytes the strict parser rejected. */
|
|
118
|
+
function scanKind(bytes) {
|
|
119
|
+
const text = bytes.toString('latin1');
|
|
120
|
+
// Exactly one hook_event_name in the raw bytes: a second one (e.g. nested in model-controlled tool_input) makes the
|
|
121
|
+
// event ambiguous, so fall back to exit 2 rather than risk the wrong event's block body.
|
|
122
|
+
if ((text.match(/"hook_event_name"/gu) ?? []).length !== 1)
|
|
123
|
+
return undefined;
|
|
124
|
+
const m = /"hook_event_name"\s*:\s*"(PreToolUse|UserPromptExpansion)"/u.exec(text);
|
|
125
|
+
return m ? m[1] : undefined;
|
|
126
|
+
}
|
|
127
|
+
const OK = { code: 0, stdout: '', stderr: '' };
|
|
128
|
+
/** Never throws and never outlives the self-deadline. */
|
|
129
|
+
export async function runHook(argv, deps) {
|
|
130
|
+
let mode = 'enforce';
|
|
131
|
+
const out = await runHookInner(argv, deps, (m) => { mode = m; });
|
|
132
|
+
return { ...out, mode };
|
|
133
|
+
}
|
|
134
|
+
async function runHookInner(argv, deps, setMode) {
|
|
135
|
+
const uid = deps.rootUid ?? 0; // never from argv: a non-root uid here would let that user run a fake service
|
|
136
|
+
let mode = argv[1] === 'shadow' ? 'shadow' : 'enforce';
|
|
137
|
+
let kind;
|
|
138
|
+
let cfg;
|
|
139
|
+
try {
|
|
140
|
+
cfg = await loadConfig(argv[0] ?? '', uid);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
cfg = undefined;
|
|
144
|
+
} // lstat first, so a FIFO cannot hang it
|
|
145
|
+
if (cfg?.mode === 'enforce')
|
|
146
|
+
mode = 'enforce';
|
|
147
|
+
setMode(mode);
|
|
148
|
+
const fail = (message) => (mode === 'shadow' ? OK : block(kind, message));
|
|
149
|
+
const work = async () => {
|
|
150
|
+
const bytes = await deps.readStdin();
|
|
151
|
+
if (!bytes)
|
|
152
|
+
return fail(COULD_NOT_VERIFY);
|
|
153
|
+
let parsed;
|
|
154
|
+
try {
|
|
155
|
+
parsed = parseHookInput(bytes, (k) => { kind = k; });
|
|
156
|
+
}
|
|
157
|
+
catch {
|
|
158
|
+
kind ??= scanKind(bytes);
|
|
159
|
+
return fail(COULD_NOT_VERIFY);
|
|
160
|
+
}
|
|
161
|
+
if (!cfg)
|
|
162
|
+
return fail(COULD_NOT_VERIFY);
|
|
163
|
+
let pid;
|
|
164
|
+
try {
|
|
165
|
+
pid = await (deps.findHost ?? findHostPid)(cfg.hostExes);
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
return fail(COULD_NOT_VERIFY);
|
|
169
|
+
}
|
|
170
|
+
const request = {
|
|
171
|
+
v: 1, request_id: newRequestId(), session: `pid:${pid}`,
|
|
172
|
+
event: parsed.kind === 'session-start' ? 'session-start' : parsed.event,
|
|
173
|
+
...(parsed.kind === 'skill' ? { skill: parsed.skill } : {}),
|
|
174
|
+
};
|
|
175
|
+
const answer = await (deps.ask ?? askService)(cfg.socket, request, cfg.clientDeadlineMs, cfg.rootUid);
|
|
176
|
+
if (parsed.kind === 'session-start')
|
|
177
|
+
return OK; // never blocks; an unknown session is denied by the service later
|
|
178
|
+
const result = answer.ok ? answer.result : { kind: 'parse-failure' };
|
|
179
|
+
if (decideAction(result, mode) !== 'deny')
|
|
180
|
+
return OK;
|
|
181
|
+
return block(kind, result.kind === 'verdict' && result.verdict !== 'UNVERIFIABLE' ? notApproved(result.verdict) : COULD_NOT_VERIFY);
|
|
182
|
+
};
|
|
183
|
+
let timer;
|
|
184
|
+
const timeout = new Promise((resolve) => {
|
|
185
|
+
timer = setTimeout(() => resolve(fail(COULD_NOT_VERIFY)), cfg?.selfDeadlineMs ?? DEFAULT_SELF_DEADLINE_MS);
|
|
186
|
+
});
|
|
187
|
+
try {
|
|
188
|
+
return await Promise.race([work().catch(() => fail(COULD_NOT_VERIFY)), timeout]);
|
|
189
|
+
}
|
|
190
|
+
finally {
|
|
191
|
+
clearTimeout(timer);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { type GateRequest, type GateResult } from '../contract.ts';
|
|
2
|
+
export type ClientFailure = 'no-answer' | 'late' | 'malformed' | 'connect-failed';
|
|
3
|
+
export type AskResult = {
|
|
4
|
+
ok: true;
|
|
5
|
+
result: GateResult;
|
|
6
|
+
} | {
|
|
7
|
+
ok: false;
|
|
8
|
+
failure: ClientFailure;
|
|
9
|
+
};
|
|
10
|
+
export declare const MAX_ANSWER_BYTES = 4096;
|
|
11
|
+
export declare const DEFAULT_CLIENT_DEADLINE_MS = 1500;
|
|
12
|
+
export declare const newRequestId: () => string;
|
|
13
|
+
export declare function askService(socketPath: string, request: GateRequest, deadlineMs?: number, rootUid?: number): Promise<AskResult>;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
// Decision-socket client shared by all harness adapters. One strict request line out, one bounded answer line in,
|
|
2
|
+
// its own deadline. It never throws for transport or parse problems; the adapter turns any failure into a deny
|
|
3
|
+
// (service.ts ADAPTER CONTRACT).
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { lstat } from 'node:fs/promises';
|
|
6
|
+
import net from 'node:net';
|
|
7
|
+
import { parseGateResult, serializeGateRequest } from "../contract.js";
|
|
8
|
+
export const MAX_ANSWER_BYTES = 4096;
|
|
9
|
+
export const DEFAULT_CLIENT_DEADLINE_MS = 1500;
|
|
10
|
+
export const newRequestId = () => randomBytes(16).toString('hex');
|
|
11
|
+
export async function askService(socketPath, request, deadlineMs = DEFAULT_CLIENT_DEADLINE_MS, rootUid = 0) {
|
|
12
|
+
// Right before connecting: the path must be a socket owned by the service's uid (not a planted file or symlink).
|
|
13
|
+
const st = await lstat(socketPath).catch(() => undefined);
|
|
14
|
+
if (!st || !st.isSocket() || st.uid !== rootUid)
|
|
15
|
+
return { ok: false, failure: 'connect-failed' };
|
|
16
|
+
return new Promise((resolve) => {
|
|
17
|
+
let done = false;
|
|
18
|
+
let connected = false;
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let size = 0;
|
|
21
|
+
const sock = net.connect(socketPath);
|
|
22
|
+
const finish = (r) => {
|
|
23
|
+
if (done)
|
|
24
|
+
return;
|
|
25
|
+
done = true;
|
|
26
|
+
clearTimeout(timer);
|
|
27
|
+
sock.destroy();
|
|
28
|
+
resolve(r);
|
|
29
|
+
};
|
|
30
|
+
const timer = setTimeout(() => finish({ ok: false, failure: connected ? 'late' : 'connect-failed' }), deadlineMs);
|
|
31
|
+
const parse = (line) => {
|
|
32
|
+
try {
|
|
33
|
+
finish({ ok: true, result: parseGateResult(line, request.request_id) });
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
finish({ ok: false, failure: 'malformed' });
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
sock.on('connect', () => { connected = true; sock.write(`${serializeGateRequest(request)}\n`); });
|
|
40
|
+
sock.on('error', () => finish({ ok: false, failure: connected ? 'no-answer' : 'connect-failed' }));
|
|
41
|
+
sock.on('data', (d) => {
|
|
42
|
+
chunks.push(d);
|
|
43
|
+
size += d.length;
|
|
44
|
+
const all = Buffer.concat(chunks);
|
|
45
|
+
const nl = all.indexOf(0x0a);
|
|
46
|
+
if (nl >= 0)
|
|
47
|
+
return parse(all.subarray(0, nl));
|
|
48
|
+
if (size > MAX_ANSWER_BYTES)
|
|
49
|
+
finish({ ok: false, failure: 'malformed' });
|
|
50
|
+
});
|
|
51
|
+
sock.on('close', () => {
|
|
52
|
+
if (done)
|
|
53
|
+
return;
|
|
54
|
+
finish({ ok: false, failure: size === 0 ? 'no-answer' : 'malformed' });
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// Entry point of the Codex hook: `env -i node --no-addons codex-hook.js <config.json> <enforce|shadow>`.
|
|
2
|
+
// The config, socket directory and socket must be root-owned; see codex.ts.
|
|
3
|
+
import { runHook } from "./codex.js";
|
|
4
|
+
import { hookMain } from "./hook-main.js";
|
|
5
|
+
await hookMain(process.argv.slice(2, 4), {}, runHook);
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { Mode } from '../../policy.ts';
|
|
2
|
+
export interface CodexRequirementsInput {
|
|
3
|
+
mode: Mode;
|
|
4
|
+
nodePath: string;
|
|
5
|
+
hookEntry: string;
|
|
6
|
+
configPath: string;
|
|
7
|
+
hookTimeoutSec: number;
|
|
8
|
+
/** Must match the hook config's self_deadline_ms; the host timeout has to outlast it by at least 1 s. */
|
|
9
|
+
selfDeadlineMs: number;
|
|
10
|
+
envPath?: string;
|
|
11
|
+
/**
|
|
12
|
+
* Absolute fixed user Skill roots, supplied by the installer, per user: <home>/.codex/skills, <home>/.codex/skills/.system
|
|
13
|
+
* (bundled system Skills) and <home>/.agents/skills (the generator reads no env, so it cannot find $CODEX_HOME). These feed
|
|
14
|
+
* only deny_read; the adapter derives its own scan roots from the host's environment, so listing them in the adapter
|
|
15
|
+
* config's `skill_roots` is optional.
|
|
16
|
+
*/
|
|
17
|
+
userSkillRoots: string[];
|
|
18
|
+
}
|
|
19
|
+
export declare function codexRequirementsToml(input: CodexRequirementsInput): string;
|
|
@@ -0,0 +1,56 @@
|
|
|
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.
|
|
5
|
+
//
|
|
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.
|
|
13
|
+
// * 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).
|
|
25
|
+
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
|
|
27
|
+
const q = (s) => `"${s}"`;
|
|
28
|
+
export function codexRequirementsToml(input) {
|
|
29
|
+
const { mode, nodePath, hookEntry, configPath, hookTimeoutSec, selfDeadlineMs, userSkillRoots } = input;
|
|
30
|
+
const envPath = input.envPath ?? '/usr/bin/env';
|
|
31
|
+
for (const p of [envPath, nodePath, hookEntry, configPath, ...userSkillRoots])
|
|
32
|
+
if (!path.isAbsolute(p) || !SAFE_PATH.test(p) || p.endsWith('/'))
|
|
33
|
+
throw new Error('paths must be absolute, shell-safe and without a trailing slash');
|
|
34
|
+
if (mode !== 'enforce' && mode !== 'shadow')
|
|
35
|
+
throw new Error('mode must be enforce or shadow');
|
|
36
|
+
if (!Number.isInteger(hookTimeoutSec) || hookTimeoutSec < 1 || hookTimeoutSec > 600)
|
|
37
|
+
throw new Error('hookTimeoutSec must be an integer in 1..600');
|
|
38
|
+
if (!Number.isInteger(selfDeadlineMs) || selfDeadlineMs < 1 || hookTimeoutSec * 1000 < selfDeadlineMs + 1000)
|
|
39
|
+
throw new Error('hookTimeoutSec * 1000 must be at least selfDeadlineMs + 1000');
|
|
40
|
+
const command = q(`${envPath} -i ${nodePath} --no-addons ${hookEntry} ${configPath} ${mode}`); // env -i: no NODE_OPTIONS etc.
|
|
41
|
+
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.',
|
|
46
|
+
];
|
|
47
|
+
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');
|
|
49
|
+
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(', ')}]`);
|
|
51
|
+
}
|
|
52
|
+
lines.push('', '# [cx0.1] managed hooks; Codex needs managed_dir (without it the hooks are ignored).', '[hooks]', `managed_dir = ${q(path.dirname(hookEntry))}`);
|
|
53
|
+
for (const [event, matcher] of [['SessionStart', false], ['UserPromptSubmit', false], ['PreToolUse', true]])
|
|
54
|
+
lines.push('', `[[hooks.${event}]]`, ...(matcher ? ['matcher = "*"'] : []), `[[hooks.${event}.hooks]]`, 'type = "command"', `command = ${command}`, `timeout = ${hookTimeoutSec}`);
|
|
55
|
+
return `${lines.join('\n')}\n`;
|
|
56
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { type HookDeps, type HookOutcome } from './claude-code.ts';
|
|
2
|
+
export declare const DEFAULT_ADMIN_ROOT = "/etc/codex/skills";
|
|
3
|
+
export declare function extractMentions(text: string, links?: string[], plain?: Set<string>, linkNames?: string[]): Set<string>;
|
|
4
|
+
/** What the adapter learns of the host's environment (values are never logged). */
|
|
5
|
+
export interface HostEnv {
|
|
6
|
+
codexHome?: string;
|
|
7
|
+
home?: string;
|
|
8
|
+
}
|
|
9
|
+
/** Reads CODEX_HOME and HOME from /proc/<pid>/environ (first occurrence, as getenv). Throws on any problem. */
|
|
10
|
+
export declare function readProcEnviron(pid: number): Promise<HostEnv>;
|
|
11
|
+
/** Codex adapter dependencies: the shared hook ones plus a reader of the host's environment (tests inject it). */
|
|
12
|
+
export interface CodexDeps extends HookDeps {
|
|
13
|
+
readHostEnv?: (pid: number) => Promise<HostEnv>;
|
|
14
|
+
}
|
|
15
|
+
/** Never throws and never outlives the self-deadline. */
|
|
16
|
+
export declare function runHook(argv: readonly string[], deps: CodexDeps): Promise<HookOutcome>;
|